repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
30
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-06-13 10:24:29
hints_text
stringlengths
0
228k
base_commit
stringlengths
40
40
test_instructions
stringlengths
0
232k
filenames
listlengths
0
300
juspay/hyperswitch
juspay__hyperswitch-7904
Bug: [FEATURE] Tokenization service ### Feature Description Need of generic tokenization service is required which can be used to tokenize any data which could be used by the consumer in various other services, one of the usecases is proxy payments ### Possible Implementation Use the locker to store the tokenized data and give out reference to that data to user through which it can be used in any place. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/api-reference-v2/api-reference/tokenization/tokenization--create.mdx b/api-reference-v2/api-reference/tokenization/tokenization--create.mdx new file mode 100644 index 00000000000..a0002736185 --- /dev/null +++ b/api-reference-v2/api-reference/tokenization/tokenization--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/tokenize +--- \ No newline at end of file diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index e56b9d684ec..8c49d3dd708 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -146,6 +146,10 @@ { "group": "Proxy", "pages": ["api-reference/proxy/proxy"] + }, + { + "group": "Tokenization", + "pages": ["api-reference/tokenization/tokenization--create"] } ], "footerSocials": { diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 00e3e7bc4ff..2347c6f9f49 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3532,6 +3532,67 @@ } ] } + }, + "/v2/tokenize": { + "post": { + "tags": [ + "Tokenization" + ], + "operationId": "create_token_vault_api", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenericTokenizationRequest" + }, + "examples": { + "Create a token with customer_id": { + "value": { + "customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8", + "token_request": { + "payment_method_data": { + "card": { + "card_holder_name": "test name" + } + } + } + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Token created successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenericTokenizationResponse" + } + } + } + }, + "400": { + "description": "Invalid request" + }, + "401": { + "description": "Unauthorized" + }, + "500": { + "description": "Internal server error" + } + }, + "security": [ + { + "ephemeral_key": [] + }, + { + "api_key": [] + } + ] + } } }, "components": { @@ -11032,6 +11093,50 @@ } } }, + "GenericTokenizationRequest": { + "type": "object", + "required": [ + "customer_id", + "token_request" + ], + "properties": { + "customer_id": { + "type": "string", + "description": "Customer ID for which the tokenization is requested", + "example": "12345_cus_01926c58bc6e77c09e809964e72af8c8" + }, + "token_request": { + "type": "object", + "description": "Request for tokenization which contains the data to be tokenized" + } + } + }, + "GenericTokenizationResponse": { + "type": "object", + "required": [ + "id", + "created_at", + "flag" + ], + "properties": { + "id": { + "type": "string", + "description": "Unique identifier returned by the tokenization service", + "example": "12345_tok_01926c58bc6e77c09e809964e72af8c8" + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Created time of the tokenization id", + "example": "2024-02-24T11:04:09.922Z" + }, + "flag": { + "type": "string", + "description": "Status of the tokenization id created", + "example": "enabled" + } + } + }, "GiftCardAdditionalData": { "oneOf": [ { @@ -16595,6 +16700,10 @@ "example": 900, "nullable": true, "minimum": 0 + }, + "tokenization_data": { + "description": "Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data", + "nullable": true } } }, @@ -16640,6 +16749,10 @@ ], "nullable": true }, + "tokenization_data": { + "description": "Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data", + "nullable": true + }, "expires_at": { "type": "string", "format": "date-time", @@ -16678,6 +16791,12 @@ }, "description": "The payment method that was created using this payment method session", "nullable": true + }, + "associated_token_id": { + "type": "string", + "description": "The token-id created if there is tokenization_data present", + "example": "12345_tok_01926c58bc6e77c09e809964e72af8c8", + "nullable": true } } }, @@ -16941,6 +17060,10 @@ } ], "nullable": true + }, + "tokenization_data": { + "description": "Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data", + "nullable": true } } }, diff --git a/config/development.toml b/config/development.toml index 7deb3b46992..039bd7c274b 100644 --- a/config/development.toml +++ b/config/development.toml @@ -84,28 +84,8 @@ redis_lock_timeout_in_seconds = 100 redis_ttl_in_seconds = 172800 [jwekey] -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_encryption_key = "" +rust_locker_encryption_key = "" vault_private_key = "" tunnel_private_key = "" diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 120e9121388..32a798c3c0b 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -17,13 +17,14 @@ olap = [] openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"] recon = [] v1 = ["common_utils/v1"] -v2 = ["common_types/v2", "common_utils/v2", "customer_v2", "refunds_v2"] +v2 = ["common_types/v2", "common_utils/v2", "customer_v2", "refunds_v2", "tokenization_v2"] customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2", "dep:reqwest"] refunds_v2 = [] dynamic_routing = [] control_center_theme = ["dep:actix-web", "dep:actix-multipart"] revenue_recovery = [] +tokenization_v2 = ["common_utils/tokenization_v2"] [dependencies] actix-multipart = { version = "0.6.1", optional = true } diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 973bdea9eef..e0e57050c4e 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -22,6 +22,8 @@ use common_utils::{ }; use crate::customers::CustomerListRequest; +#[cfg(feature = "tokenization_v2")] +use crate::tokenization; #[allow(unused_imports)] use crate::{ admin::*, @@ -228,3 +230,8 @@ impl ApiEventMetric for PaymentMethodSessionResponse { }) } } +#[cfg(feature = "tokenization_v2")] +impl ApiEventMetric for tokenization::GenericTokenizationRequest {} + +#[cfg(feature = "tokenization_v2")] +impl ApiEventMetric for tokenization::GenericTokenizationResponse {} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index fa3c34db930..a77baf7d942 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -40,6 +40,8 @@ pub mod refunds; pub mod relay; pub mod routing; pub mod surcharge_decision_configs; +#[cfg(feature = "tokenization_v2")] +pub mod tokenization; pub mod user; pub mod user_role; pub mod verifications; diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 6e9a174c9f6..92761192d1c 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -2861,6 +2861,10 @@ pub struct PaymentMethodSessionRequest { /// If not provided, the session will expire in 15 minutes #[schema(example = 900, default = 900)] pub expires_in: Option<u32>, + + /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data + #[schema(value_type = Option<serde_json::Value>)] + pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] @@ -2877,6 +2881,10 @@ pub struct PaymentMethodsSessionUpdateRequest { /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + + /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data + #[schema(value_type = Option<serde_json::Value>)] + pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] @@ -2941,6 +2949,10 @@ pub struct PaymentMethodSessionResponse { #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data + #[schema(value_type = Option<serde_json::Value>)] + pub tokenization_data: Option<pii::SecretSerdeValue>, + /// 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")] @@ -2966,6 +2978,10 @@ pub struct PaymentMethodSessionResponse { /// The payment method that was created using this payment method session #[schema(value_type = Option<Vec<String>>)] pub associated_payment_methods: Option<Vec<id_type::GlobalPaymentMethodId>>, + + /// The token-id created if there is tokenization_data present + #[schema(value_type = Option<String>, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] + pub associated_token_id: Option<id_type::GlobalTokenId>, } #[cfg(feature = "v2")] diff --git a/crates/api_models/src/tokenization.rs b/crates/api_models/src/tokenization.rs new file mode 100644 index 00000000000..5ee044ec1fb --- /dev/null +++ b/crates/api_models/src/tokenization.rs @@ -0,0 +1,30 @@ +use common_enums; +use common_utils::id_type::{GlobalCustomerId, GlobalTokenId}; +use masking::Secret; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; +use utoipa::{schema, ToSchema}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct GenericTokenizationResponse { + /// Unique identifier returned by the tokenization service + #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] + pub id: GlobalTokenId, + /// Created time of the tokenization id + #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] + pub created_at: PrimitiveDateTime, + /// Status of the tokenization id created + #[schema(value_type = String,example = "enabled")] + pub flag: common_enums::TokenizationFlag, +} +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct GenericTokenizationRequest { + /// Customer ID for which the tokenization is requested + #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] + pub customer_id: GlobalCustomerId, + /// Request for tokenization which contains the data to be tokenized + #[schema(value_type = Object,example = json!({ "city": "NY", "unit": "245" }))] + pub token_request: masking::Secret<serde_json::Value>, +} diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index b3ab41b020a..0f0064414ca 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -29,7 +29,7 @@ pub mod diesel_exports { DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, - DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbTokenizationFlag as TokenizationFlag, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } @@ -8299,6 +8299,28 @@ pub enum CryptoPadding { ZeroPadding, } +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum TokenizationFlag { + /// Token is active and can be used for payments + Enabled, + /// Token is inactive and cannot be used for payments + Disabled, +} + /// The type of token data to fetch for get-token endpoint #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/common_types/Cargo.toml b/crates/common_types/Cargo.toml index 3f49f546a71..97695cb87d3 100644 --- a/crates/common_types/Cargo.toml +++ b/crates/common_types/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true default = [] v1 = ["common_utils/v1"] v2 = ["common_utils/v2"] +tokenization_v2 = ["common_utils/tokenization_v2"] [dependencies] diesel = "2.2.3" diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 4f4322c3ca3..43f28817c7e 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -23,6 +23,7 @@ v2 = [] customer_v2 = [] payment_methods_v2 = [] crypto_openssl = ["dep:openssl"] +tokenization_v2 = [] [dependencies] async-trait = { version = "0.1.79", optional = true } diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index e3eba81b12f..bdbaa1eae6c 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -179,6 +179,10 @@ pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600; /// SOAP 1.1 Envelope Namespace pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/"; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +/// Length of generated tokens +pub const TOKEN_LENGTH: usize = 32; + /// The tag name used for identifying the host in metrics. pub const METRICS_HOST_TAG_NAME: &str = "host"; diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index f7a068b8e49..5ba16ee2c42 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -121,6 +121,10 @@ pub enum ApiEventsType { PaymentMethodSession { payment_method_session_id: id_type::GlobalPaymentMethodSessionId, }, + #[cfg(feature = "v2")] + Token { + token_id: Option<id_type::GlobalTokenId>, + }, ProcessTracker, } diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 30b6a3888da..34a3844e76b 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -34,6 +34,7 @@ pub use self::global_id::{ payment::{GlobalAttemptId, GlobalPaymentId}, payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId}, refunds::GlobalRefundId, + token::GlobalTokenId, CellId, }; pub use self::{ diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs index bb296d7ef1a..b9ed173ce3e 100644 --- a/crates/common_utils/src/id_type/global_id.rs +++ b/crates/common_utils/src/id_type/global_id.rs @@ -2,6 +2,7 @@ pub(super) mod customer; pub(super) mod payment; pub(super) mod payment_methods; pub(super) mod refunds; +pub(super) mod token; use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types}; use error_stack::ResultExt; @@ -27,6 +28,7 @@ pub(crate) enum GlobalEntity { PaymentMethod, Refund, PaymentMethodSession, + Token, } impl GlobalEntity { @@ -38,6 +40,7 @@ impl GlobalEntity { Self::Attempt => "att", Self::Refund => "ref", Self::PaymentMethodSession => "pms", + Self::Token => "tok", } } } diff --git a/crates/common_utils/src/id_type/global_id/token.rs b/crates/common_utils/src/id_type/global_id/token.rs new file mode 100644 index 00000000000..929c03f0959 --- /dev/null +++ b/crates/common_utils/src/id_type/global_id/token.rs @@ -0,0 +1,37 @@ +use error_stack::ResultExt; + +use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types}; + +crate::global_id_type!( + GlobalTokenId, + "A global id that can be used to identify a token. + +The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`. + +Example: `cell1_tok_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`" +); + +// Database related implementations so that this field can be used directly in the database tables +crate::impl_queryable_id_type!(GlobalTokenId); +crate::impl_to_sql_from_sql_global_id_type!(GlobalTokenId); + +impl GlobalTokenId { + /// Get string representation of the id + pub fn get_string_repr(&self) -> &str { + self.0.get_string_repr() + } + + /// Generate a new GlobalTokenId from a cell id + pub fn generate(cell_id: &crate::id_type::CellId) -> Self { + let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Token); + Self(global_id) + } +} + +impl crate::events::ApiEventMetric for GlobalTokenId { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::Token { + token_id: Some(self.clone()), + }) + } +} diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index fd0c935035f..759329ba327 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -333,3 +333,10 @@ mod nanoid_tests { assert!(ref_id.is_ok()) } } + +/// Module for tokenization-related functionality +/// +/// This module provides types and functions for handling tokenized payment data, +/// including response structures and token generation utilities. +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub mod tokenization; diff --git a/crates/common_utils/src/tokenization.rs b/crates/common_utils/src/tokenization.rs new file mode 100644 index 00000000000..aa0f3dda8c1 --- /dev/null +++ b/crates/common_utils/src/tokenization.rs @@ -0,0 +1,21 @@ +//! Module for tokenization-related functionality +//! +//! This module provides types and functions for handling tokenized payment data, +//! including response structures and token generation utilities. + +use common_enums::ApiVersion; +use diesel; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::{consts::TOKEN_LENGTH, id_type::GlobalTokenId}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +/// Generates a new token string +/// +/// # Returns +/// A randomly generated token string of length `TOKEN_LENGTH` +pub fn generate_token() -> String { + use nanoid::nanoid; + nanoid!(TOKEN_LENGTH) +} diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index e10428c5daf..8f7c5f92908 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -15,6 +15,7 @@ v2 = ["common_utils/v2", "common_types/v2"] customer_v2 = [] payment_methods_v2 = [] refunds_v2 = [] +tokenization_v2 = [] [dependencies] async-bb8-diesel = "0.2.1" diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index bd710dfdd6b..39ce33a5130 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -23,13 +23,16 @@ pub mod diesel_exports { DbRevenueRecoveryAlgorithmType as RevenueRecoveryAlgorithmType, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, - DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, - DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, - DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbTokenizationFlag as TokenizationFlag, DbTotpStatus as TotpStatus, + DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion, + DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } + pub use common_enums::*; use common_utils::pii; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub use common_utils::tokenization; use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Jsonb}; use router_derive::diesel_enum; use time::PrimitiveDateTime; diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index e5c7aea9d56..e34e7e552d8 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -140,3 +140,6 @@ pub(crate) mod metrics { counter_metric!(DATABASE_CALLS_COUNT, GLOBAL_METER); histogram_metric_f64!(DATABASE_CALL_TIME, GLOBAL_METER); } + +#[cfg(feature = "tokenization_v2")] +pub mod tokenization; diff --git a/crates/diesel_models/src/mod.rs b/crates/diesel_models/src/mod.rs new file mode 100644 index 00000000000..3cdc13b0c8a --- /dev/null +++ b/crates/diesel_models/src/mod.rs @@ -0,0 +1,2 @@ +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub mod tokenization; \ No newline at end of file diff --git a/crates/diesel_models/src/payment_methods_session.rs b/crates/diesel_models/src/payment_methods_session.rs index 250fd44bdbf..037214387a7 100644 --- a/crates/diesel_models/src/payment_methods_session.rs +++ b/crates/diesel_models/src/payment_methods_session.rs @@ -1,3 +1,5 @@ +use common_utils::pii; + #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodSession { @@ -6,11 +8,13 @@ pub struct PaymentMethodSession { pub billing: Option<common_utils::encryption::Encryption>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub tokenization_data: Option<pii::SecretSerdeValue>, pub return_url: Option<common_utils::types::Url>, #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_at: time::PrimitiveDateTime, pub associated_payment_methods: Option<Vec<common_utils::id_type::GlobalPaymentMethodId>>, pub associated_payment: Option<common_utils::id_type::GlobalPaymentId>, + pub associated_token_id: Option<common_utils::id_type::GlobalTokenId>, } #[cfg(feature = "v2")] @@ -22,10 +26,12 @@ impl PaymentMethodSession { billing, psp_tokenization, network_tokenization, + tokenization_data, expires_at, return_url, associated_payment_methods, associated_payment, + associated_token_id, } = self; Self { @@ -34,10 +40,12 @@ impl PaymentMethodSession { billing: update_session.billing.or(billing), psp_tokenization: update_session.psp_tokenization.or(psp_tokenization), network_tokenization: update_session.network_tokenization.or(network_tokenization), + tokenization_data: update_session.tokenzation_data.or(tokenization_data), expires_at, return_url, associated_payment_methods, associated_payment, + associated_token_id, } } } @@ -47,4 +55,5 @@ pub struct PaymentMethodsSessionUpdateInternal { pub billing: Option<common_utils::encryption::Encryption>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub tokenzation_data: Option<masking::Secret<serde_json::Value>>, } diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 9a886c473cd..7c8831b3811 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -39,6 +39,8 @@ pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; +#[cfg(feature = "tokenization_v2")] +pub mod tokenization; pub mod unified_translations; pub mod user; pub mod user_authentication_method; diff --git a/crates/diesel_models/src/query/tokenization.rs b/crates/diesel_models/src/query/tokenization.rs new file mode 100644 index 00000000000..0d818eb6636 --- /dev/null +++ b/crates/diesel_models/src/query/tokenization.rs @@ -0,0 +1,46 @@ +#[cfg(feature = "v2")] +use common_enums; +#[cfg(feature = "v2")] +use common_utils::{ + id_type::{GlobalTokenId, MerchantId}, + tokenization as tokenization_utils, +}; +#[cfg(feature = "v2")] +use diesel::{ + associations::HasTable, + deserialize::FromSqlRow, + expression::AsExpression, + pg::Pg, + serialize::{Output, ToSql}, + sql_types::{Jsonb, Text}, + AsChangeset, Identifiable, Insertable, Queryable, Selectable, +}; +#[cfg(feature = "v2")] +use serde::{Deserialize, Serialize}; +#[cfg(feature = "v2")] +use time::PrimitiveDateTime; + +#[cfg(feature = "v2")] +use crate::{ + query::generics, schema_v2::tokenization, tokenization as tokenization_diesel, PgPooledConn, + StorageResult, +}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl tokenization_diesel::Tokenization { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { + generics::generic_insert(conn, self).await + } + + pub async fn find_by_id( + conn: &PgPooledConn, + id: &common_utils::id_type::GlobalTokenId, + ) -> StorageResult<Self> { + use diesel::ExpressionMethods; + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + tokenization::dsl::id.eq(id.to_owned()), + ) + .await + } +} diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 195b0fa4298..b6d8aedfa92 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1379,6 +1379,26 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + tokenization (id) { + #[max_length = 64] + id -> Varchar, + #[max_length = 255] + merchant_id -> Varchar, + #[max_length = 64] + customer_id -> Varchar, + created_at -> Timestamp, + updated_at -> Timestamp, + #[max_length = 255] + locker_id -> Varchar, + flag -> TokenizationFlag, + version -> ApiVersion, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1532,6 +1552,7 @@ diesel::allow_tables_to_appear_in_same_query!( roles, routing_algorithm, themes, + tokenization, unified_translations, user_authentication_methods, user_key_store, diff --git a/crates/diesel_models/src/tokenization.rs b/crates/diesel_models/src/tokenization.rs new file mode 100644 index 00000000000..50a97e62c90 --- /dev/null +++ b/crates/diesel_models/src/tokenization.rs @@ -0,0 +1,61 @@ +#[cfg(feature = "v2")] +use common_enums; +#[cfg(feature = "v2")] +use common_utils::{ + id_type::{GlobalTokenId, MerchantId}, + tokenization as tokenization_utils, +}; +#[cfg(feature = "v2")] +use diesel::{ + associations::HasTable, + deserialize::FromSqlRow, + expression::AsExpression, + pg::Pg, + serialize::{Output, ToSql}, + sql_types::{Jsonb, Text}, + AsChangeset, Identifiable, Insertable, Queryable, Selectable, +}; +#[cfg(feature = "v2")] +use serde::{Deserialize, Serialize}; +#[cfg(feature = "v2")] +use time::PrimitiveDateTime; + +#[cfg(feature = "v2")] +use crate::{query::generics, schema_v2::tokenization, PgPooledConn, StorageResult}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Identifiable, Insertable, Queryable)] +#[diesel(table_name = tokenization)] +pub struct Tokenization { + pub id: common_utils::id_type::GlobalTokenId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub created_at: PrimitiveDateTime, + pub updated_at: PrimitiveDateTime, + pub locker_id: String, + pub flag: common_enums::enums::TokenizationFlag, + pub version: common_enums::enums::ApiVersion, +} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Insertable)] +#[diesel(table_name = tokenization)] +pub struct TokenizationNew { + pub id: common_utils::id_type::GlobalTokenId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub locker_id: String, + pub created_at: PrimitiveDateTime, + pub updated_at: PrimitiveDateTime, + pub version: common_enums::enums::ApiVersion, + pub flag: common_enums::enums::TokenizationFlag, +} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, AsChangeset)] +#[diesel(table_name = tokenization)] +pub struct TokenizationUpdate { + pub updated_at: Option<PrimitiveDateTime>, + pub version: Option<common_enums::enums::ApiVersion>, + pub flag: Option<common_enums::enums::TokenizationFlag>, +} diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index bf463616c6d..696cc22783d 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -9,6 +9,7 @@ use diesel::{ }; use masking::{Secret, WithType}; use serde::{self, Deserialize, Serialize}; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Jsonb)] pub struct OrderDetailsWithAmount { diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index e889d2c16c3..a3a2fc8e10c 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -17,6 +17,7 @@ v2 = ["api_models/v2", "diesel_models/v2", "common_utils/v2", "common_types/v2"] v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1", "common_types/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"] +tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2"] refunds_v2 = ["api_models/refunds_v2"] dummy_connector = [] revenue_recovery= [] diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 1d24e3eedbc..eb37f8f45da 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -34,6 +34,8 @@ pub mod router_flow_types; pub mod router_request_types; pub mod router_response_types; pub mod routing; +#[cfg(feature = "tokenization_v2")] +pub mod tokenization; pub mod type_encryption; pub mod types; pub mod vault; diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index c2be89a97e6..2f135ca881e 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -36,7 +36,11 @@ use crate::{ #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct VaultId(String); -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[cfg(any( + feature = "v2", + feature = "payment_methods_v2", + feature = "tokenization_v2" +))] impl VaultId { pub fn get_string_repr(&self) -> &String { &self.0 @@ -625,9 +629,11 @@ pub struct PaymentMethodSession { pub return_url: Option<common_utils::types::Url>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub tokenization_data: Option<pii::SecretSerdeValue>, pub expires_at: PrimitiveDateTime, pub associated_payment_methods: Option<Vec<id_type::GlobalPaymentMethodId>>, pub associated_payment: Option<id_type::GlobalPaymentId>, + pub associated_token_id: Option<id_type::GlobalTokenId>, } #[cfg(feature = "v2")] @@ -642,10 +648,12 @@ impl super::behaviour::Conversion for PaymentMethodSession { billing: self.billing.map(|val| val.into()), psp_tokenization: self.psp_tokenization, network_tokenization: self.network_tokenization, + tokenization_data: self.tokenization_data, expires_at: self.expires_at, associated_payment_methods: self.associated_payment_methods, associated_payment: self.associated_payment, return_url: self.return_url, + associated_token_id: self.associated_token_id, }) } @@ -694,10 +702,12 @@ impl super::behaviour::Conversion for PaymentMethodSession { billing, psp_tokenization: storage_model.psp_tokenization, network_tokenization: storage_model.network_tokenization, + tokenization_data: storage_model.tokenization_data, expires_at: storage_model.expires_at, associated_payment_methods: storage_model.associated_payment_methods, associated_payment: storage_model.associated_payment, return_url: storage_model.return_url, + associated_token_id: storage_model.associated_token_id, }) } .await @@ -713,10 +723,12 @@ impl super::behaviour::Conversion for PaymentMethodSession { billing: self.billing.map(|val| val.into()), psp_tokenization: self.psp_tokenization, network_tokenization: self.network_tokenization, + tokenization_data: self.tokenization_data, expires_at: self.expires_at, associated_payment_methods: self.associated_payment_methods, associated_payment: self.associated_payment, return_url: self.return_url, + associated_token_id: self.associated_token_id, }) } } @@ -878,6 +890,7 @@ pub enum PaymentMethodsSessionUpdateEnum { billing: Option<Encryptable<Address>>, psp_tokenization: Option<common_types::payment_methods::PspTokenization>, network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + tokenization_data: Option<pii::SecretSerdeValue>, }, } @@ -889,10 +902,12 @@ impl From<PaymentMethodsSessionUpdateEnum> for PaymentMethodsSessionUpdateIntern billing, psp_tokenization, network_tokenization, + tokenization_data, } => Self { billing, psp_tokenization, network_tokenization, + tokenization_data, }, } } @@ -907,10 +922,12 @@ impl PaymentMethodSession { billing, psp_tokenization, network_tokenization, + tokenization_data, expires_at, return_url, associated_payment_methods, associated_payment, + associated_token_id, } = self; Self { id, @@ -918,10 +935,12 @@ impl PaymentMethodSession { billing: update_session.billing.or(billing), psp_tokenization: update_session.psp_tokenization.or(psp_tokenization), network_tokenization: update_session.network_tokenization.or(network_tokenization), + tokenization_data: update_session.tokenization_data.or(tokenization_data), expires_at, return_url, associated_payment_methods, associated_payment, + associated_token_id, } } } @@ -931,6 +950,7 @@ pub struct PaymentMethodsSessionUpdateInternal { pub billing: Option<Encryptable<Address>>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(all( diff --git a/crates/hyperswitch_domain_models/src/tokenization.rs b/crates/hyperswitch_domain_models/src/tokenization.rs new file mode 100644 index 00000000000..4bbdaa2fb41 --- /dev/null +++ b/crates/hyperswitch_domain_models/src/tokenization.rs @@ -0,0 +1,105 @@ +use common_enums; +use common_utils::{ + self, + errors::{CustomResult, ValidationError}, + id_type, pii, + types::{keymanager, MinorUnit}, +}; +use diesel_models::tokenization; +use masking::{ExposeInterface, Secret}; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::{merchant_key_store::MerchantKeyStore, types}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Tokenization { + pub id: common_utils::id_type::GlobalTokenId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub locker_id: String, + pub created_at: PrimitiveDateTime, + pub updated_at: PrimitiveDateTime, + pub flag: common_enums::TokenizationFlag, + pub version: common_enums::ApiVersion, +} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TokenizationNew { + pub id: common_utils::id_type::GlobalTokenId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub locker_id: String, + pub flag: common_enums::TokenizationFlag, + pub version: common_enums::ApiVersion, +} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TokenizationResponse { + pub token: String, + pub created_at: PrimitiveDateTime, + pub flag: common_enums::TokenizationFlag, +} + +impl From<Tokenization> for TokenizationResponse { + fn from(value: Tokenization) -> Self { + Self { + token: value.id.get_string_repr().to_string(), + created_at: value.created_at, + flag: value.flag, + } + } +} + +#[async_trait::async_trait] +impl super::behaviour::Conversion for Tokenization { + type DstType = diesel_models::tokenization::Tokenization; + type NewDstType = diesel_models::tokenization::Tokenization; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(diesel_models::tokenization::Tokenization { + id: self.id, + merchant_id: self.merchant_id, + customer_id: self.customer_id, + locker_id: self.locker_id, + created_at: self.created_at, + updated_at: self.updated_at, + version: self.version, + flag: self.flag, + }) + } + + async fn convert_back( + _state: &keymanager::KeyManagerState, + item: Self::DstType, + _key: &Secret<Vec<u8>>, + _key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> { + Ok(Self { + id: item.id, + merchant_id: item.merchant_id, + customer_id: item.customer_id, + locker_id: item.locker_id, + created_at: item.created_at, + updated_at: item.updated_at, + flag: item.flag, + version: item.version, + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(diesel_models::tokenization::Tokenization { + id: self.id, + merchant_id: self.merchant_id, + customer_id: self.customer_id, + locker_id: self.locker_id, + created_at: self.created_at, + updated_at: self.updated_at, + version: self.version, + flag: self.flag, + }) + } +} diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index 49e9cbf54f7..35e55c8cb36 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -17,6 +17,8 @@ pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface, SwitchStrat mod secret; mod strong_secret; +#[cfg(feature = "serde")] +pub use secret::JsonMaskStrategy; pub use secret::Secret; pub use strong_secret::StrongSecret; diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index ee65b1c015b..f2f519dd3ed 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -167,3 +167,258 @@ impl AsRef<[u8]> for Secret<Vec<u8>> { self.peek().as_slice() } } + +/// Strategy for masking JSON values +#[cfg(feature = "serde")] +pub enum JsonMaskStrategy {} + +#[cfg(feature = "serde")] +impl Strategy<serde_json::Value> for JsonMaskStrategy { + fn fmt(value: &serde_json::Value, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match value { + serde_json::Value::Object(map) => { + write!(f, "{{")?; + let mut first = true; + for (key, val) in map { + if !first { + write!(f, ", ")?; + } + first = false; + write!(f, "\"{}\":", key)?; + Self::fmt(val, f)?; + } + write!(f, "}}") + } + serde_json::Value::Array(arr) => { + write!(f, "[")?; + let mut first = true; + for val in arr { + if !first { + write!(f, ", ")?; + } + first = false; + Self::fmt(val, f)?; + } + write!(f, "]") + } + serde_json::Value::String(s) => { + // For strings, we show a masked version that gives a hint about the content + let masked = if s.len() <= 2 { + "**".to_string() + } else if s.len() <= 6 { + format!("{}**", &s[0..1]) + } else { + // For longer strings, show first and last character with length in between + format!( + "{}**{}**{}", + &s[0..1], + s.len() - 2, + &s[s.len() - 1..s.len()] + ) + }; + write!(f, "\"{}\"", masked) + } + serde_json::Value::Number(n) => { + // For numbers, we can show the order of magnitude + if n.is_i64() || n.is_u64() { + let num_str = n.to_string(); + let masked_num = "*".repeat(num_str.len()); + write!(f, "{}", masked_num) + } else if n.is_f64() { + // For floats, just use a generic mask + write!(f, "**.**") + } else { + write!(f, "0") + } + } + serde_json::Value::Bool(b) => { + // For booleans, we can show a hint about which one it is + write!(f, "{}", if *b { "**true" } else { "**false" }) + } + serde_json::Value::Null => write!(f, "null"), + } + } +} + +#[cfg(test)] +#[cfg(feature = "serde")] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + #[allow(clippy::expect_used)] + fn test_json_mask_strategy() { + // Create a sample JSON with different types for testing + let original = json!({ "user": { "name": "John Doe", "email": "[email protected]", "age": 35, "verified": true }, "card": { "number": "4242424242424242", "cvv": 123, "amount": 99.99 }, "tags": ["personal", "premium"], "null_value": null, "short": "hi" }); + + // Apply the JsonMaskStrategy + let secret = Secret::<_, JsonMaskStrategy>::new(original.clone()); + let masked_str = format!("{:?}", secret); + + // Get specific values from original + let original_obj = original.as_object().expect("Original should be an object"); + let user_obj = original_obj["user"] + .as_object() + .expect("User should be an object"); + let name = user_obj["name"].as_str().expect("Name should be a string"); + let email = user_obj["email"] + .as_str() + .expect("Email should be a string"); + let age = user_obj["age"].as_i64().expect("Age should be a number"); + let verified = user_obj["verified"] + .as_bool() + .expect("Verified should be a boolean"); + + let card_obj = original_obj["card"] + .as_object() + .expect("Card should be an object"); + let card_number = card_obj["number"] + .as_str() + .expect("Card number should be a string"); + let cvv = card_obj["cvv"].as_i64().expect("CVV should be a number"); + + let tags = original_obj["tags"] + .as_array() + .expect("Tags should be an array"); + let tag1 = tags + .first() + .and_then(|v| v.as_str()) + .expect("First tag should be a string"); + + // Now explicitly verify the masking patterns for each value type + + // 1. String masking - pattern: first char + ** + length - 2 + ** + last char + let expected_name_mask = format!( + "\"{}**{}**{}\"", + &name[0..1], + name.len() - 2, + &name[name.len() - 1..] + ); + let expected_email_mask = format!( + "\"{}**{}**{}\"", + &email[0..1], + email.len() - 2, + &email[email.len() - 1..] + ); + let expected_card_mask = format!( + "\"{}**{}**{}\"", + &card_number[0..1], + card_number.len() - 2, + &card_number[card_number.len() - 1..] + ); + let expected_tag1_mask = if tag1.len() <= 2 { + "\"**\"".to_string() + } else if tag1.len() <= 6 { + format!("\"{}**\"", &tag1[0..1]) + } else { + format!( + "\"{}**{}**{}\"", + &tag1[0..1], + tag1.len() - 2, + &tag1[tag1.len() - 1..] + ) + }; + let expected_short_mask = "\"**\"".to_string(); // For "hi" + + // 2. Number masking + let expected_age_mask = "*".repeat(age.to_string().len()); // Repeat * for the number of digits + let expected_cvv_mask = "*".repeat(cvv.to_string().len()); + + // 3. Boolean masking + let expected_verified_mask = if verified { "**true" } else { "**false" }; + + // Check that the masked output includes the expected masked patterns + assert!( + masked_str.contains(&expected_name_mask), + "Name not masked correctly. Expected: {}", + expected_name_mask + ); + assert!( + masked_str.contains(&expected_email_mask), + "Email not masked correctly. Expected: {}", + expected_email_mask + ); + assert!( + masked_str.contains(&expected_card_mask), + "Card number not masked correctly. Expected: {}", + expected_card_mask + ); + assert!( + masked_str.contains(&expected_tag1_mask), + "Tag not masked correctly. Expected: {}", + expected_tag1_mask + ); + assert!( + masked_str.contains(&expected_short_mask), + "Short string not masked correctly. Expected: {}", + expected_short_mask + ); + + assert!( + masked_str.contains(&expected_age_mask), + "Age not masked correctly. Expected: {}", + expected_age_mask + ); + assert!( + masked_str.contains(&expected_cvv_mask), + "CVV not masked correctly. Expected: {}", + expected_cvv_mask + ); + + assert!( + masked_str.contains(expected_verified_mask), + "Boolean not masked correctly. Expected: {}", + expected_verified_mask + ); + + // Check structure preservation + assert!( + masked_str.contains("\"user\""), + "Structure not preserved - missing user object" + ); + assert!( + masked_str.contains("\"card\""), + "Structure not preserved - missing card object" + ); + assert!( + masked_str.contains("\"tags\""), + "Structure not preserved - missing tags array" + ); + assert!( + masked_str.contains("\"null_value\":null"), + "Null value not preserved correctly" + ); + + // Additional security checks to ensure no original values are exposed + assert!( + !masked_str.contains(name), + "Original name value exposed in masked output" + ); + assert!( + !masked_str.contains(email), + "Original email value exposed in masked output" + ); + assert!( + !masked_str.contains(card_number), + "Original card number exposed in masked output" + ); + assert!( + !masked_str.contains(&age.to_string()), + "Original age value exposed in masked output" + ); + assert!( + !masked_str.contains(&cvv.to_string()), + "Original CVV value exposed in masked output" + ); + assert!( + !masked_str.contains(tag1), + "Original tag value exposed in masked output" + ); + assert!( + !masked_str.contains("hi"), + "Original short string value exposed in masked output" + ); + } +} diff --git a/crates/openapi/Cargo.toml b/crates/openapi/Cargo.toml index 33c48e2f0ae..2fea584e9b1 100644 --- a/crates/openapi/Cargo.toml +++ b/crates/openapi/Cargo.toml @@ -17,7 +17,7 @@ common_types = { version = "0.1.0", path = "../common_types" } router_env = { version = "0.1.0", path = "../router_env" } [features] -v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2", "api_models/refunds_v2"] +v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2", "api_models/refunds_v2", "api_models/tokenization_v2"] v1 = ["api_models/v1", "common_utils/v1"] [lints] diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 9b8387389fe..45f8e87798a 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -157,6 +157,9 @@ Never share your secret api keys. Keep them guarded and secure. // Routes for proxy routes::proxy::proxy_core, + + // Route for tokenization + routes::tokenization::create_token_vault_api, ), components(schemas( common_utils::types::MinorUnit, @@ -736,6 +739,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::proxy::ProxyResponse, api_models::proxy::TokenType, routes::payments::ForceSync, + api_models::tokenization::GenericTokenizationRequest, + api_models::tokenization::GenericTokenizationResponse, )), modifiers(&SecurityAddon) )] diff --git a/crates/openapi/src/routes.rs b/crates/openapi/src/routes.rs index 8f95de75b3f..f2298c17ee5 100644 --- a/crates/openapi/src/routes.rs +++ b/crates/openapi/src/routes.rs @@ -20,4 +20,5 @@ pub mod refunds; pub mod relay; pub mod revenue_recovery; pub mod routing; +pub mod tokenization; pub mod webhook_events; diff --git a/crates/openapi/src/routes/tokenization.rs b/crates/openapi/src/routes/tokenization.rs new file mode 100644 index 00000000000..22f1227a9c0 --- /dev/null +++ b/crates/openapi/src/routes/tokenization.rs @@ -0,0 +1,33 @@ +use serde_json::json; +use utoipa::OpenApi; + +#[cfg(feature = "v2")] +#[utoipa::path( + post, + path = "/v2/tokenize", + request_body( + content = GenericTokenizationRequest, + examples(("Create a token with customer_id" = ( + value = json!({ + "customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8", + "token_request": { + "payment_method_data": { + "card": { + "card_holder_name": "test name" + } + } + } + }) + ))) + ), + responses( + (status = 200, description = "Token created successfully", body = GenericTokenizationResponse), + (status = 400, description = "Invalid request"), + (status = 401, description = "Unauthorized"), + (status = 500, description = "Internal server error") + ), + tag = "Tokenization", + operation_id = "create_token_vault_api", + security(("ephemeral_key" = []),("api_key" = [])) +)] +pub async fn create_token_vault_api() {} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 06fd5ce67b1..9f6d807189d 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,13 +33,14 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] -v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","scheduler/v2", "refunds_v2", "euclid/v2", "payment_methods/v2"] +v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","scheduler/v2", "refunds_v2", "euclid/v2", "payment_methods/v2", "tokenization_v2"] v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1","scheduler/v1", "payment_methods/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery","hyperswitch_connectors/revenue_recovery"] refunds_v2 = ["api_models/refunds_v2", "diesel_models/refunds_v2", "storage_impl/refunds_v2", "hyperswitch_domain_models/refunds_v2"] +tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2", "storage_impl/tokenization_v2"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request. @@ -48,7 +49,7 @@ partial-auth = [] [dependencies] actix-cors = "0.6.5" -actix-http = "3.6.0" +actix-http = "3.6.0" actix-multipart = "0.6.1" actix-rt = "2.9.0" actix-web = "4.5.1" @@ -128,7 +129,7 @@ common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] } common_types = { version = "0.1.0", path = "../common_types" } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store", "tokenization_v2"], default-features = false } euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } events = { version = "0.1.0", path = "../events" } external_services = { version = "0.1.0", path = "../external_services" } diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index e67c3234b19..812d23165d5 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -67,3 +67,5 @@ pub mod proxy; pub mod relay; #[cfg(feature = "v2")] pub mod revenue_recovery; + +pub mod tokenization; diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 702b81f9720..8558b43491b 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -71,7 +71,7 @@ use crate::{ configs::settings, core::{ payment_methods::transformers as pm_transforms, payments as payments_core, - utils as core_utils, + tokenization as tokenization_core, utils as core_utils, }, db::errors::ConnectorErrorExt, headers, logger, @@ -2569,10 +2569,12 @@ pub async fn payment_methods_session_create( billing, psp_tokenization: request.psp_tokenization, network_tokenization: request.network_tokenization, + tokenization_data: request.tokenization_data, expires_at, return_url: request.return_url, associated_payment_methods: None, associated_payment: None, + associated_token_id: None, }; db.insert_payment_methods_session( @@ -2589,6 +2591,7 @@ pub async fn payment_methods_session_create( payment_method_session_domain_model, client_secret.secret, None, + None, ); Ok(services::ApplicationResponse::Json(response)) @@ -2638,6 +2641,7 @@ pub async fn payment_methods_session_update( billing, psp_tokenization: request.psp_tokenization, network_tokenization: request.network_tokenization, + tokenization_data: request.tokenization_data, }; let update_state_change = db @@ -2656,6 +2660,7 @@ pub async fn payment_methods_session_update( update_state_change, Secret::new("CLIENT_SECRET_REDACTED".to_string()), None, // TODO: send associated payments response based on the expandable param + None, ); Ok(services::ApplicationResponse::Json(response)) @@ -2685,6 +2690,7 @@ pub async fn payment_methods_session_retrieve( payment_method_session_domain_model, Secret::new("CLIENT_SECRET_REDACTED".to_string()), None, // TODO: send associated payments response based on the expandable param + None, ); Ok(services::ApplicationResponse::Json(response)) @@ -2873,6 +2879,8 @@ pub async fn payment_methods_session_confirm( }) .or_else(|| payment_method_session_billing.clone()); + let customer_id = payment_method_session.customer_id.clone(); + let create_payment_method_request = get_payment_method_create_request( request .payment_method_data @@ -2881,7 +2889,7 @@ pub async fn payment_methods_session_confirm( .get_required_value("payment_method_data")?, request.payment_method_type, request.payment_method_subtype, - payment_method_session.customer_id.clone(), + customer_id.clone(), unified_billing_address.as_ref(), Some(&payment_method_session), ) @@ -2936,11 +2944,35 @@ pub async fn payment_methods_session_confirm( None => None, }; + let tokenization_response = match payment_method_session.tokenization_data.clone() { + Some(tokenization_data) => { + let tokenization_response = tokenization_core::create_vault_token_core( + state.clone(), + &merchant_context.get_merchant_account().clone(), + &merchant_context.get_merchant_key_store().clone(), + api_models::tokenization::GenericTokenizationRequest { + customer_id: customer_id.clone(), + token_request: tokenization_data, + }, + ) + .await?; + let token = match tokenization_response { + services::ApplicationResponse::Json(response) => Some(response), + _ => None, + }; + Some(token) + } + None => None, + }; + + logger::debug!(?tokenization_response, "Tokenization response"); + //TODO: update the payment method session with the payment id and payment method id let payment_method_session_response = transformers::generate_payment_method_session_response( payment_method_session, Secret::new("CLIENT_SECRET_REDACTED".to_string()), payments_response, + (tokenization_response.flatten()), ); Ok(services::ApplicationResponse::Json( diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 31ecd45e466..fd36f6d0ab7 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -1021,6 +1021,7 @@ pub fn generate_payment_method_session_response( payment_method_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, client_secret: Secret<String>, associated_payment: Option<api_models::payments::PaymentsResponse>, + tokenization_service_response: Option<api_models::tokenization::GenericTokenizationResponse>, ) -> api_models::payment_methods::PaymentMethodSessionResponse { let next_action = associated_payment .as_ref() @@ -1034,6 +1035,10 @@ pub fn generate_payment_method_session_response( }, ); + let token_id = tokenization_service_response + .as_ref() + .map(|tokenization_service_response| tokenization_service_response.id.clone()); + api_models::payment_methods::PaymentMethodSessionResponse { id: payment_method_session.id, customer_id: payment_method_session.customer_id, @@ -1043,12 +1048,14 @@ pub fn generate_payment_method_session_response( .map(From::from), psp_tokenization: payment_method_session.psp_tokenization, network_tokenization: payment_method_session.network_tokenization, + tokenization_data: payment_method_session.tokenization_data, expires_at: payment_method_session.expires_at, client_secret, next_action, return_url: payment_method_session.return_url, associated_payment_methods: payment_method_session.associated_payment_methods, authentication_details, + associated_token_id: token_id, } } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index e29527f9fe7..c545bcac503 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1355,6 +1355,30 @@ pub async fn retrieve_payment_method_from_vault_internal( Ok(stored_pm_resp) } +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[instrument(skip_all)] +pub async fn retrive_value_from_vault( + state: &routes::SessionState, + request: pm_types::VaultRetrieveRequest, +) -> CustomResult<serde_json::value::Value, errors::VaultError> { + let payload = request + .encode_to_vec() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode VaultRetrieveRequest")?; + + let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) + .await + .change_context(errors::VaultError::VaultAPIError) + .attach_printable("Call to vault failed")?; + + let stored_resp: serde_json::Value = resp + .parse_struct("VaultRetrieveResponse") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to parse data into VaultRetrieveResponse")?; + + Ok(stored_resp) +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_external( diff --git a/crates/router/src/core/tokenization.rs b/crates/router/src/core/tokenization.rs new file mode 100644 index 00000000000..44bc53c77a0 --- /dev/null +++ b/crates/router/src/core/tokenization.rs @@ -0,0 +1,156 @@ +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use std::sync::Arc; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use actix_web::{web, HttpRequest, HttpResponse}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use api_models; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use common_enums::enums; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use common_utils::{ + crypto::{DecodeMessage, EncodeMessage, GcmAes256}, + errors::CustomResult, + ext_traits::{BytesExt, Encode, StringExt}, + id_type, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use error_stack::ResultExt; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use hyperswitch_domain_models; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use masking::{JsonMaskStrategy, Secret}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use router_env::{instrument, logger, tracing, Flow}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use serde::Serialize; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use crate::{ + core::{ + errors::{self, RouterResponse, RouterResult}, + payment_methods::vault as pm_vault, + tokenization, + }, + routes::{app::StorageInterface, AppState, SessionState}, + services::{self, api as api_service, authentication as auth}, + types::{api, domain, payment_methods as pm_types}, +}; + +#[instrument(skip_all)] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub async fn create_vault_token_core( + state: SessionState, + merchant_account: &domain::MerchantAccount, + merchant_key_store: &domain::MerchantKeyStore, + req: api_models::tokenization::GenericTokenizationRequest, +) -> RouterResponse<api_models::tokenization::GenericTokenizationResponse> { + // Generate a unique vault ID + let vault_id = domain::VaultId::generate(uuid::Uuid::now_v7().to_string()); + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + let customer_id = req.customer_id.clone(); + // Create vault request + let payload = pm_types::AddVaultRequest { + entity_id: merchant_account.get_id().to_owned(), + vault_id: vault_id.clone(), + data: req.token_request.clone(), + ttl: state.conf.locker.ttl_for_storage_in_secs, + } + .encode_to_vec() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode Request")?; + + // Call the vault service + let resp = pm_vault::call_to_vault::<pm_types::AddVault>(&state, payload.clone()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Call to vault failed")?; + + // Parse the response + let stored_resp: pm_types::AddVaultResponse = resp + .parse_struct("AddVaultResponse") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse data into AddVaultResponse")?; + + // Create new tokenization record + let tokenization_new = hyperswitch_domain_models::tokenization::Tokenization { + id: id_type::GlobalTokenId::generate(&state.conf.cell_information.id), + merchant_id: merchant_account.get_id().clone(), + customer_id: customer_id.clone(), + locker_id: stored_resp.vault_id.get_string_repr().to_string(), + created_at: common_utils::date_time::now(), + updated_at: common_utils::date_time::now(), + flag: enums::TokenizationFlag::Enabled, + version: enums::ApiVersion::V2, + }; + + // Insert into database + let tokenization = db + .insert_tokenization( + tokenization_new, + &(merchant_key_store.clone()), + key_manager_state, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to insert tokenization record")?; + + // Convert to TokenizationResponse + Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( + api_models::tokenization::GenericTokenizationResponse { + id: tokenization.id, + created_at: tokenization.created_at, + flag: tokenization.flag, + }, + )) +} + +#[instrument(skip_all)] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub async fn get_token_vault_core( + state: SessionState, + merchant_account: &domain::MerchantAccount, + merchant_key_store: &domain::MerchantKeyStore, + query: id_type::GlobalTokenId, +) -> CustomResult<serde_json::Value, errors::ApiErrorResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + let tokenization_record = db + .get_entity_id_vault_id_by_token_id( + &query, + &(merchant_key_store.clone()), + key_manager_state, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get tokenization record")?; + + if tokenization_record.flag == enums::TokenizationFlag::Disabled { + return Err(errors::ApiErrorResponse::GenericNotFoundError { + message: "Tokenization is disabled for the id".to_string(), + } + .into()); + } + + let vault_request = pm_types::VaultRetrieveRequest { + entity_id: tokenization_record.merchant_id.clone(), + vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate( + tokenization_record.locker_id.clone(), + ), + }; + + let vault_data = pm_vault::retrive_value_from_vault(&state, vault_request) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve vault data")?; + + let data_json = vault_data + .get("data") + .cloned() + .unwrap_or(serde_json::Value::Null); + + // Create the response + Ok(data_json) +} diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 17938dbbe31..d77e1926260 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -61,7 +61,9 @@ use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use masking::PeekInterface; use redis_interface::errors::RedisError; use router_env::logger; -use storage_impl::{errors::StorageError, redis::kv_store::RedisConnInterface, MockDb}; +use storage_impl::{ + errors::StorageError, redis::kv_store::RedisConnInterface, tokenization, MockDb, +}; pub use self::kafka_store::KafkaStore; use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface}; @@ -139,6 +141,7 @@ pub trait StorageInterface: + relay::RelayInterface + user::theme::ThemeInterface + payment_method_session::PaymentMethodsSessionInterface + + tokenization::TokenizationInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8c4ac07a32a..547846f8a0a 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -80,6 +80,7 @@ use crate::{ refund::RefundInterface, reverse_lookup::ReverseLookupInterface, routing_algorithm::RoutingAlgorithmInterface, + tokenization::TokenizationInterface, unified_translations::UnifiedTranslationsInterface, AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface, MasterKeyInterface, StorageInterface, @@ -87,7 +88,6 @@ use crate::{ services::{kafka::KafkaProducer, Store}, types::{domain, storage, AccessToken}, }; - #[derive(Debug, Clone, Serialize)] pub struct TenantID(pub String); @@ -4234,3 +4234,34 @@ impl CallbackMapperInterface for KafkaStore { self.diesel_store.find_call_back_mapper_by_id(id).await } } + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[async_trait::async_trait] +impl TokenizationInterface for KafkaStore { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + self.diesel_store + .insert_tokenization(tokenization, merchant_key_store, key_manager_state) + .await + } + + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &id_type::GlobalTokenId, + merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + self.diesel_store + .get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state) + .await + } +} + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +impl TokenizationInterface for KafkaStore {} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 0388f68225b..eb794a5c4fe 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -158,7 +158,10 @@ pub fn mk_app( .service(routes::PaymentMethodSession::server(state.clone())) .service(routes::Refunds::server(state.clone())); } - + #[cfg(all(feature = "v2", feature = "oltp", feature = "tokenization_v2"))] + { + server_app = server_app.service(routes::Tokenization::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 f36e7b6049b..21db7a4624d 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -47,6 +47,7 @@ pub mod recon; pub mod refunds; #[cfg(feature = "olap")] pub mod routing; +pub mod tokenization; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] @@ -78,6 +79,8 @@ pub use self::app::PaymentMethodSession; pub use self::app::Proxy; #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub use self::app::Recon; +#[cfg(feature = "v2")] +pub use self::app::Tokenization; pub use self::app::{ ApiKeys, AppState, ApplePayCertificatesMigration, Cache, Cards, Configs, ConnectorOnboarding, Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm, Health, Hypersense, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 173ac34bd3a..6071a9ee0b0 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -55,6 +55,8 @@ use super::recovery_webhooks::*; use super::refunds; #[cfg(feature = "olap")] use super::routing; +#[cfg(all(feature = "oltp", feature = "v2"))] +use super::tokenization as tokenization_routes; #[cfg(all(feature = "olap", feature = "v1"))] use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "oltp")] @@ -1418,6 +1420,20 @@ impl PaymentMethodSession { } } +#[cfg(all(feature = "v2", feature = "oltp"))] +pub struct Tokenization; + +#[cfg(all(feature = "v2", feature = "oltp"))] +impl Tokenization { + pub fn server(state: AppState) -> Scope { + let mut token_route = web::scope("/v2/tokenize").app_data(web::Data::new(state)); + token_route = token_route.service( + web::resource("").route(web::post().to(tokenization_routes::create_token_vault_api)), + ); + token_route + } +} + #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub struct Recon; diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1f224d2177c..8f14d5b5532 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -44,6 +44,7 @@ pub enum ApiIdentifier { PaymentMethodSession, ProcessTracker, Proxy, + GenericTokenization, } impl From<Flow> for ApiIdentifier { @@ -342,6 +343,8 @@ impl From<Flow> for ApiIdentifier { Flow::RevenueRecoveryRetrieve => Self::ProcessTracker, Flow::Proxy => Self::Proxy, + + Flow::TokenizationCreate | Flow::TokenizationRetrieve => Self::GenericTokenization, } } } diff --git a/crates/router/src/routes/tokenization.rs b/crates/router/src/routes/tokenization.rs new file mode 100644 index 00000000000..6becca19df7 --- /dev/null +++ b/crates/router/src/routes/tokenization.rs @@ -0,0 +1,74 @@ +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use std::sync::Arc; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use actix_web::{web, HttpRequest, HttpResponse}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use api_models; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use common_utils::{ + ext_traits::{BytesExt, Encode}, + id_type, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use error_stack::ResultExt; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use hyperswitch_domain_models; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use masking::Secret; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use router_env::{instrument, logger, tracing, Flow}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use serde::Serialize; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use crate::{ + core::{ + api_locking, + errors::{self, RouterResult}, + tokenization, + }, + headers::X_CUSTOMER_ID, + routes::{app::StorageInterface, AppState, SessionState}, + services::{self, api as api_service, authentication as auth}, + types::{api, domain, payment_methods as pm_types}, +}; + +#[instrument(skip_all, fields(flow = ?Flow::TokenizationCreate))] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub async fn create_token_vault_api( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_models::tokenization::GenericTokenizationRequest>, +) -> HttpResponse { + let flow = Flow::TokenizationCreate; + let payload = json_payload.into_inner(); + let customer_id = payload.customer_id.clone(); + Box::pin(api_service::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, request, _| async move { + tokenization::create_vault_token_core( + state, + &auth.merchant_account, + &auth.key_store, + request, + ) + .await + }, + auth::api_or_client_auth( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Customer( + customer_id, + )), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs index 342347cd793..f05442ed45d 100644 --- a/crates/router/src/types/payment_methods.rs +++ b/crates/router/src/types/payment_methods.rs @@ -44,7 +44,11 @@ pub struct VaultFingerprintResponse { pub fingerprint_id: String, } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[cfg(any( + feature = "v2", + feature = "payment_methods_v2", + feature = "tokenization_v2" +))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultRequest<D> { pub entity_id: id_type::MerchantId, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 60a8939aeb0..c4fe30334b9 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -586,6 +586,10 @@ pub enum Flow { TotalPaymentMethodCount, /// Process Tracker Revenue Recovery Workflow Retrieve RevenueRecoveryRetrieve, + /// Tokenization flow + TokenizationCreate, + /// Tokenization retrieve flow + TokenizationRetrieve, /// Clone Connector flow CloneConnector, ///Proxy Flow diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index ee849f78f46..4830201db74 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -18,6 +18,7 @@ v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "comm customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"] payment_methods_v2 = ["diesel_models/payment_methods_v2", "api_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2"] refunds_v2 = ["diesel_models/refunds_v2"] +tokenization_v2 = ["diesel_models/tokenization_v2", "api_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2"] [dependencies] # First Party dependencies diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 6cc5f035a7a..05fc865860a 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -32,6 +32,9 @@ pub mod utils; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use database::store::PgPool; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use diesel_models::tokenization::Tokenization; +pub mod tokenization; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; pub use mock_db::MockDb; @@ -502,3 +505,14 @@ impl UniqueConstraints for diesel_models::Customer { impl<T: DatabaseStore> PayoutAttemptInterface for RouterStore<T> {} #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutsInterface for RouterStore<T> {} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl UniqueConstraints for diesel_models::tokenization::Tokenization { + fn unique_constraints(&self) -> Vec<String> { + vec![format!("id_{}", self.id.get_string_repr())] + } + + fn table_name(&self) -> &str { + "tokenization" + } +} diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index 1471f854de6..884d9747943 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -45,6 +45,8 @@ pub struct MockDb { pub mandates: Arc<Mutex<Vec<store::Mandate>>>, pub captures: Arc<Mutex<Vec<store::capture::Capture>>>, pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>, + #[cfg(all(feature = "v2", feature = "tokenization_v2"))] + pub tokenizations: Arc<Mutex<Vec<store::tokenization::Tokenization>>>, pub business_profiles: Arc<Mutex<Vec<store::business_profile::Profile>>>, pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>, pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>, @@ -92,6 +94,8 @@ impl MockDb { mandates: Default::default(), captures: Default::default(), merchant_key_store: Default::default(), + #[cfg(all(feature = "v2", feature = "tokenization_v2"))] + tokenizations: Default::default(), business_profiles: Default::default(), reverse_lookups: Default::default(), payment_link: Default::default(), diff --git a/crates/storage_impl/src/tokenization.rs b/crates/storage_impl/src/tokenization.rs new file mode 100644 index 00000000000..5ecb6b0a813 --- /dev/null +++ b/crates/storage_impl/src/tokenization.rs @@ -0,0 +1,174 @@ +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use async_bb8_diesel::AsyncRunQueryDsl; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use common_utils::{ + errors::CustomResult, + ext_traits::OptionExt, + id_type::{CellId, GlobalTokenId, MerchantId}, + types::keymanager::KeyManagerState, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use diesel::{ExpressionMethods, Insertable, RunQueryDsl}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use diesel_models::{ + enums::TokenizationFlag as DbTokenizationFlag, + schema_v2::tokenization::dsl as tokenization_dsl, tokenization, PgPooledConn, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use error_stack::{report, Report, ResultExt}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use hyperswitch_domain_models::tokenization::Tokenization; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use hyperswitch_domain_models::{ + behaviour::{Conversion, ReverseConversion}, + merchant_key_store::MerchantKeyStore, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use tokio::time; + +use super::MockDb; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use crate::{ + connection, diesel_error_to_data_error, errors, + kv_router_store::{ + FilterResourceParams, FindResourceBy, InsertResourceParams, UpdateResourceParams, + }, + redis::kv_store::{Op, PartitionKey}, + utils::{pg_connection_read, pg_connection_write}, +}; +use crate::{kv_router_store::KVRouterStore, DatabaseStore, RouterStore}; + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +pub trait TokenizationInterface {} + +#[async_trait::async_trait] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub trait TokenizationInterface { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; + + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &common_utils::id_type::GlobalTokenId, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; +} + +#[async_trait::async_trait] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + let conn = connection::pg_connection_write(self).await?; + + tokenization + .construct_new() + .await + .change_context(errors::StorageError::EncryptionError)? + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error)))? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } + + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &common_utils::id_type::GlobalTokenId, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + let conn = connection::pg_connection_read(self).await?; + + let tokenization = diesel_models::tokenization::Tokenization::find_by_id(&conn, token) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + + let domain = tokenization + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError)?; + + Ok(domain) + } +} + +#[async_trait::async_trait] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + self.router_store + .insert_tokenization(tokenization, merchant_key_store, key_manager_state) + .await + } + + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &common_utils::id_type::GlobalTokenId, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + self.router_store + .get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state) + .await + } +} + +#[async_trait::async_trait] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl TokenizationInterface for MockDb { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + Err(errors::StorageError::MockDbError)? + } + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &common_utils::id_type::GlobalTokenId, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + Err(errors::StorageError::MockDbError)? + } +} + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +impl TokenizationInterface for MockDb {} + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {} + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> {} diff --git a/v2_migrations/2025-04-25-105138_tokenization_service_creation/down.sql b/v2_migrations/2025-04-25-105138_tokenization_service_creation/down.sql new file mode 100644 index 00000000000..0eabe21fc74 --- /dev/null +++ b/v2_migrations/2025-04-25-105138_tokenization_service_creation/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +DROP TABLE IF EXISTS tokenization; +DROP TYPE "TokenizationFlag"; \ No newline at end of file diff --git a/v2_migrations/2025-04-25-105138_tokenization_service_creation/up.sql b/v2_migrations/2025-04-25-105138_tokenization_service_creation/up.sql new file mode 100644 index 00000000000..bfffd383ee5 --- /dev/null +++ b/v2_migrations/2025-04-25-105138_tokenization_service_creation/up.sql @@ -0,0 +1,13 @@ +-- Your SQL goes here +CREATE TYPE "TokenizationFlag" AS ENUM ('enabled', 'disabled'); + +CREATE TABLE IF NOT EXISTS tokenization ( + id VARCHAR(64) PRIMARY KEY, -- GlobalTokenId + merchant_id VARCHAR(255) NOT NULL, + customer_id VARCHAR(64) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + locker_id VARCHAR(255) NOT NULL, + flag "TokenizationFlag" NOT NULL DEFAULT 'enabled', + version "ApiVersion" NOT NULL DEFAULT 'v2' -- ApiVersion enum +); \ No newline at end of file
2025-04-25T11:46:43Z
## Description <!-- Describe your changes in detail --> Create a new set of endpoints for giving tokenization as a service for generic usage, current motivation of the service is to be used in proxy payment service. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
8e9bad6457449ef2a435be03a9f97acc2dd2108a
**Create a token** ```bash curl --location 'http: //localhost:8080/v2/tokenize' \ --header 'x-profile-id: pro_neU1Qn8gnIich0LAaQXm' \ --header 'Authorization: publishable-key=PUBLISHABLE_KEY,client-secret=CLIENT_SECRET' \ --header 'Content-Type: application/json' \ --data '{ "customer_id": customer_id, "token_request": { "payment_method_data": { "card": { "card_holder_name": "Narayan Bhat" } } } }' ``` Response ```json { "id": "12345_tok_01966c6515157c3193db1c2502435ad5", "created_at": "2025-04-25 10:01:26.037519", "flag": "enabled" } ```
[ "api-reference-v2/api-reference/tokenization/tokenization--create.mdx", "api-reference-v2/mint.json", "api-reference-v2/openapi_spec.json", "config/development.toml", "crates/api_models/Cargo.toml", "crates/api_models/src/events.rs", "crates/api_models/src/lib.rs", "crates/api_models/src/payment_methods.rs", "crates/api_models/src/tokenization.rs", "crates/common_enums/src/enums.rs", "crates/common_types/Cargo.toml", "crates/common_utils/Cargo.toml", "crates/common_utils/src/consts.rs", "crates/common_utils/src/events.rs", "crates/common_utils/src/id_type.rs", "crates/common_utils/src/id_type/global_id.rs", "crates/common_utils/src/id_type/global_id/token.rs", "crates/common_utils/src/lib.rs", "crates/common_utils/src/tokenization.rs", "crates/diesel_models/Cargo.toml", "crates/diesel_models/src/enums.rs", "crates/diesel_models/src/lib.rs", "crates/diesel_models/src/mod.rs", "crates/diesel_models/src/payment_methods_session.rs", "crates/diesel_models/src/query.rs", "crates/diesel_models/src/query/tokenization.rs", "crates/diesel_models/src/schema_v2.rs", "crates/diesel_models/src/tokenization.rs", "crates/diesel_models/src/types.rs", "crates/hyperswitch_domain_models/Cargo.toml", "crates/hyperswitch_domain_models/src/lib.rs", "crates/hyperswitch_domain_models/src/payment_methods.rs", "crates/hyperswitch_domain_models/src/tokenization.rs", "crates/masking/src/lib.rs", "crates/masking/src/secret.rs", "crates/openapi/Cargo.toml", "crates/openapi/src/openapi_v2.rs", "crates/openapi/src/routes.rs", "crates/openapi/src/routes/tokenization.rs", "crates/router/Cargo.toml", "crates/router/src/core.rs", "crates/router/src/core/payment_methods.rs", "crates/router/src/core/payment_methods/transformers.rs", "crates/router/src/core/payment_methods/vault.rs", "crates/router/src/core/tokenization.rs", "crates/router/src/db.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/lib.rs", "crates/router/src/routes.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/tokenization.rs", "crates/router/src/types/payment_methods.rs", "crates/router_env/src/logger/types.rs", "crates/storage_impl/Cargo.toml", "crates/storage_impl/src/lib.rs", "crates/storage_impl/src/mock_db.rs", "crates/storage_impl/src/tokenization.rs", "v2_migrations/2025-04-25-105138_tokenization_service_creation/down.sql", "v2_migrations/2025-04-25-105138_tokenization_service_creation/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7883
Bug: [chore] add cardholder name to payment required fields Add cardholder name to payment required fields for Worldpay card payments.
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index 4628eaf116e..645502b267d 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -285,6 +285,7 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons http_code: res.status_code, }, optional_correlation_id, + data.request.amount.unwrap_or(0), )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -759,6 +760,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData http_code: res.status_code, }, optional_correlation_id, + data.request.amount, )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -870,6 +872,7 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp http_code: res.status_code, }, optional_correlation_id, + data.request.amount, )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index 8fd41ea2031..adee7fb2891 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -86,34 +86,24 @@ fn fetch_payment_instrument( }, cvc: card.card_cvc, card_holder_name: billing_address.and_then(|address| address.get_optional_full_name()), - billing_address: if let Some(address) = - billing_address.and_then(|addr| addr.address.clone()) - { - Some(BillingAddress { - address1: address.line1.get_required_value("line1").change_context( - errors::ConnectorError::MissingRequiredField { - field_name: "line1", - }, - )?, - address2: address.line2, - address3: address.line3, - 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" }, - )?, - country_code: address - .country - .get_required_value("country_code") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "country_code", - })?, - }) - } else { - None - }, + billing_address: billing_address + .and_then(|addr| addr.address.clone()) + .and_then(|address| { + match (address.line1, address.city, address.zip, address.country) { + (Some(address1), Some(city), Some(postal_code), Some(country_code)) => { + Some(BillingAddress { + address1, + address2: address.line2, + address3: address.line3, + city, + state: address.state, + postal_code, + country_code, + }) + } + _ => None, + } + }), })), PaymentMethodData::CardDetailsForNetworkTransactionId(raw_card_details) => { Ok(PaymentInstrument::RawCardForNTI(RawCardDetails { @@ -264,7 +254,7 @@ impl WorldpayPaymentsRequestData for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData> { fn get_return_url(&self) -> Result<String, error_stack::Report<errors::ConnectorError>> { - self.request.get_router_return_url() + self.request.get_complete_authorize_url() } fn get_auth_type(&self) -> &enums::AuthenticationType { @@ -681,6 +671,7 @@ impl<F, T> ForeignTryFrom<( ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>, Option<String>, + i64, )> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; @@ -688,9 +679,10 @@ impl<F, T> item: ( ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>, Option<String>, + i64, ), ) -> Result<Self, Self::Error> { - let (router_data, optional_correlation_id) = item; + let (router_data, optional_correlation_id, amount) = item; let (description, redirection_data, mandate_reference, network_txn_id, error) = router_data .response .other_fields @@ -770,7 +762,11 @@ impl<F, T> PaymentOutcome::FraudHighRisk => Some("Transaction marked as high risk".to_string()), _ => None, }; - let status = enums::AttemptStatus::from(worldpay_status.clone()); + let status = if amount == 0 && worldpay_status == PaymentOutcome::Authorized { + enums::AttemptStatus::Charged + } else { + enums::AttemptStatus::from(worldpay_status.clone()) + }; let response = match (optional_error_message, error) { (None, None) => Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::foreign_try_from(( diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 192d45c8fce..69cb4b97de4 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1473,6 +1473,7 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { RequiredField::CardNumber, RequiredField::CardExpMonth, RequiredField::CardExpYear, + RequiredField::BillingUserFirstName, ], ), ),
2025-04-24T13:40:33Z
## Description This PR adds below changes - Add required field for Worldpay card transactions - card holder name. - Fix 3DS SetupMandate flows for Worldpay card transactions ## Motivation and Context Card holder name is a mandatory field which is required by WP during card transactions. Fixing the 3DS SetupMandate flow for Worldpay allows merchants to consume the functionality. #
54e910582fac9bd6fe300a9a96926adf5123403e
<details> <summary>1. [No3DS] Create zero amount off_session payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' \ --data-raw '{"amount":0,"currency":"SGD","confirm":true,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","setup_future_usage":"off_session","customer_id":"cus_GPjGfsYpA50dZpSocrbd","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"737"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_wfFMLqmemSnqwZVHT3kM","merchant_id":"merchant_1745484169","status":"succeeded","amount":0,"net_amount":0,"shipping_cost":null,"amount_capturable":0,"amount_received":0,"connector":"worldpay","client_secret":"pay_wfFMLqmemSnqwZVHT3kM_secret_eeoF2tNW0wRyvp2pU3WP","created":"2025-04-24T13:31:24.448Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_GPjGfsYpA50dZpSocrbd","created_at":1745501484,"expires":1745505084,"secret":"epk_a62a7064a7e34ccd8305d605ae359881"},"manual_retry_allowed":false,"connector_transaction_id":"23fbb1ff-43c0-4fc4-b27d-072e23683f97","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"23fbb1ff-43c0-4fc4-b27d-072e23683f97","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:32:24.448Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_yg0qfrNde4WjKQH8Gi3h","payment_method_status":"active","updated":"2025-04-24T13:31:26.513Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"https://try.access.worldpay.com/tokens/eyJrIjoxLCJkIjoidFlEWFFxbDNSUDNZZDg4T0VoWVVxbkdlaFB0RUlvVjFQcEs5TU9KRk9TQT0ifQ","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> <details> <summary>2. [No3DS] Create non zero amount off_session payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' \ --data-raw '{"amount":1000,"currency":"SGD","confirm":true,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","setup_future_usage":"off_session","customer_id":"cus_GPjGfsYpA50dZpSocrbd","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"737"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_OmaRK9FIhoOR0opBCA5q","merchant_id":"merchant_1745484169","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":1000,"connector":"worldpay","client_secret":"pay_OmaRK9FIhoOR0opBCA5q_secret_BZ0tzOif151DIaYSqUWl","created":"2025-04-24T13:32:05.834Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_GPjGfsYpA50dZpSocrbd","created_at":1745501525,"expires":1745505125,"secret":"epk_f3c123ca19364af294602e915a89a659"},"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNi4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99HBj426bdlJXCgTskLhNY5Ml0rXtEPNSyl2cbsnj4b2DZrMdENEzIjocoy3lSG96aYlW4Z+fnZKMutoUGX3m1:mDK4Giru8JHLS90mSN+Z+gkVKRI3EE1MXDv7dp+h3RhHFHGaPn9ksCvhYk:a:cH+e81VQ0:KjdVX14V+Q12mM8f8UUuVrb1pWfdmRX0ol0w4rW66yFNGsWi87tzkRENLR8ix3NBfHPU2KlzlyTrmR0mwasA4zRNlfY:bG7Aaa:GaUgn8jvCNhmdUlN6uDEfAu3+Gpx8cadeYO0VLI6Wl9In2xgejGQ0ri:BU5HlAn:UMGwtz7wDtU06VN+Rkfa60cHqFXxXOGsvxbfcVlSe:hmS+WwXVvDoxGmrxlJztOw0ZEV8g:Qgoe7iLzyfbMA1TfZNrYIkRNlWpYaVeOJiIYYCBgREKSZGhVAzktTueU3oo=","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"929b66d4-df1d-4660-a4a1-ec4c14136cea","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:33:05.834Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_BMicZubaUj8L5mP3dk5M","payment_method_status":"active","updated":"2025-04-24T13:32:07.354Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"https://try.access.worldpay.com/tokens/eyJrIjoxLCJkIjoidFlEWFFxbDNSUDNZZDg4T0VoWVVxbkdlaFB0RUlvVjFQcEs5TU9KRk9TQT0ifQ","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> <details> <summary>3. [3DS] Create non zero amount off_session payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' \ --data-raw '{"amount":1000,"currency":"SGD","confirm":true,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","customer_id":"cus_GPjGfsYpA50dZpSocrbd","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"737"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_V52ZUSmwZcawWT6SmhK9","merchant_id":"merchant_1745484169","status":"requires_customer_action","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":1000,"amount_received":null,"connector":"worldpay","client_secret":"pay_V52ZUSmwZcawWT6SmhK9_secret_xkcz8525E884zswbTF90","created":"2025-04-24T13:32:54.875Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_V52ZUSmwZcawWT6SmhK9/merchant_1745484169/pay_V52ZUSmwZcawWT6SmhK9_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_GPjGfsYpA50dZpSocrbd","created_at":1745501574,"expires":1745505174,"secret":"epk_79da3389a5d349a2a060f8ef6377ad7a"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoiZnFyaU40UENQRnQzVHRndEtDdDg0bHZkVGsyMlNGZkpHRmV3Q3UxRHVwSUxvQVZFYmcwR3Q5NHkrN0xNNitQMiJ9_2","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"0b390991-6688-40b9-8b95-950a65af5678","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:33:54.875Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_1NL54rrmq8DE3vQ9VgZX","payment_method_status":"inactive","updated":"2025-04-24T13:32:55.282Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} Complete the payment by clicking the link cURL (retrieve) curl --location --request GET 'http://localhost:8080/payments/pay_V52ZUSmwZcawWT6SmhK9' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' Response {"payment_id":"pay_V52ZUSmwZcawWT6SmhK9","merchant_id":"merchant_1745484169","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":1000,"connector":"worldpay","client_secret":"pay_V52ZUSmwZcawWT6SmhK9_secret_xkcz8525E884zswbTF90","created":"2025-04-24T13:32:54.875Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNi4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99HBj426bdlJXCgTskLhNY5Ml0rXtEPNSyl2cbsnj4b2DZrMdENEzIjocoy3lSG96aYlW4Z+fnZKMutoUGX3m1:mmJTlkRKFQu2PsVe3y+vegKDX5ZP4XxijGSq2aIDDwI7FHGaPn9ksCvhYk:a:cH+e81VQ0:KjdVX14V+Q12mM8f8UUuVrb1pWfdmRX0ol0w4rW66yFNGsWi87tzkRENLR8ix3NBfHPU2KlzlyTrmR0mwasA4zRNlfY:bG7Aaa:GaUgn8jvCNhmdUlN6uDEfAu3+Gpx8cadeYO0VLI6Wl9IlLyMVREoNqKOzGKAWbV6MGEiI1GbjFu2YIwRaZQDXnodMGaowTzH8y6H4OLwV6Mey+WwXVvDoxGmrxlJztOw0ZEV8g:Qgoe7iLzyfbMA1TfZNrYIkRNlWpYaVeOJiIYYCBgREKSZGhVAzktTueU3oo=","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"69586da7-7ba1-4154-844c-35a4dddc9b86","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:33:54.875Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_1NL54rrmq8DE3vQ9VgZX","payment_method_status":"active","updated":"2025-04-24T13:33:09.920Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> <details> <summary>4. [3DS] Create zero amount off_session payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' \ --data-raw '{"amount":0,"currency":"SGD","confirm":true,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","customer_id":"cus_GPjGfsYpA50dZpSocrbd","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"737"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_i87Xb0hGyY0UmG1yhrpH","merchant_id":"merchant_1745484169","status":"requires_customer_action","amount":0,"net_amount":0,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"worldpay","client_secret":"pay_i87Xb0hGyY0UmG1yhrpH_secret_sjCsGpNDs2T8YVZEjaid","created":"2025-04-24T13:35:09.354Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_i87Xb0hGyY0UmG1yhrpH/merchant_1745484169/pay_i87Xb0hGyY0UmG1yhrpH_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_GPjGfsYpA50dZpSocrbd","created_at":1745501709,"expires":1745505309,"secret":"epk_f1b950bdde6d4989a336c8322ef732a6"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoiY1d2OGxEdTVBbEF4M1VSNVIwK0FnTGpKakl1cVhVWWpZQ3laVHpxdm5WTUxvQVZFYmcwR3Q5NHkrN0xNNitQMiJ9_2","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"43da3943-2049-4e20-95fc-172a1b763dde","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:36:09.354Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_Lih5KP2o2m4mcGBnlgWF","payment_method_status":"inactive","updated":"2025-04-24T13:35:10.457Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} cURL (retrieve) curl --location --request GET 'http://localhost:8080/payments/pay_i87Xb0hGyY0UmG1yhrpH' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' Response {"payment_id":"pay_i87Xb0hGyY0UmG1yhrpH","merchant_id":"merchant_1745484169","status":"succeeded","amount":0,"net_amount":0,"shipping_cost":null,"amount_capturable":0,"amount_received":0,"connector":"worldpay","client_secret":"pay_i87Xb0hGyY0UmG1yhrpH_secret_sjCsGpNDs2T8YVZEjaid","created":"2025-04-24T13:35:09.354Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"1142f6b3-364b-4988-a508-14b17c18b523","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"1142f6b3-364b-4988-a508-14b17c18b523","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:36:09.354Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_Lih5KP2o2m4mcGBnlgWF","payment_method_status":"active","updated":"2025-04-24T13:36:35.533Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details>
[ "crates/hyperswitch_connectors/src/connectors/worldpay.rs", "crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs", "crates/payment_methods/src/configs/payment_connector_required_fields.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7895
Bug: open router integration of elimination routing Add support for integrating open router's elimination routing in Hyperswitch
diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index c33365df169..07af605892f 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -10,14 +10,14 @@ pub use euclid::{ }; use serde::{Deserialize, Serialize}; -use crate::enums::{Currency, PaymentMethod, RoutableConnectors}; +use crate::enums::{Currency, PaymentMethod}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OpenRouterDecideGatewayRequest { pub payment_info: PaymentInfo, pub merchant_id: id_type::ProfileId, - pub eligible_gateway_list: Option<Vec<RoutableConnectors>>, + pub eligible_gateway_list: Option<Vec<String>>, pub ranking_algorithm: Option<RankingAlgorithm>, pub elimination_enabled: Option<bool>, } @@ -80,7 +80,7 @@ pub struct UnifiedError { #[serde(rename_all = "camelCase")] pub struct UpdateScorePayload { pub merchant_id: id_type::ProfileId, - pub gateway: RoutableConnectors, + pub gateway: String, pub status: TxnStatus, pub payment_id: id_type::PaymentId, } @@ -91,7 +91,7 @@ pub enum TxnStatus { Started, AuthenticationFailed, JuspayDeclined, - PendingVBV, + PendingVbv, VBVSuccessful, Authorized, AuthorizationFailed, @@ -111,12 +111,3 @@ pub enum TxnStatus { Failure, Declined, } - -impl From<bool> for TxnStatus { - fn from(value: bool) -> Self { - match value { - true => Self::Charged, - _ => Self::Failure, - } - } -} diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index d3529edd29e..a683e3343aa 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -642,6 +642,17 @@ impl DynamicRoutingAlgorithmRef { pub fn update_volume_split(&mut self, volume: Option<u8>) { self.dynamic_routing_volume_split = volume } + + pub fn is_elimination_enabled(&self) -> bool { + self.elimination_routing_algorithm + .as_ref() + .map(|elimination_routing| { + elimination_routing.enabled_feature + == DynamicRoutingFeatures::DynamicConnectorSelection + || elimination_routing.enabled_feature == DynamicRoutingFeatures::Metrics + }) + .unwrap_or_default() + } } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)] diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 038751451ac..6bc55203615 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1516,6 +1516,7 @@ pub async fn perform_open_routing( profile.get_id().get_string_repr() ); + let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled(); let connectors = dynamic_routing_algo_ref .success_based_algorithm .async_map(|algo| { @@ -1524,16 +1525,34 @@ pub async fn perform_open_routing( routable_connectors.clone(), profile.get_id(), algo, - payment_data, + &payment_data, + is_elimination_enabled, ) }) .await - .transpose() - .inspect_err(|e| logger::error!(dynamic_routing_error=?e)) - .ok() - .flatten() + .transpose()? .unwrap_or(routable_connectors); + if is_elimination_enabled { + // This will initiate the elimination process for the connector. + // Penalize the elimination score of the connector before making a payment. + // Once the payment is made, we will update the score based on the payment status + if let Some(connector) = connectors.first() { + logger::debug!( + "penalizing the elimination score of the gateway with id {} in open router for profile {}", + connector, profile.get_id().get_string_repr() + ); + update_success_rate_score_with_open_router( + state, + connector.clone(), + profile.get_id(), + &payment_data.payment_id, + common_enums::AttemptStatus::AuthenticationPending, + ) + .await? + } + } + Ok(connectors) } @@ -1634,7 +1653,8 @@ pub async fn perform_success_based_routing_with_open_router( mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, success_based_algo_ref: api_routing::SuccessBasedAlgorithm, - payment_attempt: oss_storage::PaymentAttempt, + payment_attempt: &oss_storage::PaymentAttempt, + is_elimination_enabled: bool, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { if success_based_algo_ref.enabled_feature == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection @@ -1646,11 +1666,9 @@ pub async fn perform_success_based_routing_with_open_router( let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request( payment_attempt, - routable_connectors - .iter() - .map(|gateway| gateway.connector) - .collect::<Vec<_>>(), + routable_connectors.clone(), Some(or_types::RankingAlgorithm::SrBasedRouting), + is_elimination_enabled, ); let url = format!("{}/{}", &state.conf.open_router.url, "decide-gateway"); @@ -1724,15 +1742,15 @@ pub async fn perform_success_based_routing_with_open_router( #[instrument(skip_all)] pub async fn update_success_rate_score_with_open_router( state: &SessionState, - payment_connector: common_enums::RoutableConnectors, + payment_connector: api_routing::RoutableConnectorChoice, profile_id: &common_utils::id_type::ProfileId, payment_id: &common_utils::id_type::PaymentId, - payment_status: bool, + payment_status: common_enums::AttemptStatus, ) -> RoutingResult<()> { let open_router_req_body = or_types::UpdateScorePayload { merchant_id: profile_id.clone(), - gateway: payment_connector, - status: payment_status.into(), + gateway: payment_connector.to_string(), + status: payment_status.foreign_into(), payment_id: payment_id.clone(), }; @@ -1763,7 +1781,8 @@ pub async fn update_success_rate_score_with_open_router( )?; logger::debug!( - "Open router update_gateway_score response: {:?}", + "Open router update_gateway_score response for gateway with id {}: {:?}", + payment_connector, update_score_resp ); diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index b10500d2844..cf14c70ca32 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -8,6 +8,8 @@ use std::str::FromStr; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use std::sync::Arc; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::open_router; use api_models::routing as routing_types; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use common_utils::ext_traits::ValueExt; @@ -39,6 +41,8 @@ use storage_impl::redis::cache::Cacheable; use crate::db::errors::StorageErrorExt; #[cfg(feature = "v2")] use crate::types::domain::MerchantConnectorAccount; +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +use crate::types::transformers::ForeignFrom; use crate::{ core::errors::{self, RouterResult}, db::StorageInterface, @@ -729,20 +733,27 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( }, )?; - let payment_status_attribute = - get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); + let routable_connector = routing_types::RoutableConnectorChoice { + choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + }; let should_route_to_open_router = state.conf.open_router.enabled; if should_route_to_open_router { + logger::debug!( + "performing update-gateway-score for gateway with id {} in open router for profile: {}", + routable_connector, profile_id.get_string_repr() + ); routing::payments_routing::update_success_rate_score_with_open_router( state, - common_enums::RoutableConnectors::from_str(payment_connector.as_str()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to infer routable_connector from connector")?, + routable_connector.clone(), profile_id, &payment_attempt.payment_id, - payment_status_attribute == common_enums::AttemptStatus::Charged, + payment_attempt.status, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -751,6 +762,9 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( return Ok(()); } + let payment_status_attribute = + get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); + let success_based_routing_configs = fetch_dynamic_routing_configs::< routing_types::SuccessBasedRoutingConfig, >( @@ -972,17 +986,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( success_based_routing_configs, success_based_routing_config_params, vec![routing_types::RoutableConnectorChoiceWithStatus::new( - routing_types::RoutableConnectorChoice { - choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, - connector: common_enums::RoutableConnectors::from_str( - payment_connector.as_str(), - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "unable to infer routable_connector from connector", - )?, - merchant_connector_id: payment_attempt.merchant_connector_id.clone(), - }, + routable_connector, payment_status_attribute == common_enums::AttemptStatus::Charged, )], state.get_grpc_headers(), @@ -1350,6 +1354,38 @@ fn get_desired_payment_status_for_dynamic_routing_metrics( } } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl ForeignFrom<common_enums::AttemptStatus> for open_router::TxnStatus { + fn foreign_from(attempt_status: common_enums::AttemptStatus) -> Self { + match attempt_status { + common_enums::AttemptStatus::Started => Self::Started, + common_enums::AttemptStatus::AuthenticationFailed => Self::AuthenticationFailed, + common_enums::AttemptStatus::RouterDeclined => Self::JuspayDeclined, + common_enums::AttemptStatus::AuthenticationPending => Self::PendingVbv, + common_enums::AttemptStatus::AuthenticationSuccessful => Self::VBVSuccessful, + common_enums::AttemptStatus::Authorized => Self::Authorized, + common_enums::AttemptStatus::AuthorizationFailed => Self::AuthorizationFailed, + common_enums::AttemptStatus::Charged => Self::Charged, + common_enums::AttemptStatus::Authorizing => Self::Authorizing, + common_enums::AttemptStatus::CodInitiated => Self::CODInitiated, + common_enums::AttemptStatus::Voided => Self::Voided, + common_enums::AttemptStatus::VoidInitiated => Self::VoidInitiated, + common_enums::AttemptStatus::CaptureInitiated => Self::CaptureInitiated, + common_enums::AttemptStatus::CaptureFailed => Self::CaptureFailed, + common_enums::AttemptStatus::VoidFailed => Self::VoidFailed, + common_enums::AttemptStatus::AutoRefunded => Self::AutoRefunded, + common_enums::AttemptStatus::PartialCharged => Self::PartialCharged, + common_enums::AttemptStatus::PartialChargedAndChargeable => Self::ToBeCharged, + common_enums::AttemptStatus::Unresolved => Self::Pending, + common_enums::AttemptStatus::Pending => Self::Pending, + common_enums::AttemptStatus::Failure => Self::Failure, + common_enums::AttemptStatus::PaymentMethodAwaited => Self::Pending, + common_enums::AttemptStatus::ConfirmationAwaited => Self::Pending, + common_enums::AttemptStatus::DeviceDataCollectionPending => Self::Pending, + } + } +} + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] fn get_dynamic_routing_based_metrics_outcome_for_payment( payment_status_attribute: common_enums::AttemptStatus, diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs index d73e0d28671..85b6e5832a8 100644 --- a/crates/router/src/core/routing/transformers.rs +++ b/crates/router/src/core/routing/transformers.rs @@ -1,11 +1,12 @@ -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use api_models::open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm}; use api_models::routing::{ MerchantRoutingAlgorithm, RoutingAlgorithm as Algorithm, RoutingAlgorithmKind, RoutingDictionaryRecord, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use common_enums::RoutableConnectors; +use api_models::{ + open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm}, + routing::RoutableConnectorChoice, +}; use common_utils::ext_traits::ValueExt; use diesel_models::{ enums as storage_enums, @@ -108,9 +109,10 @@ impl From<&routing::TransactionData<'_>> for storage_enums::TransactionType { #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub trait OpenRouterDecideGatewayRequestExt { fn construct_sr_request( - attempt: PaymentAttempt, - eligible_gateway_list: Vec<RoutableConnectors>, + attempt: &PaymentAttempt, + eligible_gateway_list: Vec<RoutableConnectorChoice>, ranking_algorithm: Option<RankingAlgorithm>, + is_elimination_enabled: bool, ) -> Self where Self: Sized; @@ -119,13 +121,14 @@ pub trait OpenRouterDecideGatewayRequestExt { #[cfg(all(feature = "v1", feature = "dynamic_routing"))] impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { fn construct_sr_request( - attempt: PaymentAttempt, - eligible_gateway_list: Vec<RoutableConnectors>, + attempt: &PaymentAttempt, + eligible_gateway_list: Vec<RoutableConnectorChoice>, ranking_algorithm: Option<RankingAlgorithm>, + is_elimination_enabled: bool, ) -> Self { Self { payment_info: PaymentInfo { - payment_id: attempt.payment_id, + payment_id: attempt.payment_id.clone(), amount: attempt.net_amount.get_order_amount(), currency: attempt.currency.unwrap_or(storage_enums::Currency::USD), payment_type: "ORDER_PAYMENT".to_string(), @@ -133,10 +136,15 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt payment_method: attempt.payment_method.unwrap_or_default(), }, - merchant_id: attempt.profile_id, - eligible_gateway_list: Some(eligible_gateway_list), + merchant_id: attempt.profile_id.clone(), + eligible_gateway_list: Some( + eligible_gateway_list + .into_iter() + .map(|connector| connector.to_string()) + .collect(), + ), ranking_algorithm, - elimination_enabled: None, + elimination_enabled: Some(is_elimination_enabled), } } }
2025-04-24T13:31:59Z
## Description <!-- Describe your changes in detail --> This PR adds the elimination routing integration support with open router. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
bc7679d54f09c04037604c04e6a655ed5bf264cd
Create merchant_account, api_key, mca 1. Enable elimination routing for merchant ``` curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/elimination/toggle?enable=dynamic_connector_selection' \ --header 'api-key: xyz' ``` 2. Enable Volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/set_volume_split?split=100' \ --header 'api-key: xyz' ``` 3. Create a Payment Search for the log " penalizing the elimination score of the gateway with id" ![image](https://github.com/user-attachments/assets/16bd41b3-5dd9-4911-b64e-4f53ceb50689)
[ "crates/api_models/src/open_router.rs", "crates/api_models/src/routing.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/core/routing/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7924
Bug: Fix: populating the docker related changes from main to stable release Some docker related changes were made in the main branch, these need to be included in the stable release too.
diff --git a/README.md b/README.md index 72ac7e0e3a7..3033263e578 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,8 @@ Single API to access the payments ecosystem and its features ## Table of Contents 1. [Introduction](#introduction) -2. [Architectural Overview](#architectural-overview) -3. [Try Hyperswitch](#try-hyperswitch) +2. [Try Hyperswitch](#try-hyperswitch) +3. [Architectural Overview](#architectural-overview) 4. [Support, Feature requests & Bugs](#support-feature-requests) 5. [Our Vision](#our-vision) 6. [Versioning](#versioning) @@ -63,51 +63,37 @@ Here are the key components of Hyperswitch that deliver the whole solution: Read more at [Hyperswitch docs](https://docs.hyperswitch.io/). -<a href="#architectural-overview"> - <h2 id="architectural-overview">Architectural Overview</h2> -</a> -<img src="./docs/imgs/features.png" /> -<img src="./docs/imgs/non-functional-features.png" /> - -<img src="./docs/imgs/hyperswitch-architecture-v1.png" /> - <a href="#try-hyperswitch"> <h2 id="try-hyperswitch">Try Hyperswitch</h2> </a> ### 1. Local Setup -You can run Hyperswitch on your system using Docker compose after cloning this repository. +#### One-Click Setup (Recommended) + +You can run Hyperswitch on your system with a single command using our one-click setup script: ```shell git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch cd hyperswitch -docker compose up -d +scripts/setup.sh ``` -Check out the [local setup guide][local-setup-guide] for a more details on setting up the entire stack or component wise. This takes 15-mins and gives the following output -```shell -[+] Running 2/2 -✔ hyperswitch-control-center Pulled 2.9s -✔ hyperswitch-server Pulled 3.0s -[+] Running 6/0 - -✔ Container hyperswitch-pg-1 Created 0.0s -✔ Container hyperswitch-redis-standalone-1 Created 0.0s -✔ Container hyperswitch-migration_runner-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-server-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-web-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-control-center-1 Created 0.0s - -Attaching to hyperswitch-control-center-1, hyperswitch-server-1, hyperswitch-web-1, migration_runner-1, pg-1, redis-standalone-1 -``` -You've now setup Hyperswitch in your local machine. In order to verify that the server is up and running hit the health endpoint: -```shell -curl --head --request GET 'http://localhost:8080/health' -``` -The expected response here is a `200 OK` status code. This indicates that the server and all of its dependent services are functioning correctly. -Now, you can access the Control Center in your browser at `http://localhost:9000`. -The next step is to configure a connector with the Hyperswitch Control Center and try a payment. +The above script will: +- Check for prerequisites (Docker Compose/Podman) +- Set up necessary configurations +- Let you select a deployment profile: + - **Standard**: Recommended - App server + Control Center + Web SDK. + - **Full**: Standard + Monitoring + Scheduler. + - **Standalone App Server**: Core services only (Hyperswitch server, PostgreSQL, Redis) +- Start the selected services +- Check service health +- Provide access information + +The next step is to [configure a connector][configure-a-connector] with the Hyperswitch Control Center and [try a payment][try-a-payment]. + +Check out the [local setup guide][local-setup-guide] for more details on setting up the entire stack or component wise. + ### 2. Deployment on cloud @@ -136,6 +122,14 @@ We support deployment on GCP and Azure via Helm charts which takes 30-45mins. Yo You can experience the product by signing up for our [hosted sandbox](https://app.hyperswitch.io/). The signup process accepts any email ID and provides access to the entire Control Center. You can set up connectors, define workflows for routing and retries, and even try payments from the dashboard. +<a href="#architectural-overview"> + <h2 id="architectural-overview">Architectural Overview</h2> +</a> +<img src="./docs/imgs/features.png" /> +<img src="./docs/imgs/non-functional-features.png" /> + +<img src="./docs/imgs/hyperswitch-architecture-v1.png" /> + [docs-link-for-enterprise]: https://docs.hyperswitch.io/hyperswitch-cloud/quickstart [docs-link-for-developers]: https://docs.hyperswitch.io/hyperswitch-open-source/overview [contributing-guidelines]: docs/CONTRIBUTING.md @@ -144,7 +138,8 @@ You can experience the product by signing up for our [hosted sandbox](https://ap [learning-resources]: https://docs.hyperswitch.io/learn-more/payment-flows [local-setup-guide]: /docs/try_local_system.md [docker-compose-scheduler-monitoring]: /docs/try_local_system.md#running-additional-services - +[configure-a-connector]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/using-hyperswitch-control-center#add-a-payment-processor +[try-a-payment]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/test-a-payment <a href="support-feature-requests"> <h2 id="support-feature-requests">Support, Feature requests & Bugs</h2> diff --git a/docker-compose.yml b/docker-compose.yml index cb39b23b133..cc58c38e88a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,20 @@ networks: services: ### Dependencies + prestart-hook: + image: curlimages/curl-base:latest + container_name: prestart-hook + entrypoint: + [ + "/bin/sh", + "-c", + "apk add --no-cache bash && /bin/bash /prestart_hook.sh", + ] + volumes: + - ./scripts/prestart_hook.sh:/prestart_hook.sh + networks: + - router_net + pg: image: postgres:latest ports: @@ -51,7 +65,7 @@ services: environment: # format -> postgresql://DB_USER:DB_PASSWORD@HOST:PORT/DATABASE_NAME - DATABASE_URL=postgresql://db_user:db_pass@pg:5432/hyperswitch_db - + mailhog: image: mailhog/mailhog networks: @@ -86,6 +100,23 @@ services: start_period: 5s timeout: 5s + poststart-hook: + image: curlimages/curl-base:latest + container_name: poststart-hook + depends_on: + hyperswitch-server: + condition: service_healthy # Ensures it only starts when `hyperswitch-server` is healthy + entrypoint: + [ + "/bin/sh", + "-c", + "apk add --no-cache bash jq && /bin/bash /poststart_hook.sh", + ] + volumes: + - ./scripts/poststart_hook.sh:/poststart_hook.sh + networks: + - router_net + hyperswitch-producer: image: docker.juspay.io/juspaydotin/hyperswitch-producer:standalone pull_policy: always @@ -153,20 +184,13 @@ services: pull_policy: always ports: - "9050:9050" - - "9060:9060" - - "5252:5252" networks: - router_net depends_on: hyperswitch-server: condition: service_healthy environment: - - HYPERSWITCH_PUBLISHABLE_KEY=placeholder_publishable_key - - HYPERSWITCH_SECRET_KEY=placeholder_api_key - - HYPERSWITCH_SERVER_URL=http://localhost:8080 - - HYPERSWITCH_SERVER_URL_FOR_DEMO_APP=http://hyperswitch-server:8080 - - HYPERSWITCH_CLIENT_URL=http://localhost:9050 - - SELF_SERVER_URL=http://localhost:5252 + - ENABLE_LOGGING=true - SDK_ENV=local - ENV_LOGGING_URL=http://localhost:3103 - ENV_BACKEND_URL=http://localhost:8080 @@ -421,3 +445,25 @@ services: volumes: - ./config/vector.yaml:/etc/vector/vector.yaml - /var/run/docker.sock:/var/run/docker.sock + + hyperswitch-demo: + image: docker.juspay.io/juspaydotin/hyperswitch-react-demo-app:latest + pull_policy: always + ports: + - "9060:9060" + - "5252:5252" + networks: + - router_net + depends_on: + hyperswitch-server: + condition: service_healthy + hyperswitch-web: + condition: service_healthy + environment: + - HYPERSWITCH_PUBLISHABLE_KEY=placeholder_publishable_key + - HYPERSWITCH_SECRET_KEY=placeholder_api_key + - PROFILE_ID=placeholder_profile_id + - HYPERSWITCH_CLIENT_URL=http://localhost:9050 + - HYPERSWITCH_SERVER_URL=http://localhost:8080 + labels: + logs: "promtail" diff --git a/scripts/docker_output.sh b/scripts/docker_output.sh new file mode 100755 index 00000000000..80d178ca75b --- /dev/null +++ b/scripts/docker_output.sh @@ -0,0 +1,33 @@ +#! /usr/bin/env bash +set -euo pipefail + +# Define the URL to check service availability (adjust HOST and PORT if needed) +HOST="localhost" +PORT="8080" +SERVICE_URL="http://${HOST}:${PORT}/health" + +MAX_RETRIES=70 +RETRY_COUNT=0 + +# Wait until the service is available or retries are exhausted +while ! curl --silent --fail "${SERVICE_URL}" > /dev/null; do + if (( RETRY_COUNT >= MAX_RETRIES )); then + echo "" + echo "Service failed to start. Kindly check the logs." + echo "You can view the logs using the command: docker-compose logs -f <service name>" + exit 1 + fi + printf "." + sleep 2 + ((RETRY_COUNT++)) +done + +# Define ANSI 24-bit (true color) escape sequences for Light Sky Blue +LIGHT_SKY_BLUE="\033[38;2;135;206;250m" +RESET="\033[0m" + +# Print the service URLs with only the links colored +echo -e "Control Centre running at ${LIGHT_SKY_BLUE}http://localhost:9000${RESET}" +echo -e "App server running at ${LIGHT_SKY_BLUE}http://localhost:8080${RESET}" +echo -e "Web-SDK running at ${LIGHT_SKY_BLUE}http://localhost:5252/HyperLoader.js${RESET}" +echo -e "Mailhog running at ${LIGHT_SKY_BLUE}http://localhost:8025${RESET}" \ No newline at end of file diff --git a/scripts/poststart_hook.sh b/scripts/poststart_hook.sh new file mode 100755 index 00000000000..dcd06aa02bc --- /dev/null +++ b/scripts/poststart_hook.sh @@ -0,0 +1,65 @@ +#! /usr/bin/env bash +set -euo pipefail + +# Configuration +PLATFORM="docker-compose" # Change to "helm" or "cdk" as needed +VERSION="unknown" +STATUS="" +SERVER_BASE_URL="http://hyperswitch-server:8080" +HYPERSWITCH_HEALTH_URL="${SERVER_BASE_URL}/health" +HYPERSWITCH_DEEP_HEALTH_URL="${SERVER_BASE_URL}/health/ready" +WEBHOOK_URL="https://hyperswitch.gateway.scarf.sh/${PLATFORM}" + +# Fetch health status +echo "Fetching app server health status..." +HEALTH_RESPONSE=$(curl --silent --fail "${HYPERSWITCH_HEALTH_URL}") || HEALTH_RESPONSE="connection_error" + +if [[ "${HEALTH_RESPONSE}" == "connection_error" ]]; then + STATUS="error" + ERROR_MESSAGE="404 response" + + curl --get "${WEBHOOK_URL}" \ + --data-urlencode "version=${VERSION}" \ + --data-urlencode "status=${STATUS}" \ + --data-urlencode "error_message=${ERROR_MESSAGE}" + + echo "Webhook sent with connection error." + exit 0 +fi + +# Fetch Hyperswitch version +VERSION=$(curl --silent --output /dev/null --request GET --write-out '%header{x-hyperswitch-version}' "${HYPERSWITCH_DEEP_HEALTH_URL}" | sed 's/-dirty$//') + +echo "Fetching Hyperswitch health status..." +HEALTH_RESPONSE=$(curl --silent "${HYPERSWITCH_DEEP_HEALTH_URL}") + +# Prepare curl command +CURL_COMMAND=("curl" "--get" "${WEBHOOK_URL}" "--data-urlencode" "version=${VERSION}") + +# Check if the response contains an error +if [[ "$(echo "${HEALTH_RESPONSE}" | jq --raw-output '.error')" != 'null' ]]; then + STATUS="error" + ERROR_TYPE=$(echo "${HEALTH_RESPONSE}" | jq --raw-output '.error.type') + ERROR_MESSAGE=$(echo "${HEALTH_RESPONSE}" | jq --raw-output '.error.message') + ERROR_CODE=$(echo "${HEALTH_RESPONSE}" | jq --raw-output '.error.code') + + CURL_COMMAND+=( + "--data-urlencode" "status=${STATUS}" + "--data-urlencode" "error_type=${ERROR_TYPE}" + "--data-urlencode" "error_message=${ERROR_MESSAGE}" + "--data-urlencode" "error_code=${ERROR_CODE}" + ) +else + STATUS="success" + CURL_COMMAND+=("--data-urlencode" "status=${STATUS}") + + for key in $(echo "${HEALTH_RESPONSE}" | jq --raw-output 'keys_unsorted[]'); do + value=$(echo "${HEALTH_RESPONSE}" | jq --raw-output --arg key "${key}" '.[$key]') + CURL_COMMAND+=("--data-urlencode" "'${key}=${value}'") + done +fi + +# Send the webhook request +bash -c "${CURL_COMMAND[*]}" + +echo "Webhook notification sent." diff --git a/scripts/prestart_hook.sh b/scripts/prestart_hook.sh new file mode 100755 index 00000000000..c4eb16efd8c --- /dev/null +++ b/scripts/prestart_hook.sh @@ -0,0 +1,14 @@ +#! /usr/bin/env bash +set -euo pipefail + +# Define the URL and parameters +PLATFORM="docker-compose" +WEBHOOK_URL="https://hyperswitch.gateway.scarf.sh/${PLATFORM}" +VERSION="unknown" +STATUS="initiated" + +# Send the GET request +curl --get "${WEBHOOK_URL}" --data-urlencode "version=${VERSION}" --data-urlencode "status=${STATUS}" + +# Print confirmation +echo "Request sent to ${WEBHOOK_URL} with version=${VERSION} and status=${STATUS}" diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 00000000000..c40c5365c90 --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,241 @@ +#! /usr/bin/env bash +set -euo pipefail + +# ANSI color codes for pretty output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +BLUE='\033[0;34m' +BOLD='\033[1m' +NC='\033[0m' # No Color + +# Alias for docker to use podman +alias docker=podman + +# Function to print colorful messages +echo_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +echo_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +echo_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +echo_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +show_banner() { + echo -e "${BLUE}${BOLD}" + echo "" + echo " # " + echo " # # # #### ##### ## # # " + echo " # # # # # # # # # # " + echo " # # # #### # # # # # " + echo " # # # # # ##### ###### # " + echo " # # # # # # # # # # " + echo " ##### #### #### # # # # " + echo "" + echo "" + echo " # # # # ##### ###### ##### #### # # # ##### #### # # " + echo " # # # # # # # # # # # # # # # # # # " + echo " # # # # # ##### # # #### # # # # # ###### " + echo " ####### # ##### # ##### # # ## # # # # # # " + echo " # # # # # # # # # ## ## # # # # # # " + echo " # # # # ###### # # #### # # # # #### # # " + echo "" + sleep 1 + echo -e "${NC}" + echo -e "🚀 ${BLUE}One-Click Docker Setup${NC} 🚀" + echo +} + +# Detect Docker Compose version +detect_docker_compose() { + # Check Docker or Podman + if command -v docker &> /dev/null; then + CONTAINER_ENGINE="docker" + echo_success "Docker is installed." + elif command -v podman &> /dev/null; then + CONTAINER_ENGINE="podman" + echo_success "Podman is installed." + else + echo_error "Neither Docker nor Podman is installed. Please install one of them to proceed." + echo_info "Visit https://docs.docker.com/get-docker/ or https://podman.io/docs/installation for installation instructions." + echo_info "After installation, re-run this script: scripts/setup.sh" + exit 1 + fi + + # Check Docker Compose or Podman Compose + if $CONTAINER_ENGINE compose version &> /dev/null; then + DOCKER_COMPOSE="$CONTAINER_ENGINE compose" + echo_success "Compose is installed for $CONTAINER_ENGINE." + else + echo_error "Compose is not installed for $CONTAINER_ENGINE. Please install $CONTAINER_ENGINE compose to proceed." + if [ "$CONTAINER_ENGINE" = "docker" ]; then + echo_info "Visit https://docs.docker.com/compose/install/ for installation instructions." + elif [ "$CONTAINER_ENGINE" = "podman" ]; then + echo_info "Visit https://podman-desktop.io/docs/compose/setting-up-compose for installation instructions." + fi + echo_info "After installation, re-run this script: scripts/setup.sh" + exit 1 + fi +} + +check_prerequisites() { + # Check curl + if ! command -v curl &> /dev/null; then + echo_error "curl is not installed. Please install curl to proceed." + exit 1 + fi + echo_success "curl is installed." + + # Check ports + required_ports=(8080 9000 9050 5432 6379 9060) + unavailable_ports=() + + for port in "${required_ports[@]}"; do + if command -v nc &> /dev/null; then + if nc -z localhost "$port" 2>/dev/null; then + unavailable_ports+=("$port") + fi + elif command -v lsof &> /dev/null; then + if lsof -i :"$port" &> /dev/null; then + unavailable_ports+=("$port") + fi + else + echo_warning "Neither nc nor lsof available to check ports. Skipping port check." + break + fi + done + + if [ ${#unavailable_ports[@]} -ne 0 ]; then + echo_warning "The following ports are already in use: ${unavailable_ports[*]}" + echo_warning "This might cause conflicts with Hyperswitch services." + read -p "Do you want to continue anyway? (y/n): " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + exit 1 + fi + else + echo_success "All required ports are available." + fi +} + +setup_config() { + if [ ! -f "config/docker_compose.toml" ]; then + echo_error "Configuration file 'config/docker_compose.toml' not found. Please ensure the file exists and is correctly configured." + exit 1 + fi +} + +select_profile() { + echo "" + echo "Select a setup option:" + echo -e "1) Standard Setup: ${BLUE}[Recommended]${NC} Ideal for quick trial. Services included: ${BLUE}App Server, Control Center, Unified Checkout, PostgreSQL and Redis${NC}" + echo -e "2) Full Stack Setup: Ideal for comprehensive end-to-end payment testing. Services included: ${BLUE}Everything in Standard, Monitoring and Scheduler${NC}" + echo -e "3) Standalone App Server: Ideal for API-first integration testing. Services included: ${BLUE}App server, PostgreSQL and Redis)${NC}" + echo "" + local profile_selected=false + while [ "$profile_selected" = false ]; do + read -p "Enter your choice (1-3): " profile_choice + profile_choice=${profile_choice:-1} + + case $profile_choice in + 1) + PROFILE="standard" + profile_selected=true + ;; + 2) + PROFILE="full" + profile_selected=true + ;; + 3) + PROFILE="standalone" + profile_selected=true + ;; + *) + echo_error "Invalid choice. Please enter 1, 2, or 3." + ;; + esac + done + + echo "Selected setup: $PROFILE" +} + +start_services() { + + case $PROFILE in + standalone) + $DOCKER_COMPOSE up -d pg redis-standalone migration_runner hyperswitch-server + ;; + standard) + $DOCKER_COMPOSE up -d + ;; + full) + $DOCKER_COMPOSE --profile scheduler --profile monitoring --profile olap up -d + ;; + esac +} + +check_services_health() { + # Wait for the hyperswitch-server to be healthy + MAX_RETRIES=30 + RETRY_INTERVAL=5 + RETRIES=0 + + while [ $RETRIES -lt $MAX_RETRIES ]; do + if curl --silent --head --request GET 'http://localhost:8080/health' | grep "200 OK" > /dev/null; then + echo_success "Hyperswitch server is healthy!" + print_access_info # Call print_access_info only when the server is healthy + return + fi + + RETRIES=$((RETRIES+1)) + if [ $RETRIES -eq $MAX_RETRIES ]; then + echo "" + echo_error "${RED}${BOLD}Hyperswitch server did not become healthy in the expected time." + echo -e "Check logs with: $DOCKER_COMPOSE logs hyperswitch-server, Or reach out to us on slack(https://hyperswitch-io.slack.com/) for help." + echo -e "The setup process will continue, but some services might not work correctly.${NC}" + echo "" + else + echo "Waiting for server to become healthy... ($RETRIES/$MAX_RETRIES)" + sleep $RETRY_INTERVAL + fi + done +} + +print_access_info() { + echo "" + echo -e "${GREEN}${BOLD}Setup complete! You can access Hyperswitch services at:${NC}" + echo "" + + if [ "$PROFILE" != "standalone" ]; then + echo -e " • ${GREEN}${BOLD}Control Center${NC}: ${BLUE}${BOLD}http://localhost:9000${NC}" + fi + + echo -e " • ${GREEN}${BOLD}App Server${NC}: ${BLUE}${BOLD}http://localhost:8080${NC}" + + if [ "$PROFILE" != "standalone" ]; then + echo -e " • ${GREEN}${BOLD}Unified Checkout${NC}: ${BLUE}${BOLD}http://localhost:9060${NC}" + fi + + if [ "$PROFILE" = "full" ]; then + echo -e " • ${GREEN}${BOLD}Monitoring (Grafana)${NC}: ${BLUE}${BOLD}http://localhost:3000${NC}" + fi + echo "" + echo_info "To stop all services, run: $DOCKER_COMPOSE down" +} + +# Main execution flow +show_banner +detect_docker_compose +check_prerequisites +setup_config +select_profile +start_services +check_services_health # This will call print_access_info if the server is healthy
2025-04-24T13:02:22Z
This PR contains the docker compose file changes for stable release. The PRs included in this file are - https://github.com/juspay/hyperswitch/pull/7762 - https://github.com/juspay/hyperswitch/pull/7839 - https://github.com/juspay/hyperswitch/pull/7841 - https://github.com/juspay/hyperswitch/pull/7653
a387bd4711a12c826f8ac0f66df17336778720c5
[ "README.md", "docker-compose.yml", "scripts/docker_output.sh", "scripts/poststart_hook.sh", "scripts/prestart_hook.sh", "scripts/setup.sh" ]
juspay/hyperswitch
juspay__hyperswitch-7910
Bug: refactor(connector): [stripebilling] Change BillingConnectorPaymentSync from charges api to payment intents api. Change the url from charge api to stripes payment intent api.
diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs index 3fe121a1fc3..39a8e5a0dae 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -599,7 +599,7 @@ impl connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( - "{}v1/charges/{}", + "{}v1/payment_intents/{}?expand[0]=latest_charge", self.base_url(connectors), req.request.billing_connector_psync_id )) @@ -632,10 +632,10 @@ impl recovery_router_data_types::BillingConnectorPaymentsSyncRouterData, errors::ConnectorError, > { - let response: stripebilling::StripebillingRecoveryDetailsData = res + let response: stripebilling::StripebillingBillingConnectorPaymentSyncResponseData = res .response - .parse_struct::<stripebilling::StripebillingRecoveryDetailsData>( - "StripebillingRecoveryDetailsData", + .parse_struct::<stripebilling::StripebillingBillingConnectorPaymentSyncResponseData>( + "StripebillingBillingConnectorPaymentSyncResponseData", ) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -807,7 +807,9 @@ impl webhooks::IncomingWebhook for Stripebilling { stripebilling::StripebillingWebhookBody::get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId(webhook.data.object.charge), + api_models::payments::PaymentIdType::ConnectorTransactionId( + webhook.data.object.payment_intent, + ), )) } diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs index 3ff7d04fde6..1056006642f 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs @@ -296,6 +296,7 @@ pub struct StripebillingWebhookObject { #[serde(rename = "amount_remaining")] pub amount: common_utils::types::MinorUnit, pub charge: String, + pub payment_intent: String, } #[derive(Debug, Serialize, Deserialize)] @@ -346,7 +347,12 @@ impl TryFrom<StripebillingInvoiceBody> for revenue_recovery::RevenueRecoveryInvo } #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct StripebillingRecoveryDetailsData { +pub struct StripebillingBillingConnectorPaymentSyncResponseData { + pub latest_charge: StripebillingLatestChargeData, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct StripebillingLatestChargeData { #[serde(rename = "id")] pub charge_id: String, pub status: StripebillingChargeStatus, @@ -410,7 +416,7 @@ impl TryFrom< ResponseRouterData< recovery_router_flows::BillingConnectorPaymentsSync, - StripebillingRecoveryDetailsData, + StripebillingBillingConnectorPaymentSyncResponseData, recovery_request_types::BillingConnectorPaymentsSyncRequest, recovery_response_types::BillingConnectorPaymentsSyncResponse, >, @@ -420,45 +426,45 @@ impl fn try_from( item: ResponseRouterData< recovery_router_flows::BillingConnectorPaymentsSync, - StripebillingRecoveryDetailsData, + StripebillingBillingConnectorPaymentSyncResponseData, recovery_request_types::BillingConnectorPaymentsSyncRequest, recovery_response_types::BillingConnectorPaymentsSyncResponse, >, ) -> Result<Self, Self::Error> { - let merchant_reference_id = id_type::PaymentReferenceId::from_str( - &item.response.invoice_id, - ) - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "invoice_id", - })?; + let charge_details = item.response.latest_charge; + let merchant_reference_id = + id_type::PaymentReferenceId::from_str(charge_details.invoice_id.as_str()) + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "invoice_id", + })?; let connector_transaction_id = Some(common_utils::types::ConnectorTransactionId::from( - item.response.charge_id, + charge_details.charge_id, )); Ok(Self { response: Ok( recovery_response_types::BillingConnectorPaymentsSyncResponse { - status: item.response.status.into(), - amount: item.response.amount, - currency: item.response.currency, + status: charge_details.status.into(), + amount: charge_details.amount, + currency: charge_details.currency, merchant_reference_id, connector_account_reference_id: MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA .to_string(), connector_transaction_id, - error_code: item.response.failure_code, - error_message: item.response.failure_message, - processor_payment_method_token: item.response.payment_method, - connector_customer_id: item.response.customer, - transaction_created_at: Some(item.response.created), + error_code: charge_details.failure_code, + error_message: charge_details.failure_message, + processor_payment_method_token: charge_details.payment_method, + connector_customer_id: charge_details.customer, + transaction_created_at: Some(charge_details.created), payment_method_sub_type: common_enums::PaymentMethodType::from( - item.response + charge_details .payment_method_details .card_funding_type .funding, ), payment_method_type: common_enums::PaymentMethod::from( - item.response.payment_method_details.type_of_payment_method, + charge_details.payment_method_details.type_of_payment_method, ), }, ),
2025-04-24T12:52:11Z
## Description This PR changes the url of billing connector payment sync flow from using stripe charge api to stripe payment intents api. Because in Recovery Flow there is a chance to call stripe's psync flow to update the error codes and other details for an attempt. And psync flow accepts payment intent id rather than the charge id. To reuse the existing flow we need payment_intent id to propogate. ## Motivation and Context #
54e910582fac9bd6fe300a9a96926adf5123403e
To test this You can follow the steps of this PR: #7461 Tested it locally. And the logs are as following. <img width="1290" alt="Screenshot 2025-04-24 at 6 10 52 PM" src="https://github.com/user-attachments/assets/7803e047-7ef5-4f58-85a5-f00313f3ab04" /> <img width="1296" alt="Screenshot 2025-04-24 at 6 11 02 PM" src="https://github.com/user-attachments/assets/80049b8e-17fc-40f3-b6ae-d5977ea3ab79" /> <img width="1288" alt="Screenshot 2025-04-24 at 6 10 25 PM" src="https://github.com/user-attachments/assets/cc252496-1924-4e9d-8daa-563c15e85979" />
[ "crates/hyperswitch_connectors/src/connectors/stripebilling.rs", "crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7891
Bug: Standardize Redis Key Prefix for User Lineage Context Currently, the lineage context is cached in Redis using tenant-specific key prefixes (public_, public_v2_). This causes inconsistencies across V1 and V2 environments — especially during login/logout flows — as lineage context data becomes deployment-specific. Need to introduce a new Redis connection helper that overrides the prefix with the global value from config (global).
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 3e339a2a570..13190125d7d 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -143,6 +143,27 @@ pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnect .attach_printable("Failed to get redis connection") } +pub fn get_redis_connection_for_global_tenant( + state: &SessionState, +) -> UserResult<Arc<RedisConnectionPool>> { + let redis_connection_pool = state + .store + .get_redis_conn() + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let global_tenant_prefix = &state.conf.multitenancy.global_tenant.redis_key_prefix; + + Ok(Arc::new(RedisConnectionPool { + pool: Arc::clone(&redis_connection_pool.pool), + key_prefix: global_tenant_prefix.to_string(), + config: Arc::clone(&redis_connection_pool.config), + subscriber: Arc::clone(&redis_connection_pool.subscriber), + publisher: Arc::clone(&redis_connection_pool.publisher), + is_redis_available: Arc::clone(&redis_connection_pool.is_redis_available), + })) +} + impl ForeignFrom<&user_api::AuthConfig> for UserAuthType { fn foreign_from(from: &user_api::AuthConfig) -> Self { match *from { @@ -347,7 +368,7 @@ pub async fn get_lineage_context_from_cache( state: &SessionState, user_id: &str, ) -> UserResult<Option<LineageContext>> { - let connection = get_redis_connection(state)?; + let connection = get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); let lineage_context = connection .get_key::<Option<String>>(&key.into()) @@ -371,7 +392,7 @@ pub async fn set_lineage_context_in_cache( user_id: &str, lineage_context: LineageContext, ) -> UserResult<()> { - let connection = get_redis_connection(state)?; + let connection = get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); let serialized_lineage_context: String = serde_json::to_string(&lineage_context) .change_context(UserErrors::InternalServerError)
2025-04-24T12:20:59Z
## Description <!-- Describe your changes in detail --> This PR updates the lineage context Redis caching logic to use a dedicated global Redis key prefix (`global`) instead of the default tenant-scoped prefixes (`public_`, `public_v2_`), causing inconsistencies between deployments (i.e., v1 and v2). Introduced a new helper: `get_redis_connection_for_global_tenant` - Fetches Redis connection with `key_prefix` set to `global`. - Updated lineage context caching (`get_lineage_context_from_cache`, `set_lineage_context_in_cache`) to use the global Redis connection This will enable [https://github.com/juspay/hyperswitch/pull/7871](https://github.com/juspay/hyperswitch/pull/7871) to work with both v1 and v2 merchant accounts. The redis-key should now be in the format of global:LINEAGE_CONTEXT_<user_id> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Previously, lineage context was being cached with environment-specific prefixes (`public_` in V1 and `public_v2_` in V2), leading to inconsistencies in user experience during login/logout flows across deployments. Switching to a consistent global prefix resolves this by isolating user lineage data under a unified Redis namespace. #
54e910582fac9bd6fe300a9a96926adf5123403e
Use test cases from this PR: [https://github.com/juspay/hyperswitch/pull/7871](https://github.com/juspay/hyperswitch/pull/7871) The key should now be in the format of global:LINEAGE_CONTEXT_<user_id> <img width="1202" alt="image" src="https://github.com/user-attachments/assets/830883c3-5e08-4e00-b101-c2af6a251564" />
[ "crates/router/src/utils/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7886
Bug: [FIX] remove open-router configuration from docker compose toml
diff --git a/config/docker_compose.toml b/config/docker_compose.toml index d8f2d4bd34d..2f2f6843154 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -899,6 +899,3 @@ background_color = "#FFFFFF" [platform] enabled = true - -[open_router] -enabled = false
2025-04-24T04:27:28Z
## Description <!-- Describe your changes in detail --> This PR removes the open-router configuration from docker_compose.toml ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
f966defb3bdb0cf8a0f55b23ba3e7eaa61af06db
Since this is just a docker config change and cypress was failing due to this, ensuring CI check pass for cypress should suffice
[ "config/docker_compose.toml" ]
juspay/hyperswitch
juspay__hyperswitch-7889
Bug: Add onboarding flow for VSAAS - Support for endpoint to create a platform - Create platform org and platform merchant account - Support to create connected merchant account inside platform org - Modify existing list responses for org and merchant, to distinguish platform from standard.
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 5e0564b4187..1a20e7b90b0 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -15,13 +15,13 @@ use crate::user::{ CreateTenantUserRequest, CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, InviteUserRequest, - ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, - SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, - SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, - TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest, - UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantAccountResponse, - UserMerchantCreate, UserOrgMerchantCreateRequest, VerifyEmailRequest, - VerifyRecoveryCodeRequest, VerifyTotpRequest, + PlatformAccountCreateRequest, PlatformAccountCreateResponse, ReInviteUserRequest, + RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, + SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest, + SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse, + TwoFactorStatus, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, + UserFromEmailRequest, UserMerchantAccountResponse, UserMerchantCreate, + UserOrgMerchantCreateRequest, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; common_utils::impl_api_event_type!( @@ -39,6 +39,8 @@ common_utils::impl_api_event_type!( SwitchProfileRequest, CreateInternalUserRequest, CreateTenantUserRequest, + PlatformAccountCreateRequest, + PlatformAccountCreateResponse, UserOrgMerchantCreateRequest, UserMerchantAccountResponse, UserMerchantCreate, diff --git a/crates/api_models/src/organization.rs b/crates/api_models/src/organization.rs index c6bc3924d11..e7ec5d32d74 100644 --- a/crates/api_models/src/organization.rs +++ b/crates/api_models/src/organization.rs @@ -1,14 +1,17 @@ +use common_enums::OrganizationType; use common_utils::{id_type, pii}; use utoipa::ToSchema; pub struct OrganizationNew { pub org_id: id_type::OrganizationId, + pub org_type: OrganizationType, pub org_name: Option<String>, } impl OrganizationNew { - pub fn new(org_name: Option<String>) -> Self { + pub fn new(org_type: OrganizationType, org_name: Option<String>) -> Self { Self { org_id: id_type::OrganizationId::default(), + org_type, org_name, } } @@ -47,6 +50,9 @@ pub struct OrganizationUpdateRequest { /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, + + /// Platform merchant id is unique distiguisher for special merchant in the platform org + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index aa39877f0c7..d979a2d5a11 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -130,6 +130,20 @@ pub struct UserOrgMerchantCreateRequest { pub merchant_name: Secret<String>, } +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct PlatformAccountCreateRequest { + pub organization_name: Secret<String>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct PlatformAccountCreateResponse { + pub org_id: id_type::OrganizationId, + pub org_name: Option<String>, + pub org_type: common_enums::OrganizationType, + pub merchant_id: id_type::MerchantId, + pub merchant_account_type: common_enums::MerchantAccountType, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserMerchantCreate { pub company_name: String, @@ -381,6 +395,7 @@ pub struct UserTransferKeyResponse { pub struct ListOrgsForUserResponse { pub org_id: id_type::OrganizationId, pub org_name: Option<String>, + pub org_type: common_enums::OrganizationType, } #[derive(Debug, serde::Serialize)] @@ -388,6 +403,7 @@ pub struct UserMerchantAccountResponse { pub merchant_id: id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, pub version: common_enums::ApiVersion, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 2643b97904c..01abaf277f0 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -6,7 +6,7 @@ use std::{ num::{ParseFloatError, TryFromIntError}, }; -pub use accounts::MerchantProductType; +pub use accounts::{MerchantAccountType, MerchantProductType, OrganizationType}; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs index e5b3ef733c6..7500dcac7c8 100644 --- a/crates/common_enums/src/enums/accounts.rs +++ b/crates/common_enums/src/enums/accounts.rs @@ -26,3 +26,46 @@ pub enum MerchantProductType { CostObservability, DynamicRouting, } + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum MerchantAccountType { + #[default] + Standard, + Platform, + Connected, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum OrganizationType { + #[default] + Standard, + Platform, +} diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 40c6a1e4ff3..e0b421f40c9 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -54,6 +54,7 @@ pub struct MerchantAccount { pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: Option<common_enums::MerchantAccountType>, } #[cfg(feature = "v1")] @@ -88,6 +89,7 @@ pub struct MerchantAccountSetter { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] @@ -125,6 +127,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, + merchant_account_type: Some(item.merchant_account_type), } } } @@ -158,6 +161,7 @@ pub struct MerchantAccount { pub is_platform_account: bool, pub id: common_utils::id_type::MerchantId, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: Option<common_enums::MerchantAccountType>, } #[cfg(feature = "v2")] @@ -177,6 +181,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, + merchant_account_type: Some(item.merchant_account_type), } } } @@ -196,6 +201,7 @@ pub struct MerchantAccountSetter { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } impl MerchantAccount { @@ -245,6 +251,7 @@ pub struct MerchantAccountNew { pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] @@ -263,6 +270,7 @@ pub struct MerchantAccountNew { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] @@ -311,6 +319,7 @@ impl MerchantAccountUpdateInternal { id: source.id, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), product_type: product_type.or(source.product_type), + merchant_account_type: source.merchant_account_type, } } } @@ -417,6 +426,7 @@ impl MerchantAccountUpdateInternal { is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), id: source.id, product_type: product_type.or(source.product_type), + merchant_account_type: source.merchant_account_type, } } } diff --git a/crates/diesel_models/src/organization.rs b/crates/diesel_models/src/organization.rs index 1ca86225934..ffa1e94fcfa 100644 --- a/crates/diesel_models/src/organization.rs +++ b/crates/diesel_models/src/organization.rs @@ -29,6 +29,8 @@ pub struct Organization { #[allow(dead_code)] organization_name: Option<String>, pub version: common_enums::ApiVersion, + pub organization_type: Option<common_enums::OrganizationType>, + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] @@ -46,6 +48,8 @@ pub struct Organization { id: id_type::OrganizationId, organization_name: Option<String>, pub version: common_enums::ApiVersion, + pub organization_type: Option<common_enums::OrganizationType>, + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] @@ -61,6 +65,8 @@ impl Organization { id: _, organization_name: _, version, + organization_type, + platform_merchant_id, } = org_new; Self { id: Some(org_id.clone()), @@ -72,8 +78,14 @@ impl Organization { created_at, modified_at, version, + organization_type: Some(organization_type), + platform_merchant_id, } } + + pub fn get_organization_type(&self) -> common_enums::OrganizationType { + self.organization_type.unwrap_or_default() + } } #[cfg(feature = "v2")] @@ -87,6 +99,8 @@ impl Organization { created_at, modified_at, version, + organization_type, + platform_merchant_id, } = org_new; Self { id, @@ -96,8 +110,14 @@ impl Organization { created_at, modified_at, version, + organization_type: Some(organization_type), + platform_merchant_id, } } + + pub fn get_organization_type(&self) -> common_enums::OrganizationType { + self.organization_type.unwrap_or_default() + } } #[cfg(feature = "v1")] @@ -113,6 +133,8 @@ pub struct OrganizationNew { pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, + pub organization_type: common_enums::OrganizationType, + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] @@ -126,11 +148,17 @@ pub struct OrganizationNew { pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, + pub organization_type: common_enums::OrganizationType, + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] impl OrganizationNew { - pub fn new(id: id_type::OrganizationId, organization_name: Option<String>) -> Self { + pub fn new( + id: id_type::OrganizationId, + organization_type: common_enums::OrganizationType, + organization_name: Option<String>, + ) -> Self { Self { org_id: id.clone(), org_name: organization_name.clone(), @@ -141,13 +169,19 @@ impl OrganizationNew { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, + organization_type, + platform_merchant_id: None, } } } #[cfg(feature = "v2")] impl OrganizationNew { - pub fn new(id: id_type::OrganizationId, organization_name: Option<String>) -> Self { + pub fn new( + id: id_type::OrganizationId, + organization_type: common_enums::OrganizationType, + organization_name: Option<String>, + ) -> Self { Self { id, organization_name, @@ -156,6 +190,8 @@ impl OrganizationNew { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, + organization_type, + platform_merchant_id: None, } } } @@ -169,6 +205,7 @@ pub struct OrganizationUpdateInternal { organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, + platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] @@ -179,6 +216,7 @@ pub struct OrganizationUpdateInternal { organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, + platform_merchant_id: Option<id_type::MerchantId>, } pub enum OrganizationUpdate { @@ -186,6 +224,7 @@ pub enum OrganizationUpdate { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, + platform_merchant_id: Option<id_type::MerchantId>, }, } @@ -197,12 +236,14 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal { organization_name, organization_details, metadata, + platform_merchant_id, } => Self { org_name: organization_name.clone(), organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), + platform_merchant_id, }, } } @@ -216,11 +257,13 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal { organization_name, organization_details, metadata, + platform_merchant_id, } => Self { organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), + platform_merchant_id, }, } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index c25acc386f5..46a36bab8c9 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -750,6 +750,8 @@ diesel::table! { id -> Nullable<Varchar>, #[max_length = 64] product_type -> Nullable<Varchar>, + #[max_length = 64] + merchant_account_type -> Nullable<Varchar>, } } @@ -823,6 +825,10 @@ diesel::table! { id -> Nullable<Varchar>, organization_name -> Nullable<Text>, version -> ApiVersion, + #[max_length = 64] + organization_type -> Nullable<Varchar>, + #[max_length = 64] + platform_merchant_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 8f857a4db26..d9df67f0fb7 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -738,6 +738,8 @@ diesel::table! { id -> Varchar, #[max_length = 64] product_type -> Nullable<Varchar>, + #[max_length = 64] + merchant_account_type -> Nullable<Varchar>, } } @@ -800,6 +802,10 @@ diesel::table! { id -> Varchar, organization_name -> Nullable<Text>, version -> ApiVersion, + #[max_length = 64] + organization_type -> Nullable<Varchar>, + #[max_length = 64] + platform_merchant_id -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index 8657af91c57..2cd1af98639 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -49,6 +49,7 @@ pub struct MerchantAccount { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] @@ -85,6 +86,7 @@ pub struct MerchantAccountSetter { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] @@ -121,6 +123,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, + merchant_account_type: item.merchant_account_type, } } } @@ -142,6 +145,7 @@ pub struct MerchantAccountSetter { pub is_platform_account: bool, pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] @@ -161,6 +165,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { is_platform_account, version, product_type, + merchant_account_type, } = item; Self { id, @@ -176,6 +181,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { is_platform_account, version, product_type, + merchant_account_type, } } } @@ -196,6 +202,7 @@ pub struct MerchantAccount { pub is_platform_account: bool, pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } impl MerchantAccount { @@ -575,6 +582,7 @@ impl super::behaviour::Conversion for MerchantAccount { version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self.product_type, + merchant_account_type: self.merchant_account_type, }; Ok(diesel_models::MerchantAccount::from(setter)) @@ -637,6 +645,7 @@ impl super::behaviour::Conversion for MerchantAccount { is_platform_account: item.is_platform_account, version: item.version, product_type: item.product_type, + merchant_account_type: item.merchant_account_type.unwrap_or_default(), }) } .await @@ -662,6 +671,7 @@ impl super::behaviour::Conversion for MerchantAccount { product_type: self .product_type .or(Some(common_enums::MerchantProductType::Orchestration)), + merchant_account_type: self.merchant_account_type, }) } } @@ -703,6 +713,7 @@ impl super::behaviour::Conversion for MerchantAccount { version: self.version, is_platform_account: self.is_platform_account, product_type: self.product_type, + merchant_account_type: self.merchant_account_type, }; Ok(diesel_models::MerchantAccount::from(setter)) @@ -782,6 +793,7 @@ impl super::behaviour::Conversion for MerchantAccount { version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, + merchant_account_type: item.merchant_account_type.unwrap_or_default(), }) } .await @@ -825,6 +837,7 @@ impl super::behaviour::Conversion for MerchantAccount { product_type: self .product_type .or(Some(common_enums::MerchantProductType::Orchestration)), + merchant_account_type: self.merchant_account_type, }) } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index a5c2fbd483f..7919af296d3 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -4,6 +4,7 @@ use api_models::{ admin::{self as admin_types}, enums as api_enums, routing as routing_types, }; +use common_enums::{MerchantAccountType, OrganizationType}; use common_utils::{ date_time, ext_traits::{AsyncExt, Encode, OptionExt, ValueExt}, @@ -142,6 +143,7 @@ pub async fn update_organization( organization_name: req.organization_name, organization_details: req.organization_details, metadata: req.metadata, + platform_merchant_id: req.platform_merchant_id, }; state .accounts_store @@ -336,6 +338,31 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .create_or_validate(db) .await?; + let merchant_account_type = match organization.get_organization_type() { + OrganizationType::Standard => MerchantAccountType::Standard, + + OrganizationType::Platform => { + let accounts = state + .store + .list_merchant_accounts_by_organization_id( + &state.into(), + &organization.get_organization_id(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let platform_account_exists = accounts + .iter() + .any(|account| account.merchant_account_type == MerchantAccountType::Platform); + + if platform_account_exists { + MerchantAccountType::Connected + } else { + MerchantAccountType::Platform + } + } + }; + let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); @@ -405,6 +432,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { version: common_types::consts::API_VERSION, is_platform_account: false, product_type: self.product_type, + merchant_account_type, }, ) } @@ -461,7 +489,10 @@ impl CreateOrValidateOrganization { match self { #[cfg(feature = "v1")] Self::Create => { - let new_organization = api_models::organization::OrganizationNew::new(None); + let new_organization = api_models::organization::OrganizationNew::new( + OrganizationType::Standard, + None, + ); let db_organization = ForeignFrom::foreign_from(new_organization); db.insert_organization(db_organization) .await @@ -629,6 +660,18 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .create_or_validate(db) .await?; + let merchant_account_type = match organization.get_organization_type() { + OrganizationType::Standard => MerchantAccountType::Standard, + // Blocking v2 merchant account create for platform + OrganizationType::Platform => { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Merchant account creation is not allowed for a platform organization" + .to_string(), + } + .into()) + } + }; + let key = key_store.key.into_inner(); let id = identifier.to_owned(); let key_manager_state = state.into(); @@ -675,6 +718,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { is_platform_account: false, version: common_types::consts::API_VERSION, product_type: self.product_type, + merchant_account_type, }), ) } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 6e5360d8848..ff90ca1dfac 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1497,6 +1497,71 @@ pub async fn create_tenant_user( Ok(ApplicationResponse::StatusOk) } +#[cfg(feature = "v1")] +pub async fn create_platform_account( + state: SessionState, + user_from_token: auth::UserFromToken, + req: user_api::PlatformAccountCreateRequest, +) -> UserResponse<user_api::PlatformAccountCreateResponse> { + let user_from_db = user_from_token.get_user_from_db(&state).await?; + + let new_merchant = domain::NewUserMerchant::try_from(req)?; + let new_organization = new_merchant.get_new_organization(); + let organization = new_organization.insert_org_in_db(state.clone()).await?; + + let merchant_account = new_merchant + .create_new_merchant_and_insert_in_db(state.to_owned()) + .await?; + + state + .accounts_store + .update_organization_by_org_id( + &organization.get_organization_id(), + diesel_models::organization::OrganizationUpdate::Update { + organization_name: None, + organization_details: None, + metadata: None, + platform_merchant_id: Some(merchant_account.get_id().to_owned()), + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + let now = common_utils::date_time::now(); + + let user_role = domain::NewUserRole { + user_id: user_from_db.get_user_id().to_owned(), + role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + status: UserStatus::Active, + created_by: user_from_token.user_id.clone(), + last_modified_by: user_from_token.user_id.clone(), + created_at: now, + last_modified: now, + entity: domain::NoLevel, + }; + + user_role + .add_entity(domain::OrganizationLevel { + tenant_id: user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), + org_id: merchant_account.organization_id.clone(), + }) + .insert_in_v2(&state) + .await?; + + Ok(ApplicationResponse::Json( + user_api::PlatformAccountCreateResponse { + org_id: organization.get_organization_id(), + org_name: organization.get_organization_name(), + org_type: organization.organization_type.unwrap_or_default(), + merchant_id: merchant_account.get_id().to_owned(), + merchant_account_type: merchant_account.merchant_account_type, + }, + )) +} + #[cfg(feature = "v1")] pub async fn create_org_merchant_for_user( state: SessionState, @@ -1537,6 +1602,7 @@ pub async fn create_merchant_account( merchant_id: domain_merchant_account.get_id().to_owned(), merchant_name: domain_merchant_account.merchant_name, product_type: domain_merchant_account.product_type, + merchant_account_type: domain_merchant_account.merchant_account_type, version: domain_merchant_account.version, }, )) @@ -2893,6 +2959,7 @@ pub async fn list_orgs_for_user( .map(|org| user_api::ListOrgsForUserResponse { org_id: org.get_organization_id(), org_name: org.get_organization_name(), + org_type: org.organization_type.unwrap_or_default(), }) .collect::<Vec<_>>(); @@ -2975,6 +3042,7 @@ pub async fn list_merchants_for_user_in_org( merchant_name: merchant_account.merchant_name.clone(), merchant_id: merchant_account.get_id().to_owned(), product_type: merchant_account.product_type, + merchant_account_type: merchant_account.merchant_account_type, version: merchant_account.version, }) .collect::<Vec<_>>(), diff --git a/crates/router/src/db/organization.rs b/crates/router/src/db/organization.rs index b1dc58f0402..bb4f125db2a 100644 --- a/crates/router/src/db/organization.rs +++ b/crates/router/src/db/organization.rs @@ -119,12 +119,14 @@ impl OrganizationInterface for super::MockDb { organization_name, organization_details, metadata, + platform_merchant_id, } => { organization_name .as_ref() .map(|org_name| org.set_organization_name(org_name.to_owned())); organization_details.clone_into(&mut org.organization_details); metadata.clone_into(&mut org.metadata); + platform_merchant_id.clone_into(&mut org.platform_merchant_id); org } }) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9dc67be1d2d..61d5e709420 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2183,6 +2183,7 @@ impl User { .service( web::resource("/tenant_signup").route(web::post().to(user::create_tenant_user)), ) + .service(web::resource("/create_platform").route(web::post().to(user::create_platform))) .service(web::resource("/create_org").route(web::post().to(user::user_org_create))) .service( web::resource("/create_merchant") diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 760a4bc890c..9e0642b4984 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -247,6 +247,7 @@ impl From<Flow> for ApiIdentifier { | Flow::SwitchOrg | Flow::SwitchMerchantV2 | Flow::SwitchProfile + | Flow::CreatePlatformAccount | Flow::UserOrgMerchantCreate | Flow::UserMerchantAccountCreate | Flow::GenerateSampleData diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index d075048ddb6..a6d9d75dc43 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -259,6 +259,29 @@ pub async fn create_tenant_user( .await } +#[cfg(feature = "v1")] +pub async fn create_platform( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::PlatformAccountCreateRequest>, +) -> HttpResponse { + let flow = Flow::CreatePlatformAccount; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, user: auth::UserFromToken, json_payload, _| { + user_core::create_platform_account(state, user, json_payload) + }, + &auth::JWTAuth { + permission: Permission::OrganizationAccountWrite, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v1")] pub async fn user_org_create( state: web::Data<AppState>, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 016995cb550..80dbb6d5258 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -23,7 +23,7 @@ use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; -use router_env::{env, logger}; +use router_env::logger; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] @@ -267,9 +267,10 @@ impl NewUserOrganization { impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { - let new_organization = api_org::OrganizationNew::new(Some( - UserCompanyName::new(value.company_name)?.get_secret(), - )); + let new_organization = api_org::OrganizationNew::new( + common_enums::OrganizationType::Standard, + Some(UserCompanyName::new(value.company_name)?.get_secret()), + ); let db_organization = ForeignFrom::foreign_from(new_organization); Ok(Self(db_organization)) } @@ -277,7 +278,8 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization { impl From<user_api::SignUpRequest> for NewUserOrganization { fn from(_value: user_api::SignUpRequest) -> Self { - let new_organization = api_org::OrganizationNew::new(None); + let new_organization = + api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } @@ -285,7 +287,8 @@ impl From<user_api::SignUpRequest> for NewUserOrganization { impl From<user_api::ConnectAccountRequest> for NewUserOrganization { fn from(_value: user_api::ConnectAccountRequest) -> Self { - let new_organization = api_org::OrganizationNew::new(None); + let new_organization = + api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } @@ -297,6 +300,7 @@ impl From<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for Ne ) -> Self { let new_organization = api_org::OrganizationNew { org_id, + org_type: common_enums::OrganizationType::Standard, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); @@ -308,15 +312,28 @@ impl From<UserMerchantCreateRequestWithToken> for NewUserOrganization { fn from(value: UserMerchantCreateRequestWithToken) -> Self { Self(diesel_org::OrganizationNew::new( value.2.org_id, + common_enums::OrganizationType::Standard, Some(value.1.company_name), )) } } +impl From<user_api::PlatformAccountCreateRequest> for NewUserOrganization { + fn from(value: user_api::PlatformAccountCreateRequest) -> Self { + let new_organization = api_org::OrganizationNew::new( + common_enums::OrganizationType::Platform, + Some(value.organization_name.expose()), + ); + let db_organization = ForeignFrom::foreign_from(new_organization); + Self(db_organization) + } +} + type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken); impl From<InviteeUserRequestWithInvitedUserToken> for NewUserOrganization { fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self { - let new_organization = api_org::OrganizationNew::new(None); + let new_organization = + api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } @@ -331,6 +348,7 @@ impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for Ne ) -> Self { let new_organization = api_org::OrganizationNew { org_id: merchant_account_identifier.org_id, + org_type: common_enums::OrganizationType::Standard, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); @@ -349,7 +367,11 @@ impl ForeignFrom<api_models::user::UserOrgMerchantCreateRequest> metadata, .. } = item; - let mut org_new_db = Self::new(org_id, Some(organization_name.expose())); + let mut org_new_db = Self::new( + org_id, + common_enums::OrganizationType::Standard, + Some(organization_name.expose()), + ); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db @@ -698,11 +720,8 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> { - let merchant_id = if matches!(env::which(), env::Env::Production) { - id_type::MerchantId::try_from(MerchantId::new(value.1.company_name.clone())?)? - } else { - id_type::MerchantId::new_from_unix_timestamp() - }; + let merchant_id = + utils::user::generate_env_specific_merchant_id(value.1.company_name.clone())?; let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, @@ -719,6 +738,24 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { } } +impl TryFrom<user_api::PlatformAccountCreateRequest> for NewUserMerchant { + type Error = error_stack::Report<UserErrors>; + + fn try_from(value: user_api::PlatformAccountCreateRequest) -> UserResult<Self> { + let merchant_id = utils::user::generate_env_specific_merchant_id( + value.organization_name.clone().expose(), + )?; + + let new_organization = NewUserOrganization::from(value); + Ok(Self { + company_name: None, + merchant_id, + new_organization, + product_type: Some(consts::user::DEFAULT_PRODUCT_TYPE), + }) + } +} + #[derive(Debug, Clone)] pub struct MerchantAccountIdentifier { pub merchant_id: id_type::MerchantId, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 187f0c864d3..fdf52240320 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1817,7 +1817,7 @@ impl ForeignFrom<api_models::organization::OrganizationNew> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationNew) -> Self { - Self::new(item.org_id, item.org_name) + Self::new(item.org_id, item.org_type, item.org_name) } } @@ -1825,13 +1825,17 @@ impl ForeignFrom<api_models::organization::OrganizationCreateRequest> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationCreateRequest) -> Self { - let org_new = api_models::organization::OrganizationNew::new(None); + // Create a new organization with a standard type by default + let org_new = api_models::organization::OrganizationNew::new( + common_enums::OrganizationType::Standard, + None, + ); let api_models::organization::OrganizationCreateRequest { organization_name, organization_details, metadata, } = item; - let mut org_new_db = Self::new(org_new.org_id, Some(organization_name)); + let mut org_new_db = Self::new(org_new.org_id, org_new.org_type, Some(organization_name)); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 13190125d7d..61fb8472f6d 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -312,11 +312,7 @@ pub fn create_merchant_account_request_for_org( org: organization::Organization, product_type: common_enums::MerchantProductType, ) -> UserResult<api_models::admin::MerchantAccountCreate> { - let merchant_id = if matches!(env::which(), env::Env::Production) { - id_type::MerchantId::try_from(domain::MerchantId::new(req.merchant_name.clone().expose())?)? - } else { - id_type::MerchantId::new_from_unix_timestamp() - }; + let merchant_id = generate_env_specific_merchant_id(req.merchant_name.clone().expose())?; let company_name = domain::UserCompanyName::new(req.merchant_name.expose())?; Ok(api_models::admin::MerchantAccountCreate { @@ -409,3 +405,12 @@ pub async fn set_lineage_context_in_cache( Ok(()) } + +pub fn generate_env_specific_merchant_id(value: String) -> UserResult<id_type::MerchantId> { + if matches!(env::which(), env::Env::Production) { + let raw_id = domain::MerchantId::new(value)?; + Ok(id_type::MerchantId::try_from(raw_id)?) + } else { + Ok(id_type::MerchantId::new_from_unix_timestamp()) + } +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 6a4ad4bcabe..abc115dc288 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -407,6 +407,8 @@ pub enum Flow { UpdateUserRole, /// Create merchant account for user in a org UserMerchantAccountCreate, + /// Create Platform + CreatePlatformAccount, /// Create Org in a given tenancy UserOrgMerchantCreate, /// Generate Sample Data diff --git a/migrations/2025-04-10-095823_add_platform_context_in_organization/down.sql b/migrations/2025-04-10-095823_add_platform_context_in_organization/down.sql new file mode 100644 index 00000000000..65379a80226 --- /dev/null +++ b/migrations/2025-04-10-095823_add_platform_context_in_organization/down.sql @@ -0,0 +1,6 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE organization DROP COLUMN IF EXISTS organization_type; +ALTER TABLE organization DROP COLUMN IF EXISTS platform_merchant_id; + +ALTER TABLE merchant_account DROP COLUMN IF EXISTS merchant_account_type; + diff --git a/migrations/2025-04-10-095823_add_platform_context_in_organization/up.sql b/migrations/2025-04-10-095823_add_platform_context_in_organization/up.sql new file mode 100644 index 00000000000..cbcabee8e06 --- /dev/null +++ b/migrations/2025-04-10-095823_add_platform_context_in_organization/up.sql @@ -0,0 +1,5 @@ +-- Your SQL goes here +ALTER TABLE organization ADD COLUMN IF NOT EXISTS organization_type VARCHAR(64); +ALTER TABLE organization ADD COLUMN IF NOT EXISTS platform_merchant_id VARCHAR(64); + +ALTER TABLE merchant_account ADD COLUMN IF NOT EXISTS merchant_account_type VARCHAR(64);
2025-04-23T22:40:53Z
## Description The PR supports onboarding for new VSAAS merchants. - Creating Platform Org - Creation of Platform, and connected merchant accounts - Change List response of merchant and organization list. ## Motivation and Context Closes #7889 #
f70824ef5e56514e5fc40163dfed3a0fde29bd1f
Following Flow: - Signup --> terminate 2FA --> List orgs/merchants --> create Merchant inside standard org --> List merchants/orgs to validate - CreatePlatform --> Swtich to Platform Org --> List merchants/orgs to validate --> Create Merchant inside platform org We can hit the following curls: **Signup** ``` curl --location 'http://localhost:8080/user/signup?token_only=true' \ --header 'x-tenant-id: test' \ --header 'Content-Type: application/json' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NTY1ODA0MywidGVuYW50X2lkIjoicHVibGljIn0.1lHD7fOM64ZtP0rRaBnp5-oaC6vy411jMu-lsjHAyr0' \ --data-raw '{ "email": "[email protected]", "password": "Test@1234" }' ``` Response: ``` {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NTY1ODA0MywidGVuYW50X2lkIjoicHVibGljIn0.1lHD7fOM64ZtP0rRaBnp5-oaC6vy411jMu-lsjHAyr0","token_type":"totp"} ``` **Terminate 2FA** ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NTY1ODA0MywidGVuYW50X2lkIjoicHVibGljIn0.1lHD7fOM64ZtP0rRaBnp5-oaC6vy411jMu-lsjHAyr0' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' ``` Response ``` {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o","token_type":"user_info"} ``` **Create Merchant Account** ``` curl --location 'http://localhost:8080/user/create_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --data '{ "company_name": "in_standard" }' ``` Response: ``` {"merchant_id":"merchant_1745485331","merchant_name":"in_standard","product_type":"orchestration","merchant_account_type":"standard","version":"v1"} ``` **List Orgs** ``` curl --location 'http://localhost:8080/user/list/org' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDM2NzMyMTUtYWU3NS00NGMzLWJiYzEtMGY3YmMxYmYwMjdmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzEyMjE0NDE5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxMjM4NzMyOSwib3JnX2lkIjoib3JnXzhLb2lWNmhrcG9KSGZNcllER1ZhIn0.H2G9oGp_JBoz3k5S7fMvaaJ9T0cG5VtUjM0hU3ltM3g' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' ``` Response: ``` [{"org_id":"org_1TaQlxQhcvKA6JVFqHeh","org_name":null,"org_type":"standard"}] ``` **List Merchant** ``` curl --location 'http://localhost:8080/user/list/merchant' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDM2NzMyMTUtYWU3NS00NGMzLWJiYzEtMGY3YmMxYmYwMjdmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzEyMjE0NDE5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxMjM4NzMyOSwib3JnX2lkIjoib3JnXzhLb2lWNmhrcG9KSGZNcllER1ZhIn0.H2G9oGp_JBoz3k5S7fMvaaJ9T0cG5VtUjM0hU3ltM3g' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' ``` Response: ``` [{"merchant_id":"merchant_1745485242","merchant_name":null,"product_type":"orchestration","merchant_account_type":"standard","version":"v1"},{"merchant_id":"merchant_1745485331","merchant_name":"in_standard","product_type":"orchestration","merchant_account_type":"standard","version":"v1"}] ``` **Create Platform Org** ``` curl --location 'http://localhost:8080/user/create_platform' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --data '{ "organization_name": "platform" }' ``` Response: status 200 OK, witth reponse containing platform details ``` {"org_id":"org_TgxsZW9EOXksNcMSeaUy","org_name":"platform","org_type":"platform","merchant_id":"merchant_1745575171","merchant_account_type":"platform"} ``` Switch Org ``` curl --location 'http://localhost:8080/user/switch/org' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1NDg3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODM5OSwib3JnX2lkIjoib3JnXzBFZXE4cU9ETVJGc3NiNGJXa0p5IiwicHJvZmlsZV9pZCI6InByb19QOGc0R0dhbk81dDFiUXczNVQ3aiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.UW9aqcLLXYi_3xOpLCB2vB2ecmMA7M4LHNXorPT0Odc' \ --data '{ "org_id": "org_0Eeq8qODMRFssb4bWkJy" }' ``` Resonse: ``` {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1NDg3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODM5OSwib3JnX2lkIjoib3JnXzBFZXE4cU9ETVJGc3NiNGJXa0p5IiwicHJvZmlsZV9pZCI6InByb19QOGc0R0dhbk81dDFiUXczNVQ3aiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.UW9aqcLLXYi_3xOpLCB2vB2ecmMA7M4LHNXorPT0Odc","token_type":"user_info"} ``` Create Merchant inside Platfrom ``` curl --location 'http://localhost:8080/user/create_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1NDg3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODM5OSwib3JnX2lkIjoib3JnXzBFZXE4cU9ETVJGc3NiNGJXa0p5IiwicHJvZmlsZV9pZCI6InByb19QOGc0R0dhbk81dDFiUXczNVQ3aiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.UW9aqcLLXYi_3xOpLCB2vB2ecmMA7M4LHNXorPT0Odc' \ --data '{ "company_name": "in_platform" }' ``` Response: ``` {"merchant_id":"merchant_1745485645","merchant_name":"in_platform","product_type":"orchestration","merchant_account_type":"connected","version":"v1"} ``` List Org Now the list orgs for user will give following response since there are two orgs ``` [{"org_id":"org_0Eeq8qODMRFssb4bWkJy","org_name":"platform","org_type":"platform"},{"org_id":"org_1TaQlxQhcvKA6JVFqHeh","org_name":null,"org_type":"standard"}] ``` List Merchant Inside platform there will be following merchants ``` [{"merchant_id":"merchant_1745485487","merchant_name":null,"product_type":"orchestration","merchant_account_type":"platform","version":"v1"},{"merchant_id":"merchant_1745485645","merchant_name":"in_platform","product_type":"orchestration","merchant_account_type":"connected","version":"v1"}] ```
[ "crates/api_models/src/events/user.rs", "crates/api_models/src/organization.rs", "crates/api_models/src/user.rs", "crates/common_enums/src/enums.rs", "crates/common_enums/src/enums/accounts.rs", "crates/diesel_models/src/merchant_account.rs", "crates/diesel_models/src/organization.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/hyperswitch_domain_models/src/merchant_account.rs", "crates/router/src/core/admin.rs", "crates/router/src/core/user.rs", "crates/router/src/db/organization.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/types/transformers.rs", "crates/router/src/utils/user.rs", "crates/router_env/src/logger/types.rs", "migrations/2025-04-10-095823_add_platform_context_in_organization/down.sql", "migrations/2025-04-10-095823_add_platform_context_in_organization/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7875
Bug: feat(merchant_context): add struct `merchant_context` and replace all instances of `merchant_account` and `key_store` in core # Introduction of MerchantContext: Unified Merchant Operation Context ## Challenge Currently, merchant account and key store information are passed separately throughout the codebase, leading to scattered merchant context handling and reduced maintainability. Functions individually manage these components, making it difficult to implement platform-wide features or connected account capabilities. ## Proposed Changes Introducing `MerchantContext`, a new type that encapsulates both merchant account and key store information: ```rust pub enum MerchantContext { NormalMerchant(Box<Context>), } pub struct Context(pub MerchantAccount, pub MerchantKeyStore); ``` The type provides controlled access through methods: - `get_merchant_account()`: Access merchant account details - `get_merchant_key_store()`: Access cryptographic key store ## Why 1. **Unified Context**: Encapsulates merchant authentication and operational context in one place 2. **Cleaner Architecture**: Replaces scattered merchant account and key store parameters with a single context object 3. **Enhanced Control**: Method-based access enables validation, transformation, and future enhancements 4. **Maintainability**: Centralized merchant context management reduces code duplication and improves traceability ## How The implementation follows a tree-like flow where the `MerchantContext` is: 1. Declared at the route handler level (root) 2. Passed down through core operation handlers (branches) 3. Finally consumed in database operations or other terminal functions (leaves) This creates a clear, traceable flow of merchant context through the entire operation chain, making it easier to understand and maintain merchant-related operations. ## Future Objectives 1. **Operational Context extension**: The enum structure allows adding new variants for different operations, enabling: - Platform-level context inheritance - Connected account operations - cherry picking context for individual fragment of flows 2. **Granular Context Control**: - Move context declaration to auth layer - Enable advanced platform features by implementing context creation logic for platform operations This architectural change sets the foundation for future platform features while maintaining current functionality and improving code organization.
2025-04-23T09:26:46Z
## Motivation and Context ### Fixes [#7875](https://github.com/juspay/hyperswitch/issues/7875) The current implementation has several limitations: 1. Merchant account and key store information are passed separately throughout the codebase 2. Scattered merchant context handling reduces maintainability 3. Individual functions managing these components make it difficult to implement vsaas related (platform) features 4. Lack of centralized control for merchant context operations This refactoring addresses these issues by: 1. Encapsulating merchant authentication and operational context in one place 2. Providing a cleaner architecture with a single context object 3. Enabling method-based access for validation and transformation n The changes set the foundation for future enhancements including: - Platform-level context inheritance - Connected account operations - Granular context control at the auth layer (being added). - Advanced platform features through context creation logic (to be added). # #### Some core operations cURLs ##### Merchant account creation ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: REDACTED' \ --data-raw '{ "merchant_id": "merchant_1745407533", "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": "https://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", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` Res: ```json { "merchant_id": "merchant_1745407536", "merchant_name": "NewAge Retailer", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "h63lzU5pCbN8pzP9gOiWZLu8deQRy5fNMtCGa8vDoMBMqZVOyd4mL22dcSPrYLkB", "redirect_to_merchant_with_http_post": false, "merchant_details": { "primary_contact_person": "John Test", "primary_phone": "sunt laborum", "primary_email": "[email protected]", "secondary_contact_person": "John Test2", "secondary_phone": "cillum do dolor id", "secondary_email": "[email protected]", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" } }, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": "https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "payout_routing_algorithm": null, "sub_merchants_enabled": false, "parent_merchant_id": null, "publishable_key": "pk_dev_170e697c79ae4f128825aec6246761cd", "metadata": { "city": "NY", "unit": "245", "compatible_connector": null }, "locker_id": "m0010", "primary_business_details": [ { "country": "US", "business": "default" } ], "frm_routing_algorithm": null, "organization_id": "org_KQ4zLFbq0TKr7pvG59Va", "is_recon_enabled": false, "default_profile": "pro_9P0eWVliPBMEzYLqeejN", "recon_status": "not_requested", "pm_collect_link_config": null, "product_type": "orchestration" } ``` ##### Payment ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: REDACTED' \ --data-raw '{ "amount": 104000, "currency": "GBP", "amount_to_capture": 104000, "confirm": true, "profile_id": "pro_A5v5oJ8JhYmVDdJPiOGe", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "routing": { "type": "single", "data": "stripe" }, "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4532432452900131", "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "card_cvc": "257" } }, "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" }, "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": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 104000, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` Res: ```json { "payment_id": "pay_DcEBzqxP2qQ5mCDygEIu", "merchant_id": "merchant_1745478997", "status": "failed", "amount": 104000, "net_amount": 104000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "pay_DcEBzqxP2qQ5mCDygEIu_secret_YfbAUlzs6BFc3UFkandB", "created": "2025-04-24T07:21:25.127Z", "currency": "GBP", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0131", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453243", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 104000, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "DC_04", "error_message": "Card not supported. Please use test cards", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1745479285, "expires": 1745482885, "secret": "epk_64adcfbf68f24d77be6ee26af56e90c6" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null }, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_A5v5oJ8JhYmVDdJPiOGe", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MUYcgcVSOudbAphvZGRR", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-24T07:36:25.127Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-24T07:21:26.203Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ```
3d0dd5bd1a8d764757fce4a37c668c0ff548d59c
#### **Important** The changes included in this PR don't affect any flows or behaviour, it is merely a refactor of the whole core module. Test method: Ran ```cargo hack ``` locally and ran all sanity checks. #### Some core operations cURLs ##### Merchant account creation ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: REDACTED' \ --data-raw '{ "merchant_id": "merchant_1745407533", "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": "https://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", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` Res: ```json { "merchant_id": "merchant_1745407536", "merchant_name": "NewAge Retailer", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "h63lzU5pCbN8pzP9gOiWZLu8deQRy5fNMtCGa8vDoMBMqZVOyd4mL22dcSPrYLkB", "redirect_to_merchant_with_http_post": false, "merchant_details": { "primary_contact_person": "John Test", "primary_phone": "sunt laborum", "primary_email": "[email protected]", "secondary_contact_person": "John Test2", "secondary_phone": "cillum do dolor id", "secondary_email": "[email protected]", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" } }, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": "https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "payout_routing_algorithm": null, "sub_merchants_enabled": false, "parent_merchant_id": null, "publishable_key": "pk_dev_170e697c79ae4f128825aec6246761cd", "metadata": { "city": "NY", "unit": "245", "compatible_connector": null }, "locker_id": "m0010", "primary_business_details": [ { "country": "US", "business": "default" } ], "frm_routing_algorithm": null, "organization_id": "org_KQ4zLFbq0TKr7pvG59Va", "is_recon_enabled": false, "default_profile": "pro_9P0eWVliPBMEzYLqeejN", "recon_status": "not_requested", "pm_collect_link_config": null, "product_type": "orchestration" } ``` ##### Payment ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: REDACTED' \ --data-raw '{ "amount": 104000, "currency": "GBP", "amount_to_capture": 104000, "confirm": true, "profile_id": "pro_A5v5oJ8JhYmVDdJPiOGe", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "routing": { "type": "single", "data": "stripe" }, "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4532432452900131", "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "card_cvc": "257" } }, "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" }, "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": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 104000, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` Res: ```json { "payment_id": "pay_DcEBzqxP2qQ5mCDygEIu", "merchant_id": "merchant_1745478997", "status": "failed", "amount": 104000, "net_amount": 104000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "pay_DcEBzqxP2qQ5mCDygEIu_secret_YfbAUlzs6BFc3UFkandB", "created": "2025-04-24T07:21:25.127Z", "currency": "GBP", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0131", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453243", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 104000, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "DC_04", "error_message": "Card not supported. Please use test cards", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1745479285, "expires": 1745482885, "secret": "epk_64adcfbf68f24d77be6ee26af56e90c6" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null }, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_A5v5oJ8JhYmVDdJPiOGe", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MUYcgcVSOudbAphvZGRR", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-24T07:36:25.127Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-24T07:21:26.203Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ```
[]
juspay/hyperswitch
juspay__hyperswitch-7880
Bug: [Refactor] Remove merchant reference id from customers v2 update api Remove `merchant_reference_id` field from customer update request struct so that it cannot be updated.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 10682866ab7..f7f62fe5ee8 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -9362,14 +9362,6 @@ "email" ], "properties": { - "merchant_reference_id": { - "type": "string", - "description": "The merchant identifier for the customer object.", - "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", - "nullable": true, - "maxLength": 64, - "minLength": 1 - }, "name": { "type": "string", "description": "The customer's name", diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index eb61cae6e47..90f849971b2 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -313,9 +313,6 @@ impl CustomerUpdateRequest { #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerUpdateRequest { - /// The merchant identifier for the customer object. - #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] - pub merchant_reference_id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Option<Secret<String>>, @@ -349,10 +346,6 @@ pub struct CustomerUpdateRequest { #[cfg(all(feature = "v2", feature = "customer_v2"))] impl CustomerUpdateRequest { - pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { - self.merchant_reference_id.clone() - } - pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() }
2025-04-23T09:07:12Z
## Description <!-- Describe your changes in detail --> We are removing `merchant_reference_id` from all API updates, due to possible bugs on merchant side db and HS db as there might be mismatch in their's and our's db records. This exists only in customers and refunds v2 apis, a separate PR has been implemented for refunds update, and this PR is for customers v2 update api. It was noticed that in the current implementation of customers v2 update flow, the `merchant_reference_id` field is being accepted by the API but it was never updated in the db. In this PR we are removing `merchant_reference_id` from being accepted in the customers v2 update request. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Upon merging this PR, we will be removing `merchant_reference_id` from being updated in customer v2 update api. #
639b8cba5fff2aeb85787309983e412b4a21b238
- Create Customer API Call ``` curl --location 'http://localhost:8080/v2/customers' \ --header 'x-profile-id: pro_saOFnM13wT1ngOuItKJl' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_VAtwaBd0cVItaaxIS8bUTFuPcxa9DkqlmBPvH5fq6IASKSlBxc9cBUygLoCaebFj' \ --data-raw '{ "merchant_reference_id": "customer_1748929359", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "default_billing_address": null, "default_shipping_address": null, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Response from above call ``` { "id": "12345_cus_0197344f74677930a77bfc4c926c3b3e", "merchant_reference_id": "customer_1748929312", "connector_customer_ids": null, "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "default_billing_address": null, "default_shipping_address": null, "created_at": "2025-06-03T05:41:51.849Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null } ``` - Customer Update API call ``` curl --location --request PUT 'http://localhost:8080/v2/customers/12345_cus_0197344f74677930a77bfc4c926c3b3e' \ --header 'x-profile-id: pro_saOFnM13wT1ngOuItKJl' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_VAtwaBd0cVItaaxIS8bUTFuPcxa9DkqlmBPvH5fq6IASKSlBxc9cBUygLoCaebFj' \ --data-raw '{ "name": "Jane Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "Second customer", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Response from the above call ``` { "id": "12345_cus_0197344f74677930a77bfc4c926c3b3e", "merchant_reference_id": "customer_1748929312", "connector_customer_ids": null, "name": "Jane Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "Second customer", "default_billing_address": null, "default_shipping_address": null, "created_at": "2025-06-03T05:41:51.849Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null } ``` - Trying to update `merchant_reference_id` API call ``` curl --location --request PUT 'http://localhost:8080/v2/customers/12345_cus_0197344f74677930a77bfc4c926c3b3e' \ --header 'x-profile-id: pro_saOFnM13wT1ngOuItKJl' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_VAtwaBd0cVItaaxIS8bUTFuPcxa9DkqlmBPvH5fq6IASKSlBxc9cBUygLoCaebFj' \ --data-raw '{ "merchant_reference_id": "customer_1748929499", "name": "Jane Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "Second customer", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Response from the above call ``` { "error": { "error_type": "invalid_request", "message": "Json deserialize error: unknown field `merchant_reference_id`, expected one of `name`, `email`, `phone`, `description`, `phone_country_code`, `default_billing_address`, `default_shipping_address`, `metadata`, `default_payment_method_id` at line 2 column 27", "code": "IR_06" } } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/customers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7878
Bug: Add support to create profile level custom role Closes issue : https://github.com/juspay/hyperswitch/issues/7740
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs index ba63dd61a0c..67fb04099ce 100644 --- a/crates/diesel_models/src/role.rs +++ b/crates/diesel_models/src/role.rs @@ -9,7 +9,7 @@ use crate::{enums, schema::roles}; pub struct Role { pub role_name: String, pub role_id: String, - pub merchant_id: id_type::MerchantId, + pub merchant_id: Option<id_type::MerchantId>, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, @@ -28,7 +28,7 @@ pub struct Role { pub struct RoleNew { pub role_name: String, pub role_id: String, - pub merchant_id: id_type::MerchantId, + pub merchant_id: Option<id_type::MerchantId>, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 374b341a47e..c25acc386f5 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1361,7 +1361,7 @@ diesel::table! { #[max_length = 64] role_id -> Varchar, #[max_length = 64] - merchant_id -> Varchar, + merchant_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 9a72f663e4f..8cc0dcf7ed6 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1289,7 +1289,7 @@ diesel::table! { #[max_length = 64] role_id -> Varchar, #[max_length = 64] - merchant_id -> Varchar, + merchant_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 34f0e8187ca..9bb8be9cc6e 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -78,13 +78,6 @@ pub async fn create_role( return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User trying to create org level custom role"); } - - // TODO: Remove in PR custom-role-write-pr - if matches!(role_entity_type, EntityType::Profile) { - return Err(report!(UserErrors::InvalidRoleOperation)) - .attach_printable("User trying to create profile level custom role"); - } - let requestor_entity_from_role_scope = EntityType::from(req.role_scope); if requestor_entity_from_role_scope < role_entity_type { @@ -120,13 +113,15 @@ pub async fn create_role( .await?; let (org_id, merchant_id, profile_id) = match role_entity_type { - EntityType::Organization | EntityType::Tenant => { - (user_from_token.org_id, user_from_token.merchant_id, None) - } - EntityType::Merchant => (user_from_token.org_id, user_from_token.merchant_id, None), + EntityType::Organization | EntityType::Tenant => (user_from_token.org_id, None, None), + EntityType::Merchant => ( + user_from_token.org_id, + Some(user_from_token.merchant_id), + None, + ), EntityType::Profile => ( user_from_token.org_id, - user_from_token.merchant_id, + Some(user_from_token.merchant_id), Some(user_from_token.profile_id), ), }; diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index 532a59f5149..ecb962d8d29 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -265,7 +265,13 @@ impl RoleInterface for MockDb { && (role.tenant_id == *tenant_id) && role.org_id == *org_id && ((role.scope == RoleScope::Organization) - || (role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant) + || (role + .merchant_id + .as_ref() + .is_some_and(|merchant_id_from_role| { + merchant_id_from_role == merchant_id + && role.scope == RoleScope::Merchant + })) || (role .profile_id .as_ref() @@ -369,10 +375,10 @@ impl RoleInterface for MockDb { let roles_list: Vec<_> = roles .iter() .filter(|role| { - let matches_merchant = match merchant_id { - Some(merchant_id) => role.merchant_id == *merchant_id, - None => true, - }; + let matches_merchant = merchant_id + .zip(role.merchant_id.as_ref()) + .map(|(merchant_id, role_merchant_id)| merchant_id == role_merchant_id) + .unwrap_or(true); matches_merchant && role.org_id == *org_id @@ -420,17 +426,26 @@ impl RoleInterface for MockDb { vec![EntityType::Merchant] }; + let matches_merchant = role + .merchant_id + .as_ref() + .is_some_and(|merchant_id_from_role| merchant_id_from_role == merchant_id); + role.tenant_id == tenant_id && role.org_id == org_id - && (role.scope == RoleScope::Organization - || role.merchant_id == *merchant_id) + && (role.scope == RoleScope::Organization || matches_merchant) && entity_in_vec.contains(&role.entity_type) } storage::ListRolesByEntityPayload::Profile(merchant_id, profile_id) => { let entity_in_vec = [EntityType::Profile]; let matches_merchant = - role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant; + role.merchant_id + .as_ref() + .is_some_and(|merchant_id_from_role| { + merchant_id_from_role == merchant_id + && role.scope == RoleScope::Merchant + }); let matches_profile = role.profile_id diff --git a/migrations/2025-02-06-122415_udpate-roles/down.sql b/migrations/2025-02-06-122415_udpate-roles/down.sql new file mode 100644 index 00000000000..be66247abff --- /dev/null +++ b/migrations/2025-02-06-122415_udpate-roles/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE roles ALTER COLUMN merchant_id SET NOT NULL; \ No newline at end of file diff --git a/migrations/2025-02-06-122415_udpate-roles/up.sql b/migrations/2025-02-06-122415_udpate-roles/up.sql new file mode 100644 index 00000000000..490f5bcb929 --- /dev/null +++ b/migrations/2025-02-06-122415_udpate-roles/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE roles ALTER COLUMN merchant_id DROP NOT NULL; \ No newline at end of file
2025-04-23T07:32:46Z
## Description <!-- Describe your changes in detail --> This pr will enable profile level custom creation from API and also enable org level custom role read ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
bca8979a0cd25472b2f9b5e9d9daf7509a7b3cbb
1 . Valid operation Request : ``` curl --location 'http://localhost:8080/user/role' \ --header 'authorization: Bearer JWT' \ --header 'cookie: login_token=JWT' \ --data '{ "role_scope": "profile", "entity_type": "profile", "groups": [ "operations_view", "operations_manage" ], "role_name": "profile-role-at-profile-scope" }' ``` Response ``` { "role_id": "role_vcPMQVtjv0jblNi1tOxB", "groups": [ "operations_view", "operations_manage" ], "role_name": "profile-role-at-profile-scope", "role_scope": "profile", "entity_type": "profile" } ``` 2. Invalid operation Request ``` curl --location 'http://localhost:8080/user/role' \ --header 'authorization: Bearer JWT' \ --header 'cookie: login_token=JWT' \ --data '{ "role_scope": "profile", "entity_type": "merchant", "groups": [ "operations_view", "operations_manage" ], "role_name": "merchant-role-at-profile-scope" }' ``` Response ``` { "error": { "type": "invalid_request", "message": "User Role Operation Not Supported", "code": "UR_23" } } ```
[ "crates/diesel_models/src/role.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/router/src/core/user_role/role.rs", "crates/router/src/db/role.rs", "migrations/2025-02-06-122415_udpate-roles/down.sql", "migrations/2025-02-06-122415_udpate-roles/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7837
Bug: [FEATURE] connector's sandbox testing via magic values ### Feature Description Connectors provide sending magic values for certain fields in their API requests. These values can be used to simulate different error scenarios. For most of the cases across all the connectors, these can be set in the already present fields. For a few cases, extra fields are needed to be passed to the connector (eg: payment method holder name for MIT payments for Adyen). For such cases, the fields are not necessary in the real environment but necessary for simulating certain scenarios. This feature allows the end merchants to simulate different scenarios in the sandbox environment. ### Possible Implementation There are two parts to this for the implementation 1. Provision sending these fields by the merchant in the payments API request (structured metadata) 2. Consume these fields on a connector to connector basis as per the requirement Step 1 - Expose a field in `connector_metadata` for Adyen - With below fields for now - holder_name: Option<String> Sample body in the payments request ``` { ... "connector_metadata": { "adyen": { "testing": { "holder_name": "CARD_EXPIRED" } } } ... } ``` Step 2 - In non prod environment, pass this to connector integration for below actions - Authorize - SetupMandate - Refund Step 3 - Consume these fields in connector integration as per requirement Step 4 - Consume `holder_name` in MIT requests for Adyen integration ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 10682866ab7..e068f12f4be 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3775,6 +3775,17 @@ }, "additionalProperties": false }, + "AdyenConnectorMetadata": { + "type": "object", + "required": [ + "testing" + ], + "properties": { + "testing": { + "$ref": "#/components/schemas/AdyenTestingData" + } + } + }, "AdyenSplitData": { "type": "object", "description": "Fee information for Split Payments to be charged on the payment being collected for Adyen", @@ -3848,6 +3859,18 @@ "Vat" ] }, + "AdyenTestingData": { + "type": "object", + "required": [ + "holder_name" + ], + "properties": { + "holder_name": { + "type": "string", + "description": "Holder name to be sent to Adyen for a card payment(CIT) or a generic payment(MIT). This value overrides the values for card.card_holder_name and applies during both CIT and MIT payment transactions." + } + } + }, "AirwallexData": { "type": "object", "properties": { @@ -7960,6 +7983,14 @@ } ], "nullable": true + }, + "adyen": { + "allOf": [ + { + "$ref": "#/components/schemas/AdyenConnectorMetadata" + } + ], + "nullable": true } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 011fd7e4431..52b3b893dde 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6720,6 +6720,7 @@ pub struct ConnectorMetadata { pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, + pub adyen: Option<AdyenConnectorMetadata>, } impl ConnectorMetadata { @@ -6770,6 +6771,18 @@ pub struct BraintreeData { pub merchant_config_currency: Option<api_enums::Currency>, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct AdyenConnectorMetadata { + pub testing: AdyenTestingData, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct AdyenTestingData { + /// Holder name to be sent to Adyen for a card payment(CIT) or a generic payment(MIT). This value overrides the values for card.card_holder_name and applies during both CIT and MIT payment transactions. + #[schema(value_type = String)] + pub holder_name: Option<Secret<String>>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index be6543d8b1c..c15affcc8aa 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -10,7 +10,7 @@ use common_enums::enums as storage_enums; use common_utils::ext_traits::OptionExt; use common_utils::{ errors::{CustomResult, ParsingError}, - ext_traits::Encode, + ext_traits::{Encode, ValueExt}, pii::Email, request::Method, types::MinorUnit, @@ -1222,6 +1222,7 @@ pub struct AdyenMandate { #[serde(rename = "type")] payment_type: PaymentType, stored_payment_method_id: Secret<String>, + holder_name: Option<Secret<String>>, } #[serde_with::skip_serializing_none] @@ -2008,13 +2009,21 @@ impl TryFrom<(&BankDebitData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMet account_number, sort_code, .. - } => Ok(AdyenPaymentMethod::BacsDirectDebit(Box::new( - BacsDirectDebitData { - bank_account_number: account_number.clone(), - bank_location_id: sort_code.clone(), - holder_name: item.get_billing_full_name()?, - }, - ))), + } => { + let testing_data = item + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); + Ok(AdyenPaymentMethod::BacsDirectDebit(Box::new( + BacsDirectDebitData { + bank_account_number: account_number.clone(), + bank_location_id: sort_code.clone(), + holder_name: test_holder_name.unwrap_or(item.get_billing_full_name()?), + }, + ))) + } BankDebitData::BecsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), @@ -2396,30 +2405,38 @@ impl TryFrom<(&BankRedirectData, &PaymentsAuthorizeRouterData)> for AdyenPayment card_exp_month, card_exp_year, .. - } => Ok(AdyenPaymentMethod::BancontactCard(Box::new(AdyenCard { - brand: Some(CardBrand::Bcmc), - 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: Some(item.get_billing_full_name()?), - cvc: None, - network_payment_reference: None, - }))), + } => { + let testing_data = item + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); + Ok(AdyenPaymentMethod::BancontactCard(Box::new(AdyenCard { + brand: Some(CardBrand::Bcmc), + 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: test_holder_name.or(Some(item.get_billing_full_name()?)), + cvc: None, + network_payment_reference: None, + }))) + } BankRedirectData::Bizum { .. } => Ok(AdyenPaymentMethod::Bizum), BankRedirectData::Blik { blik_code } => { Ok(AdyenPaymentMethod::Blik(Box::new(BlikRedirectionData { @@ -2684,6 +2701,13 @@ impl let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_router_return_url()?; let payment_method_type = item.router_data.request.payment_method_type; + let testing_data = item + .router_data + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); let payment_method = match mandate_ref_id { payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => { let adyen_mandate = AdyenMandate { @@ -2696,6 +2720,7 @@ impl .get_connector_mandate_id() .ok_or_else(missing_field_err("mandate_id"))?, ), + holder_name: test_holder_name, }; Ok::<PaymentMethod<'_>, Self::Error>(PaymentMethod::AdyenMandatePaymentMethod( Box::new(adyen_mandate), @@ -2727,7 +2752,7 @@ impl .get_expiry_year_4_digit() .clone(), cvc: None, - holder_name: card_holder_name, + holder_name: test_holder_name.or(card_holder_name), brand: Some(brand), network_payment_reference: Some(Secret::new(network_mandate_id)), }; @@ -2768,7 +2793,7 @@ impl number: token_data.get_network_token(), expiry_month: token_data.get_network_token_expiry_month(), expiry_year: token_data.get_expiry_year_4_digit(), - holder_name: card_holder_name, + holder_name: test_holder_name.or(card_holder_name), brand: Some(brand), // FIXME: Remove hardcoding network_payment_reference: Some(Secret::new( network_mandate_id.network_transaction_id, @@ -2879,7 +2904,15 @@ impl TryFrom<(&AdyenRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AdyenP let country_code = get_country_code(item.router_data.get_optional_billing()); let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_router_return_url()?; - let card_holder_name = item.router_data.get_optional_billing_full_name(); + let testing_data = item + .router_data + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); + let card_holder_name = + test_holder_name.or(item.router_data.get_optional_billing_full_name()); let payment_method = PaymentMethod::AdyenPaymentMethod(Box::new( AdyenPaymentMethod::try_from((card_data, card_holder_name))?, )); @@ -5505,6 +5538,24 @@ pub struct DefenseDocuments { defense_document_type_code: String, } +#[derive(Debug, Deserialize)] +pub struct AdyenTestingData { + holder_name: Option<Secret<String>>, +} + +impl TryFrom<common_utils::pii::SecretSerdeValue> for AdyenTestingData { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(testing_data: common_utils::pii::SecretSerdeValue) -> Result<Self, Self::Error> { + let testing_data = testing_data + .expose() + .parse_value::<Self>("AdyenTestingData") + .change_context(errors::ConnectorError::InvalidDataFormat { + field_name: "connector_metadata.adyen.testing", + })?; + Ok(testing_data) + } +} + impl TryFrom<&SubmitEvidenceRouterData> for Evidence { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> { @@ -5782,7 +5833,15 @@ impl let country_code = get_country_code(item.router_data.get_optional_billing()); let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_router_return_url()?; - let card_holder_name = item.router_data.get_optional_billing_full_name(); + let testing_data = item + .router_data + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); + let card_holder_name = + test_holder_name.or(item.router_data.get_optional_billing_full_name()); let payment_method = PaymentMethod::AdyenPaymentMethod(Box::new( AdyenPaymentMethod::try_from((token_data, card_holder_name))?, )); diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 60cb878d9a3..c693d4789ca 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1685,6 +1685,7 @@ pub trait PaymentsAuthorizeRequestData { fn get_card_network_from_additional_payment_method_data( &self, ) -> Result<enums::CardNetwork, Error>; + fn get_connector_testing_data(&self) -> Option<pii::SecretSerdeValue>; } impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { @@ -1905,6 +1906,9 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { .into()), } } + fn get_connector_testing_data(&self) -> Option<pii::SecretSerdeValue> { + self.connector_testing_data.clone() + } } pub trait PaymentsCaptureRequestData { @@ -5998,6 +6002,7 @@ pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data( shipping_cost: data.request.shipping_cost, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: data.request.connector_testing_data.clone(), } } diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 7a91f82f306..1dc88ed95ae 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -76,6 +76,7 @@ pub struct PaymentsAuthorizeData { pub additional_payment_method_data: Option<AdditionalPaymentData>, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, + pub connector_testing_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct PaymentsPostSessionTokensData { @@ -935,4 +936,5 @@ pub struct SetupMandateRequestData { // MinorUnit for amount framework pub minor_amount: Option<MinorUnit>, pub shipping_cost: Option<MinorUnit>, + pub connector_testing_data: Option<pii::SecretSerdeValue>, } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 5d9ccfab2a4..6dc61d4bf4a 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -734,6 +734,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsUpdateMetadataRequest, api_models::payments::PaymentsUpdateMetadataResponse, api_models::payments::CtpServiceDetails, + api_models::payments::AdyenConnectorMetadata, + api_models::payments::AdyenTestingData, api_models::feature_matrix::FeatureMatrixListResponse, api_models::feature_matrix::FeatureMatrixRequest, api_models::feature_matrix::ConnectorFeatureMatrixResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 2629b1b8b7d..b7f88345484 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -701,6 +701,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::DisplayAmountOnSdk, api_models::payments::ErrorDetails, api_models::payments::CtpServiceDetails, + api_models::payments::AdyenConnectorMetadata, + api_models::payments::AdyenTestingData, api_models::feature_matrix::FeatureMatrixListResponse, api_models::feature_matrix::FeatureMatrixRequest, api_models::feature_matrix::ConnectorFeatureMatrixResponse, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 0628a7281f7..6ae4cf4ec72 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -307,6 +307,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( additional_payment_method_data: None, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt @@ -960,6 +961,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, capture_method: Some(payment_data.payment_intent.capture_method), complete_authorize_url, + connector_testing_data: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt @@ -3183,7 +3185,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz field_name: "browser_info", })?; - let order_category = additional_data + let connector_metadata = additional_data .payment_data .payment_intent .connector_metadata @@ -3193,21 +3195,16 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) - .transpose()? - .and_then(|cm| cm.noon.and_then(|noon| noon.order_category)); + .transpose()?; - let braintree_metadata = additional_data - .payment_data - .payment_intent - .connector_metadata - .clone() - .map(|cm| { - cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed parsing ConnectorMetadata") - }) - .transpose()? - .and_then(|cm| cm.braintree); + let order_category = connector_metadata.as_ref().and_then(|cm| { + cm.noon + .as_ref() + .and_then(|noon| noon.order_category.clone()) + }); + let braintree_metadata = connector_metadata + .as_ref() + .and_then(|cm| cm.braintree.clone()); let merchant_account_id = braintree_metadata .as_ref() @@ -3301,6 +3298,30 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .clone(); let shipping_cost = payment_data.payment_intent.shipping_cost; + let connector = api_models::enums::Connector::from_str(connector_name) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector_name:?}") + })?; + + let connector_testing_data = connector_metadata + .and_then(|cm| match connector { + api_models::enums::Connector::Adyen => cm + .adyen + .map(|adyen_cm| adyen_cm.testing) + .map(|testing_data| { + serde_json::to_value(testing_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse Adyen testing data") + }), + _ => None, + }) + .transpose()? + .map(pii::SecretSerdeValue::new); + Ok(Self { payment_method_data: (payment_method_data.get_required_value("payment_method_data")?), setup_future_usage: payment_data.payment_attempt.setup_future_usage_applied, @@ -3355,6 +3376,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz shipping_cost, merchant_account_id, merchant_config_currency, + connector_testing_data, }) } } @@ -4106,6 +4128,40 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ payment_data.creds_identifier.as_deref(), )); + let connector = api_models::enums::Connector::from_str(connector_name) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector_name:?}") + })?; + + let connector_testing_data = payment_data + .payment_intent + .connector_metadata + .as_ref() + .map(|cm| { + cm.clone() + .parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed parsing ConnectorMetadata") + }) + .transpose()? + .and_then(|cm| match connector { + api_models::enums::Connector::Adyen => cm + .adyen + .map(|adyen_cm| adyen_cm.testing) + .map(|testing_data| { + serde_json::to_value(testing_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse Adyen testing data") + }), + _ => None, + }) + .transpose()? + .map(pii::SecretSerdeValue::new); + Ok(Self { currency: payment_data.currency, confirm: true, @@ -4138,6 +4194,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ webhook_url, complete_authorize_url, capture_method: payment_data.payment_attempt.capture_method, + connector_testing_data, }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 2927bc4c8fa..057543d9632 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -923,6 +923,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData { shipping_cost: data.request.shipping_cost, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: data.request.connector_testing_data.clone(), } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index a2a4cf88f65..223c3e5638d 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -63,6 +63,7 @@ impl VerifyConnectorData { shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 6a7239b5b46..2bc4c9f24eb 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -987,6 +987,7 @@ impl Default for PaymentAuthorizeType { shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: None, }; Self(data) }
2025-04-23T05:27:26Z
## Description <!-- Describe your changes in detail --> This PR adds support for connector testing data in payment requests, specifically for Adyen connector. It allows merchants to send testing values via `connector_metadata` to simulate different scenarios in the sandbox environment. The implementation includes: 1. Added a new structure `AdyenConnectorMetadata` and `AdyenTestingData` in the API models 2. Modified the Adyen connector payment flows (both CIT and MIT) across different payment methods to accept and process the testing data The holder_name in testing data will override card_holder_name in the connector's payment request, allowing merchants to test specific scenarios without affecting their production implementation. ## Motivation and Context Connectors like Adyen provide special values for certain fields that can be used to simulate different error scenarios in their sandbox environments. These special values help merchants test error handling without requiring them to modify their actual implementation. For example, sending a specific holder name value like "CARD_EXPIRED" can simulate a card expiration error from Adyen. This feature enables merchants to test various error scenarios in a systematic way through HyperSwitch API without changing their integration code. #
2c9b8abdb58d5b97f9d01a112569ad82b99ea00d
<details> <summary>1. Simulate Adyen's CARD_EXPIRED error through testing data in connector_metadata for CIT</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UEgACZ01bXHeFIrvN93I7h3sWWs4V0LTiJwPQRdI9OQzV4lZcVzLQ1mnfAprp5nx' \ --data-raw '{"amount":10,"currency":"EUR","confirm":true,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","connector":["adyen"],"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4111111111111111","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","card_cvc":"737"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{"holder_name":"CARD_EXPIRED x This is my error message"}}},"session_expiry":60}' Expectations 1. Payment fails with the specified string in testing data's holder name 2. Testing data's holder name takes precedence over the value passed in payment_method_data card_holder_name Response {"payment_id":"pay_YAtEbtMJOeLlpgy6Qo1q","merchant_id":"merchant_1745378456","status":"failed","amount":10,"net_amount":10,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"adyen","client_secret":"pay_YAtEbtMJOeLlpgy6Qo1q_secret_wDnisrGKMPVJ1yITYAgB","created":"2025-04-23T04:31:43.728Z","currency":"EUR","customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","customer":{"id":"cus_xPhu4Ugm5fIPkjIUQNaH","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1111","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":"6","error_message":"Expired Card","unified_code":"UE_9000","unified_message":"Something went wrong","payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","created_at":1745382703,"expires":1745386303,"secret":"epk_deacab31d1e6413291eada3764b2986c"},"manual_retry_allowed":true,"connector_transaction_id":"LW79V9ZRB72FMNT5","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":"CARD_EXPIRED x This is my error message"}}},"feature_metadata":null,"reference_id":null,"payment_link":null,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_OSy4xc1t36A2rIA8IJcn","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-23T04:32:43.728Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-23T04:31:45.103Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":"This is my error message"} </details> <details> <summary>2. Simulate Adyen's CARD_EXPIRED error through testing data in connector_metadata for MIT<summary> cURL (for creating mandates) curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UEgACZ01bXHeFIrvN93I7h3sWWs4V0LTiJwPQRdI9OQzV4lZcVzLQ1mnfAprp5nx' \ --data-raw '{"amount":10,"currency":"EUR","confirm":true,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","connector":["adyen"],"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4111111111111111","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","card_cvc":"737"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"session_expiry":60}' Expectations 1. Payment succeeds 2. payment_method_id is retrieved Response {"payment_id":"pay_Bc8m48deiQPthw9eNKB2","merchant_id":"merchant_1745378456","status":"succeeded","amount":10,"net_amount":10,"shipping_cost":null,"amount_capturable":0,"amount_received":10,"connector":"adyen","client_secret":"pay_Bc8m48deiQPthw9eNKB2_secret_x78ITiMF1X73mI6bc4st","created":"2025-04-23T04:35:53.717Z","currency":"EUR","customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","customer":{"id":"cus_xPhu4Ugm5fIPkjIUQNaH","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1111","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","created_at":1745382953,"expires":1745386553,"secret":"epk_ee929d43a2f3400d84b614ba30219d53"},"manual_retry_allowed":false,"connector_transaction_id":"D2XCLCJRGB9VWM75","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":null}}},"feature_metadata":null,"reference_id":"pay_Bc8m48deiQPthw9eNKB2_1","payment_link":null,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_OSy4xc1t36A2rIA8IJcn","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-23T04:36:53.717Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_EJSd2QoapABA7TLpNrjp","payment_method_status":"active","updated":"2025-04-23T04:35:55.388Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"LQR35D9R636NHJ65","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} cURL (Simulating error in MIT) curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UEgACZ01bXHeFIrvN93I7h3sWWs4V0LTiJwPQRdI9OQzV4lZcVzLQ1mnfAprp5nx' \ --data-raw '{"amount":6500,"currency":"EUR","confirm":true,"capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","email":"[email protected]","name":"John Doe","phone":"999999999","profile_id":"pro_HPqNgWlKGAgwQms0jwIF","phone_country_code":"+65","description":"Its my first payment request","return_url":"https://hyperswitch.io","off_session":true,"recurring_details":{"type":"payment_method_id","data":"pm_EJSd2QoapABA7TLpNrjp"},"connector":["adyen"],"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true},"connector_metadata":{"adyen":{"testing":{"holder_name":"CARD_EXPIRED x MIT error message"}}}}' Expectations 1. MIT payment fails with the specified error in testing data's holder name field Response {"payment_id":"pay_fRuTbjd8yFPgBk9NHn1U","merchant_id":"merchant_1745378456","status":"failed","amount":6500,"net_amount":6500,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"adyen","client_secret":"pay_fRuTbjd8yFPgBk9NHn1U_secret_AZm2NYex5skj3qtRYmiy","created":"2025-04-23T04:37:46.301Z","currency":"EUR","customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","customer":{"id":"cus_xPhu4Ugm5fIPkjIUQNaH","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":"Its my first payment request","refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1111","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://hyperswitch.io/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":"6","error_message":"Expired Card","unified_code":"UE_9000","unified_message":"Something went wrong","payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","created_at":1745383066,"expires":1745386666,"secret":"epk_99ac0c08e6d843ae9d15e6f280822f2f"},"manual_retry_allowed":true,"connector_transaction_id":"JKS4HVG55L4VWM75","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":"CARD_EXPIRED x MIT error message"}}},"feature_metadata":null,"reference_id":null,"payment_link":null,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_OSy4xc1t36A2rIA8IJcn","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-23T04:52:46.301Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_EJSd2QoapABA7TLpNrjp","payment_method_status":"active","updated":"2025-04-23T04:37:47.572Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"LQR35D9R636NHJ65","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":"MIT error message"} </details> <details> <summary>Automated cypress tests for Adyen (Ideal bank redirection fails as expected)</summary> ![Screenshot 2025-04-24 at 8 28 21 PM](https://github.com/user-attachments/assets/d9119546-f8b5-4852-a141-7456e490935d) </details>
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payments.rs", "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", "crates/hyperswitch_connectors/src/utils.rs", "crates/hyperswitch_domain_models/src/router_request_types.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/openapi_v2.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/types.rs", "crates/router/src/types/api/verify_connector.rs", "crates/router/tests/connectors/utils.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7872
Bug: [FEATURE] (connector): [GETNET,HIPAY,KLARNA,MONERIS,OPENNODE] add in feature matrix api ### Feature Description [GETNET,HIPAY,KLARNA,MONERIS,OPENNODE] add in feature matrix api ### Possible Implementation [GETNET,HIPAY,KLARNA,MONERIS,OPENNODE] add in feature matrix api ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 5f13eb1388d..96c435f369f 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -471,8 +471,8 @@ slack_invite_url = "https://www.example.com/" # Slack invite url for hyperswit discord_invite_url = "https://www.example.com/" # Discord invite url for hyperswitch [mandates.supported_payment_methods] -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" wallet.paypal = { connector_list = "adyen,novalnet" } # 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,adyen" } # Mandate supported payment method type and connector for bank_debit diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index d7eb52a81e3..4b057cee228 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -177,8 +177,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" @@ -313,6 +313,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 1cde8c3079a..1f96521d3d1 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -177,8 +177,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" @@ -327,6 +327,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 4059ba2ccb2..d120205d03f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -177,8 +177,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" @@ -329,6 +329,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/development.toml b/config/development.toml index 89e35448af2..1741202d780 100644 --- a/config/development.toml +++ b/config/development.toml @@ -555,6 +555,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } @@ -819,8 +833,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index cdf82f60936..63d6f96ff66 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -479,6 +479,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } diff --git a/crates/hyperswitch_connectors/src/connectors/getnet.rs b/crates/hyperswitch_connectors/src/connectors/getnet.rs index 06bd210431a..1aa41c801ee 100644 --- a/crates/hyperswitch_connectors/src/connectors/getnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/getnet.rs @@ -1,4 +1,6 @@ pub mod transformers; +use std::sync::LazyLock; + use api_models::webhooks::IncomingWebhookEvent; use base64::{self, Engine}; use common_enums::enums; @@ -23,7 +25,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -163,23 +168,6 @@ impl ConnectorCommon for Getnet { } impl ConnectorValidation for Getnet { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::Scheduled | enums::CaptureMethod::ManualMultiple => Err( - utils::construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } - fn validate_psync_reference_id( &self, data: &PaymentsSyncData, @@ -829,4 +817,70 @@ impl webhooks::IncomingWebhook for Getnet { } } -impl ConnectorSpecifications for Getnet {} +static GETNET_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::RuPay, + common_enums::CardNetwork::Maestro, + ]; + + let mut getnet_supported_payment_methods = SupportedPaymentMethods::new(); + + getnet_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network, + } + }), + ), + }, + ); + + getnet_supported_payment_methods +}); + +static GETNET_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Getnet", + description: "Getnet is a high-tech global payment platform that helps businesses accept payments securely while providing the best frictionless experience for customers everywhere.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static GETNET_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = + [enums::EventClass::Payments, enums::EventClass::Refunds]; + +impl ConnectorSpecifications for Getnet { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&GETNET_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*GETNET_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&GETNET_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/hipay.rs b/crates/hyperswitch_connectors/src/connectors/hipay.rs index d58c81c737d..c0d02156ebc 100644 --- a/crates/hyperswitch_connectors/src/connectors/hipay.rs +++ b/crates/hyperswitch_connectors/src/connectors/hipay.rs @@ -1,6 +1,8 @@ pub mod transformers; +use std::sync::LazyLock; + use base64::Engine; -use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType}; +use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType}; use common_utils::{ consts::BASE64_ENGINE, errors::{self as common_errors, CustomResult}, @@ -21,7 +23,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData, @@ -251,28 +256,7 @@ impl ConnectorCommon for Hipay { } } -impl ConnectorValidation for Hipay { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<CaptureMethod>, - _payment_method: PaymentMethod, - _pmt: Option<PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - CaptureMethod::Automatic - | CaptureMethod::Manual - | CaptureMethod::SequentialAutomatic => Ok(()), - CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => { - Err(errors::ConnectorError::NotSupported { - message: capture_method.to_string(), - connector: self.id(), - } - .into()) - } - } - } -} +impl ConnectorValidation for Hipay {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Hipay {} @@ -768,4 +752,86 @@ impl webhooks::IncomingWebhook for Hipay { } } -impl ConnectorSpecifications for Hipay {} +static HIPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + CaptureMethod::Automatic, + CaptureMethod::Manual, + CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut hipay_supported_payment_methods = SupportedPaymentMethods::new(); + + hipay_supported_payment_methods.add( + PaymentMethod::Card, + PaymentMethodType::Credit, + 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::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + hipay_supported_payment_methods.add( + PaymentMethod::Card, + 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::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + hipay_supported_payment_methods +}); + +static HIPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Hipay", + description: "HiPay is an independent global payment service provider that is based in France.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static HIPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Hipay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&HIPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*HIPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&HIPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index d2be42a1828..03ef376fbbe 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; use common_enums::enums; @@ -24,7 +26,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -50,8 +55,8 @@ use crate::{ constants::headers, types::ResponseRouterData, utils::{ - construct_not_supported_error_report, convert_amount, get_http_header, - get_unimplemented_payment_method_error_message, missing_field_err, RefundsRequestData, + convert_amount, get_http_header, get_unimplemented_payment_method_error_message, + missing_field_err, RefundsRequestData, }, }; @@ -133,24 +138,7 @@ impl ConnectorCommon for Klarna { } } -impl ConnectorValidation for Klarna { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - construct_not_supported_error_report(capture_method, self.id()), - ), - } - } -} +impl ConnectorValidation for Klarna {} impl api::Payment for Klarna {} @@ -1369,4 +1357,47 @@ impl IncomingWebhook for Klarna { } } -impl ConnectorSpecifications for Klarna {} +static KLARNA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut klarna_supported_payment_methods = SupportedPaymentMethods::new(); + + klarna_supported_payment_methods.add( + enums::PaymentMethod::PayLater, + enums::PaymentMethodType::Klarna, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + klarna_supported_payment_methods +}); + +static KLARNA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Klarna", + description: "Klarna provides payment processing services for the e-commerce industry, managing store claims and customer payments.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static KLARNA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Klarna { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&KLARNA_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*KLARNA_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&KLARNA_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/moneris.rs b/crates/hyperswitch_connectors/src/connectors/moneris.rs index ae4832b5597..fffd71a4e0b 100644 --- a/crates/hyperswitch_connectors/src/connectors/moneris.rs +++ b/crates/hyperswitch_connectors/src/connectors/moneris.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use common_enums::enums; use common_utils::{ errors::CustomResult, @@ -20,7 +22,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, @@ -182,23 +187,6 @@ impl ConnectorCommon for Moneris { } impl ConnectorValidation for Moneris { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), - enums::CaptureMethod::ManualMultiple - | enums::CaptureMethod::Scheduled - | enums::CaptureMethod::SequentialAutomatic => Err( - utils::construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } - fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -819,4 +807,85 @@ impl webhooks::IncomingWebhook for Moneris { } } -impl ConnectorSpecifications for Moneris {} +static MONERIS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut moneris_supported_payment_methods = SupportedPaymentMethods::new(); + + moneris_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + moneris_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + moneris_supported_payment_methods +}); + +static MONERIS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Moneris", + description: "Moneris is Canada's top payment solutions provider, empowering businesses with innovative mobile, online & in-store solutions.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static MONERIS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Moneris { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&MONERIS_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*MONERIS_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&MONERIS_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/opennode.rs b/crates/hyperswitch_connectors/src/connectors/opennode.rs index dde5b9adfcd..5ce75b4332d 100644 --- a/crates/hyperswitch_connectors/src/connectors/opennode.rs +++ b/crates/hyperswitch_connectors/src/connectors/opennode.rs @@ -1,7 +1,8 @@ pub mod transformers; -use std::fmt::Debug; +use std::{fmt::Debug, sync::LazyLock}; +use common_enums::enums; use common_utils::{ crypto, errors::CustomResult, @@ -21,7 +22,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundsRouterData, @@ -439,4 +443,45 @@ impl IncomingWebhook for Opennode { } } -impl ConnectorSpecifications for Opennode {} +static OPENNODE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; + + let mut opennode_supported_payment_methods = SupportedPaymentMethods::new(); + + opennode_supported_payment_methods.add( + enums::PaymentMethod::Crypto, + enums::PaymentMethodType::CryptoCurrency, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::NotSupported, + supported_capture_methods, + specific_features: None, + }, + ); + + opennode_supported_payment_methods + }); + +static OPENNODE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Opennode", + description: + "OpenNode offers accessible way for e-commerce businesses to process bitcoin payments.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static OPENNODE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Opennode { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&OPENNODE_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*OPENNODE_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&OPENNODE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index b0c4d7f3a38..f32f5a34e33 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -397,6 +397,23 @@ sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE", currency = "CHF,EUR" credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + +[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 = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } + #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } @@ -438,8 +455,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource"
2025-04-22T18:29:30Z
## Description <!-- Describe your changes in detail --> Added Getnet, Hipay, Klarna, Moneris, Opennode in feature matrix API ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
7b3c33c81c8f896847a3a0bb0ead90a6a67f8e61
Postman Tests Request: ``` curl --location 'http://localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header '[api-key]' ``` Response: ``` { "connector_count": 5, "connectors": [ { "name": "GETNET", "display_name": "Getnet", "description": "Getnet is a high-tech global payment platform that helps businesses accept payments securely while providing the best frictionless experience for customers everywhere.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay", "RuPay", "Maestro" ], "supported_countries": [ "FIN", "BEL", "SWE", "IRL", "ESP", "NLD", "ARG", "NOR", "ARE", "POL", "MEX", "BRA", "ITA", "GBR", "CHE", "AUT", "DNK", "IND", "PRT", "CHL", "URY", "LUX", "FRA", "DEU" ], "supported_currencies": [ "ARS", "UYU", "EUR", "SEK", "NOK", "CHF", "INR", "AED", "MXN", "PLN", "DKK", "CLP", "BRL", "GBP" ] } ], "supported_webhook_flows": [ "payments", "refunds" ] }, { "name": "HIPAY", "display_name": "Hipay", "description": "HiPay is an independent global payment service provider that is based in France.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "supported_countries": [ "ZAF", "SWE", "CAN", "JPN", "HKG", "NOR", "CZE", "POL", "DNK", "USA", "GBR", "AUS", "CHE" ], "supported_currencies": [ "EUR", "GBP", "NOK", "HKD", "AUD", "ZAR", "CHF", "SEK", "DKK", "PLN", "CZK", "USD", "CAD", "JPY" ] }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "supported_countries": [ "AUS", "USA", "CAN", "CZE", "POL", "SWE", "GBR", "NOR", "ZAF", "DNK", "CHE", "JPN", "HKG" ], "supported_currencies": [ "HKD", "DKK", "SEK", "PLN", "GBP", "CAD", "CZK", "JPY", "USD", "EUR", "AUD", "NOK", "CHF", "ZAR" ] } ], "supported_webhook_flows": [] }, { "name": "KLARNA", "display_name": "Klarna", "description": "Klarna provides payment processing services for the e-commerce industry, managing store claims and customer payments.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "pay_later", "payment_method_type": "klarna", "payment_method_type_display_name": "Klarna", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "GRC", "PRT", "ESP", "CHE", "SWE", "CZE", "IRL", "FIN", "USA", "GBR", "NZL", "POL", "DNK", "NLD", "BEL", "NOR", "CAN", "AUS", "ITA", "DEU", "FRA", "AUT" ], "supported_currencies": [ "PLN", "CZK", "NOK", "CHF", "CAD", "AUD", "NZD", "DKK", "GBP", "SEK", "EUR", "USD" ] } ], "supported_webhook_flows": [] }, { "name": "MONERIS", "display_name": "Moneris", "description": "Moneris is Canada's top payment solutions provider, empowering businesses with innovative mobile, online & in-store solutions.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "supported_countries": [ "VUT", "SGP", "HUN", "DOM", "TUN", "LAO", "THA", "WSM", "PRY", "SLV", "BDI", "SVN", "KAZ", "TZA", "ESP", "TUR", "SLE", "BLZ", "MDA", "SWE", "BMU", "AGO", "ISR", "PRT", "BGR", "KWT", "DEU", "JOR", "SYC", "MRT", "BGD", "IDN", "CHL", "LUX", "GRC", "RWA", "VNM", "BIH", "SHN", "UGA", "HRV", "SRB", "CHE", "MDV", "FIN", "PER", "KEN", "BTN", "GIN", "ROU", "NIC", "KOR", "NAM", "COM", "CUB", "LVA", "DJI", "ZAF", "SLB", "ARE", "AUT", "MDG", "ITA", "GBR", "SAU", "LKA", "BHR", "RUS", "ZMB", "BRB", "NZL", "LSO", "MAC", "LBR", "HND", "PNG", "PAK", "USA", "GTM", "TKM", "AZE", "CRI", "POL", "BEL", "TJK", "AUS", "BRA", "UZB", "QAT", "EGY", "MWI", "CYM", "NOR", "ALB", "AFG", "DZA", "MEX", "DNK", "HKG", "MYS", "GUY", "FRA", "SWZ", "BLR", "JPN", "BRN", "NGA", "IND", "SVK", "LTU", "TWN", "MAR", "JAM", "BOL", "CZE", "EST", "TTO", "CYP", "COL", "ISL", "IRL", "GEO", "URY", "ABW", "MLT", "MKD", "GIB", "FJI", "CHN", "NLD", "OMN", "HTI", "NPL", "SUR", "GMB", "CPV", "ARG", "MOZ", "MUS" ], "supported_currencies": [ "PGK", "ZAR", "LSL", "MGA", "MWK", "AZN", "BIF", "NGN", "NIO", "JOD", "KWD", "NOK", "MYR", "HUF", "NAD", "AFN", "SBD", "INR", "BBD", "GTQ", "RUB", "GMD", "WST", "ALL", "MXN", "RON", "BYN", "MAD", "OMR", "HRK", "BAM", "HTG", "RSD", "BDT", "TMT", "CHF", "AUD", "AWG", "AED", "TTD", "QAR", "BND", "SEK", "TND", "DZD", "RWF", "BOB", "JMD", "XPF", "NZD", "VUV", "UZS", "PYG", "ARS", "TJS", "AOA", "MOP", "UGX", "DOP", "SLL", "BRL", "KYD", "THB", "FJD", "BZD", "KMF", "MKD", "UYU", "XOF", "DKK", "PHP", "SHP", "SGD", "BTN", "MUR", "SCR", "XCD", "ZMW", "JPY", "PEN", "ANG", "HKD", "KES", "LAK", "SZL", "CRC", "PLN", "CNY", "SVC", "IDR", "MDL", "USD", "VND", "BMD", "DJF", "GEL", "KRW", "KZT", "NPR", "PKR", "CUP", "MRU", "CZK", "ILS", "GYD", "LKR", "LRD", "BGN", "GIP", "TZS", "EUR", "GBP", "MZN", "BHD", "MVR", "SAR", "TWD", "COP", "GNF", "SRD", "TRY", "HNL", "EGP", "ISK", "CLP", "CVE" ] }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "supported_countries": [ "RWA", "MDV", "ISL", "FIN", "PRT", "COM", "USA", "UZB", "POL", "LAO", "SVK", "UGA", "BRN", "DOM", "MDA", "COL", "CRI", "BEL", "TKM", "KWT", "BGR", "MAR", "CHL", "SWE", "TWN", "JOR", "AUS", "MUS", "ARE", "KOR", "LUX", "SLV", "GRC", "URY", "LBR", "AUT", "HTI", "EST", "DEU", "ABW", "MAC", "MLT", "SLE", "OMN", "HND", "DJI", "AFG", "MYS", "THA", "SYC", "NIC", "GMB", "VUT", "PAK", "IND", "MOZ", "ROU", "JPN", "MKD", "ZAF", "BLR", "HKG", "LSO", "BDI", "PNG", "DNK", "EGY", "LKA", "ARG", "PRY", "BRA", "HRV", "JAM", "NOR", "IRL", "GIN", "BIH", "MEX", "BMU", "ITA", "WSM", "BRB", "BOL", "TJK", "FJI", "TUR", "NLD", "HUN", "CYP", "SAU", "ZMB", "ESP", "GEO", "RUS", "MDG", "DZA", "TTO", "AGO", "GTM", "SGP", "CYM", "GIB", "SVN", "FRA", "GUY", "MWI", "QAT", "LTU", "PER", "SWZ", "VNM", "LVA", "AZE", "BHR", "ISR", "CUB", "GBR", "BLZ", "CZE", "SLB", "MRT", "NGA", "BGD", "CHN", "SUR", "KEN", "ALB", "TUN", "SHN", "CHE", "BTN", "NZL", "KAZ", "NAM", "TZA", "CPV", "IDN", "SRB", "NPL" ], "supported_currencies": [ "DOP", "ISK", "AUD", "BMD", "SBD", "XOF", "AFN", "RWF", "PGK", "UZS", "HRK", "LAK", "BBD", "CVE", "MZN", "CLP", "MUR", "GBP", "BHD", "JPY", "ALL", "KMF", "NZD", "QAR", "BZD", "GYD", "TJS", "NIO", "LKR", "LRD", "MKD", "PKR", "XCD", "MXN", "TMT", "USD", "SHP", "VND", "NOK", "GIP", "MYR", "BYN", "KZT", "BAM", "BDT", "BGN", "EUR", "NPR", "PHP", "ZAR", "XPF", "SLL", "BND", "CRC", "JOD", "RON", "WST", "SZL", "GNF", "TWD", "KES", "MOP", "JMD", "TZS", "GTQ", "CZK", "INR", "SCR", "GMD", "TRY", "HTG", "NGN", "MDL", "OMR", "KYD", "SGD", "HNL", "AED", "AWG", "SRD", "VUV", "CNY", "THB", "RUB", "SEK", "CHF", "KWD", "BIF", "BOB", "PLN", "MGA", "SAR", "TND", "PYG", "SVC", "TTD", "UGX", "ANG", "DJF", "DKK", "EGP", "DZD", "ZMW", "BRL", "AOA", "AZN", "IDR", "FJD", "MWK", "MRU", "GEL", "ARS", "HUF", "ILS", "MVR", "UYU", "MAD", "HKD", "LSL", "PEN", "NAD", "CUP", "KRW", "COP", "BTN", "RSD" ] } ], "supported_webhook_flows": [] }, { "name": "OPENNODE", "display_name": "Opennode", "description": "OpenNode offers accessible way for e-commerce businesses to process bitcoin payments.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_type_display_name": "Crypto", "mandates": "not_supported", "refunds": "not_supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "SVN", "PHL", "CAN", "AUS", "BEL", "MEX", "NLD", "FIN", "GBR", "MLT", "ESP", "USA", "EST", "PRT", "SVK", "JPN", "CYP", "LVA", "LTU", "ZAF", "BRA", "HRV", "DEU", "GRC", "ITA", "SGP", "FRA", "LUX", "IRL", "NZL", "AUT" ], "supported_currencies": [ "AUD", "JPY", "BRL", "CAD", "USD", "MXN", "PHP", "GBP", "EUR", "ZAR", "SGD", "NZD" ] } ], "supported_webhook_flows": [ "payments" ] } ] } ```
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/hyperswitch_connectors/src/connectors/getnet.rs", "crates/hyperswitch_connectors/src/connectors/hipay.rs", "crates/hyperswitch_connectors/src/connectors/klarna.rs", "crates/hyperswitch_connectors/src/connectors/moneris.rs", "crates/hyperswitch_connectors/src/connectors/opennode.rs", "loadtest/config/development.toml" ]
juspay/hyperswitch
juspay__hyperswitch-7870
Bug: Add support for caching and resolving last used lineage context Currently, after a user logs in and switches between merchants or profiles, their context is **not remembered** across sessions. Each new login resolves the default role from the DB and starts with a clean slate. This leads to: - Poor user experience for users with multiple roles - Repetitive DB queries for every login - No continuity across logins for previously active merchant/profile context ### Objective Introduce a mechanism to **cache the last used lineage context** (`org_id`, `merchant_id`, `profile_id`, `role_id`, `tenant_id`) in Redis and use it for JWT generation on subsequent logins. ### Expected Behavior - During login: - If lineage context exists in Redis → use it to validate and generate the JWT. - If not found or invalid → fallback to default DB-based user role resolution. - During merchant/profile switch: - Store the latest lineage context in Redis for future use. - Redis entries should have a **TTL of 7 days** to auto-expire for inactive users.
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 4f681cda25b..649b8820859 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -41,3 +41,6 @@ pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes pub const DEFAULT_PROFILE_NAME: &str = "default"; pub const DEFAULT_PRODUCT_TYPE: common_enums::MerchantProductType = common_enums::MerchantProductType::Orchestration; + +pub const LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS: i64 = 60 * 60 * 24 * 7; // 7 days +pub const LINEAGE_CONTEXT_PREFIX: &str = "LINEAGE_CONTEXT_"; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 91b20621da8..6e5360d8848 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -3169,6 +3169,23 @@ pub async fn switch_org_for_user( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: merchant_id.clone(), + role_id: role_id.clone(), + org_id: request.org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, @@ -3364,6 +3381,23 @@ pub async fn switch_merchant_for_user_in_org( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: merchant_id.clone(), + role_id: role_id.clone(), + org_id: org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, @@ -3480,6 +3514,23 @@ pub async fn switch_profile_for_user_in_org_and_merchant( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: user_from_token.merchant_id.clone(), + role_id: role_id.clone(), + org_id: user_from_token.org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8bf177035ef..016995cb550 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -23,7 +23,7 @@ use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; -use router_env::env; +use router_env::{env, logger}; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] @@ -39,7 +39,7 @@ use crate::{ routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, - utils::user::password, + utils::{self, user::password}, }; pub mod dashboard_metadata; @@ -1458,3 +1458,54 @@ where .change_context(UserErrors::InternalServerError) } } + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct LineageContext { + pub user_id: String, + pub merchant_id: id_type::MerchantId, + pub role_id: String, + pub org_id: id_type::OrganizationId, + pub profile_id: id_type::ProfileId, + pub tenant_id: id_type::TenantId, +} + +impl LineageContext { + pub async fn try_get_lineage_context_from_cache( + state: &SessionState, + user_id: &str, + ) -> Option<Self> { + // The errors are not handled here because we don't want to fail the request if the cache operation fails. + // The errors are logged for debugging purposes. + match utils::user::get_lineage_context_from_cache(state, user_id).await { + Ok(Some(ctx)) => Some(ctx), + Ok(None) => { + logger::debug!("Lineage context not found in Redis for user {}", user_id); + None + } + Err(e) => { + logger::error!( + "Failed to retrieve lineage context from Redis for user {}: {:?}", + user_id, + e + ); + None + } + } + } + + pub async fn try_set_lineage_context_in_cache(&self, state: &SessionState, user_id: &str) { + // The errors are not handled here because we don't want to fail the request if the cache operation fails. + // The errors are logged for debugging purposes. + if let Err(e) = + utils::user::set_lineage_context_in_cache(state, user_id, self.clone()).await + { + logger::error!( + "Failed to set lineage context in Redis for user {}: {:?}", + user_id, + e + ); + } else { + logger::debug!("Lineage context cached for user {}", user_id); + } + } +} diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index bf5556dd9a7..0214d3cdd15 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,6 +1,9 @@ use common_enums::TokenPurpose; use common_utils::id_type; -use diesel_models::{enums::UserStatus, user_role::UserRole}; +use diesel_models::{ + enums::{UserRoleVersion, UserStatus}, + user_role::UserRole, +}; use error_stack::ResultExt; use masking::Secret; @@ -10,6 +13,7 @@ use crate::{ db::user_role::ListUserRolesByUserIdPayload, routes::SessionState, services::authentication as auth, + types::domain::LineageContext, utils, }; @@ -124,23 +128,93 @@ impl JWTFlow { next_flow: &NextFlow, user_role: &UserRole, ) -> UserResult<Secret<String>> { + let user_id = next_flow.user.get_user_id(); + let cached_lineage_context = + LineageContext::try_get_lineage_context_from_cache(state, user_id).await; + + let new_lineage_context = match cached_lineage_context { + Some(ctx) => { + let tenant_id = ctx.tenant_id.clone(); + let user_role_match_v1 = state + .global_store + .find_user_role_by_user_id_and_lineage( + &ctx.user_id, + &tenant_id, + &ctx.org_id, + &ctx.merchant_id, + &ctx.profile_id, + UserRoleVersion::V1, + ) + .await + .is_ok(); + + if user_role_match_v1 { + ctx + } else { + let user_role_match_v2 = state + .global_store + .find_user_role_by_user_id_and_lineage( + &ctx.user_id, + &tenant_id, + &ctx.org_id, + &ctx.merchant_id, + &ctx.profile_id, + UserRoleVersion::V2, + ) + .await + .is_ok(); + + if user_role_match_v2 { + ctx + } else { + // fallback to default lineage if cached context is invalid + Self::resolve_lineage_from_user_role(state, user_role, user_id).await? + } + } + } + None => + // no cached context found + { + Self::resolve_lineage_from_user_role(state, user_role, user_id).await? + } + }; + + new_lineage_context + .try_set_lineage_context_in_cache(state, user_id) + .await; + + auth::AuthToken::new_token( + new_lineage_context.user_id, + new_lineage_context.merchant_id, + new_lineage_context.role_id, + &state.conf, + new_lineage_context.org_id, + new_lineage_context.profile_id, + Some(new_lineage_context.tenant_id), + ) + .await + .map(|token| token.into()) + } + + pub async fn resolve_lineage_from_user_role( + state: &SessionState, + user_role: &UserRole, + user_id: &str, + ) -> UserResult<LineageContext> { let org_id = utils::user_role::get_single_org_id(state, user_role).await?; let merchant_id = utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?; let profile_id = utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?; - auth::AuthToken::new_token( - next_flow.user.get_user_id().to_string(), - merchant_id, - user_role.role_id.clone(), - &state.conf, + Ok(LineageContext { + user_id: user_id.to_string(), org_id, + merchant_id, profile_id, - Some(user_role.tenant_id.clone()), - ) - .await - .map(|token| token.into()) + role_id: user_role.role_id.clone(), + tenant_id: user_role.tenant_id.clone(), + }) } } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 89612fc1892..3e339a2a570 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -12,7 +12,10 @@ use redis_interface::RedisConnectionPool; use router_env::env; use crate::{ - consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, + consts::user::{ + LINEAGE_CONTEXT_PREFIX, LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, REDIS_SSO_PREFIX, + REDIS_SSO_TTL, + }, core::errors::{StorageError, UserErrors, UserResult}, routes::SessionState, services::{ @@ -20,7 +23,7 @@ use crate::{ authorization::roles::RoleInfo, }, types::{ - domain::{self, MerchantAccount, UserFromStorage}, + domain::{self, LineageContext, MerchantAccount, UserFromStorage}, transformers::ForeignFrom, }, }; @@ -339,3 +342,49 @@ pub async fn validate_email_domain_auth_type_using_db( .then_some(()) .ok_or(UserErrors::InvalidUserAuthMethodOperation.into()) } + +pub async fn get_lineage_context_from_cache( + state: &SessionState, + user_id: &str, +) -> UserResult<Option<LineageContext>> { + let connection = get_redis_connection(state)?; + let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); + let lineage_context = connection + .get_key::<Option<String>>(&key.into()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get lineage context from redis")?; + + match lineage_context { + Some(json_str) => { + let ctx = serde_json::from_str::<LineageContext>(&json_str) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to deserialize LineageContext from JSON")?; + Ok(Some(ctx)) + } + None => Ok(None), + } +} + +pub async fn set_lineage_context_in_cache( + state: &SessionState, + user_id: &str, + lineage_context: LineageContext, +) -> UserResult<()> { + let connection = get_redis_connection(state)?; + let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); + let serialized_lineage_context: String = serde_json::to_string(&lineage_context) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to serialize LineageContext")?; + connection + .set_key_with_expiry( + &key.into(), + serialized_lineage_context, + LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to set lineage context in redis")?; + + Ok(()) +}
2025-04-22T14:54:00Z
## Description <!-- Describe your changes in detail --> This PR introduces lineage context caching to enhance login and account-switch flows with better continuity and reduced DB load. ### Key Changes - **During Login:** - Attempt to fetch the last used `LineageContext` from Redis (`LINEAGE_CONTEXT_<user_id>`). - If context is found: - Validate whether a matching user role exists (using both `V1` and `V2` role versions). - If a valid user_role is found → use this lineage context to issue the JWT token. - If not → fallback to the default user_role-based resolution logic. - If context is **not found in cache**, fallback to the existing login flow entirely. - **During Account Switch:** - After switching org/merchant/profile context and issuing the new JWT token, the new `LineageContext` is saved to Redis (`LINEAGE_CONTEXT_<user_id>`). - This allows restoring the last used org/merchant/profile on future logins. - **Redis Cache Expiry:** - Cached lineage context entries are stored with a TTL of **7 days**. - If the user is inactive beyond this duration, the system reverts to default logic. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Improves user experience by remembering their last used account context across sessions. - Reduces unnecessary DB lookups during login for returning users. - Ensures fallback safety in case of invalid or expired lineage context. # ### Test 1: - Log in to the merchant account. - Check redis using the key: ```GET LINEAGE_CONTEXT_<user_id>``` The value should contain the last used lineage context for the user. - Switch to another org/merchant/profile. - Recheck redis with the same key: ```GET LINEAGE_CONTEXT_<user_id>```. The lineage should now be changed. ### Test 2: - After the above test, log out and log in back, within the TTL for the lineage_context, which is 7 days. - You should be logged in to exactly the same lineage which you last used. ### Test 3 (optional): - Have a note of the lineage. - Do not use this account for 7 days. - Try logging in now. - You should be logged in to a random account (possibly the lineage which you have not used last) - This proves, that the key has expired and the default fallback login is now used.
776bde00efce8be35e0c63c1bdc6215921babddf
Tested locally with TTL as 1 minute, keys are getting stored in redis <img width="1065" alt="Screenshot 2025-04-22 at 7 40 32 PM" src="https://github.com/user-attachments/assets/1201a92b-7957-4075-8ec6-9a75376c842a" /> <img width="1369" alt="image" src="https://github.com/user-attachments/assets/2e8fbec0-a1e1-4ef9-b280-67ccbea7b1d1" /> ![Screenshot 2025-04-22 at 7 41 43 PM](https://github.com/user-attachments/assets/b0cdf010-0828-4982-98a4-91625d707c84) ### Test 1: - Log in to the merchant account. - Check redis using the key: ```GET LINEAGE_CONTEXT_<user_id>``` The value should contain the last used lineage context for the user. - Switch to another org/merchant/profile. - Recheck redis with the same key: ```GET LINEAGE_CONTEXT_<user_id>```. The lineage should now be changed. ### Test 2: - After the above test, log out and log in back, within the TTL for the lineage_context, which is 7 days. - You should be logged in to exactly the same lineage which you last used. ### Test 3 (optional): - Have a note of the lineage. - Do not use this account for 7 days. - Try logging in now. - You should be logged in to a random account (possibly the lineage which you have not used last) - This proves, that the key has expired and the default fallback login is now used.
[ "crates/router/src/consts/user.rs", "crates/router/src/core/user.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/types/domain/user/decision_manager.rs", "crates/router/src/utils/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7844
Bug: Last used merchant account context To enhance the user experience, especially during sign-up or when switching between multiple merchant accounts, we can store the last used merchant account context directly in the users table. This allows the system to automatically restore the previously active context when a user logs in or returns to the dashboard, rather than requiring them to manually select a merchant account each time.
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 4f681cda25b..649b8820859 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -41,3 +41,6 @@ pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes pub const DEFAULT_PROFILE_NAME: &str = "default"; pub const DEFAULT_PRODUCT_TYPE: common_enums::MerchantProductType = common_enums::MerchantProductType::Orchestration; + +pub const LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS: i64 = 60 * 60 * 24 * 7; // 7 days +pub const LINEAGE_CONTEXT_PREFIX: &str = "LINEAGE_CONTEXT_"; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 91b20621da8..6e5360d8848 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -3169,6 +3169,23 @@ pub async fn switch_org_for_user( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: merchant_id.clone(), + role_id: role_id.clone(), + org_id: request.org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, @@ -3364,6 +3381,23 @@ pub async fn switch_merchant_for_user_in_org( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: merchant_id.clone(), + role_id: role_id.clone(), + org_id: org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, @@ -3480,6 +3514,23 @@ pub async fn switch_profile_for_user_in_org_and_merchant( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: user_from_token.merchant_id.clone(), + role_id: role_id.clone(), + org_id: user_from_token.org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8bf177035ef..016995cb550 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -23,7 +23,7 @@ use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; -use router_env::env; +use router_env::{env, logger}; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] @@ -39,7 +39,7 @@ use crate::{ routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, - utils::user::password, + utils::{self, user::password}, }; pub mod dashboard_metadata; @@ -1458,3 +1458,54 @@ where .change_context(UserErrors::InternalServerError) } } + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct LineageContext { + pub user_id: String, + pub merchant_id: id_type::MerchantId, + pub role_id: String, + pub org_id: id_type::OrganizationId, + pub profile_id: id_type::ProfileId, + pub tenant_id: id_type::TenantId, +} + +impl LineageContext { + pub async fn try_get_lineage_context_from_cache( + state: &SessionState, + user_id: &str, + ) -> Option<Self> { + // The errors are not handled here because we don't want to fail the request if the cache operation fails. + // The errors are logged for debugging purposes. + match utils::user::get_lineage_context_from_cache(state, user_id).await { + Ok(Some(ctx)) => Some(ctx), + Ok(None) => { + logger::debug!("Lineage context not found in Redis for user {}", user_id); + None + } + Err(e) => { + logger::error!( + "Failed to retrieve lineage context from Redis for user {}: {:?}", + user_id, + e + ); + None + } + } + } + + pub async fn try_set_lineage_context_in_cache(&self, state: &SessionState, user_id: &str) { + // The errors are not handled here because we don't want to fail the request if the cache operation fails. + // The errors are logged for debugging purposes. + if let Err(e) = + utils::user::set_lineage_context_in_cache(state, user_id, self.clone()).await + { + logger::error!( + "Failed to set lineage context in Redis for user {}: {:?}", + user_id, + e + ); + } else { + logger::debug!("Lineage context cached for user {}", user_id); + } + } +} diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index bf5556dd9a7..0214d3cdd15 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,6 +1,9 @@ use common_enums::TokenPurpose; use common_utils::id_type; -use diesel_models::{enums::UserStatus, user_role::UserRole}; +use diesel_models::{ + enums::{UserRoleVersion, UserStatus}, + user_role::UserRole, +}; use error_stack::ResultExt; use masking::Secret; @@ -10,6 +13,7 @@ use crate::{ db::user_role::ListUserRolesByUserIdPayload, routes::SessionState, services::authentication as auth, + types::domain::LineageContext, utils, }; @@ -124,23 +128,93 @@ impl JWTFlow { next_flow: &NextFlow, user_role: &UserRole, ) -> UserResult<Secret<String>> { + let user_id = next_flow.user.get_user_id(); + let cached_lineage_context = + LineageContext::try_get_lineage_context_from_cache(state, user_id).await; + + let new_lineage_context = match cached_lineage_context { + Some(ctx) => { + let tenant_id = ctx.tenant_id.clone(); + let user_role_match_v1 = state + .global_store + .find_user_role_by_user_id_and_lineage( + &ctx.user_id, + &tenant_id, + &ctx.org_id, + &ctx.merchant_id, + &ctx.profile_id, + UserRoleVersion::V1, + ) + .await + .is_ok(); + + if user_role_match_v1 { + ctx + } else { + let user_role_match_v2 = state + .global_store + .find_user_role_by_user_id_and_lineage( + &ctx.user_id, + &tenant_id, + &ctx.org_id, + &ctx.merchant_id, + &ctx.profile_id, + UserRoleVersion::V2, + ) + .await + .is_ok(); + + if user_role_match_v2 { + ctx + } else { + // fallback to default lineage if cached context is invalid + Self::resolve_lineage_from_user_role(state, user_role, user_id).await? + } + } + } + None => + // no cached context found + { + Self::resolve_lineage_from_user_role(state, user_role, user_id).await? + } + }; + + new_lineage_context + .try_set_lineage_context_in_cache(state, user_id) + .await; + + auth::AuthToken::new_token( + new_lineage_context.user_id, + new_lineage_context.merchant_id, + new_lineage_context.role_id, + &state.conf, + new_lineage_context.org_id, + new_lineage_context.profile_id, + Some(new_lineage_context.tenant_id), + ) + .await + .map(|token| token.into()) + } + + pub async fn resolve_lineage_from_user_role( + state: &SessionState, + user_role: &UserRole, + user_id: &str, + ) -> UserResult<LineageContext> { let org_id = utils::user_role::get_single_org_id(state, user_role).await?; let merchant_id = utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?; let profile_id = utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?; - auth::AuthToken::new_token( - next_flow.user.get_user_id().to_string(), - merchant_id, - user_role.role_id.clone(), - &state.conf, + Ok(LineageContext { + user_id: user_id.to_string(), org_id, + merchant_id, profile_id, - Some(user_role.tenant_id.clone()), - ) - .await - .map(|token| token.into()) + role_id: user_role.role_id.clone(), + tenant_id: user_role.tenant_id.clone(), + }) } } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 89612fc1892..3e339a2a570 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -12,7 +12,10 @@ use redis_interface::RedisConnectionPool; use router_env::env; use crate::{ - consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, + consts::user::{ + LINEAGE_CONTEXT_PREFIX, LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, REDIS_SSO_PREFIX, + REDIS_SSO_TTL, + }, core::errors::{StorageError, UserErrors, UserResult}, routes::SessionState, services::{ @@ -20,7 +23,7 @@ use crate::{ authorization::roles::RoleInfo, }, types::{ - domain::{self, MerchantAccount, UserFromStorage}, + domain::{self, LineageContext, MerchantAccount, UserFromStorage}, transformers::ForeignFrom, }, }; @@ -339,3 +342,49 @@ pub async fn validate_email_domain_auth_type_using_db( .then_some(()) .ok_or(UserErrors::InvalidUserAuthMethodOperation.into()) } + +pub async fn get_lineage_context_from_cache( + state: &SessionState, + user_id: &str, +) -> UserResult<Option<LineageContext>> { + let connection = get_redis_connection(state)?; + let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); + let lineage_context = connection + .get_key::<Option<String>>(&key.into()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get lineage context from redis")?; + + match lineage_context { + Some(json_str) => { + let ctx = serde_json::from_str::<LineageContext>(&json_str) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to deserialize LineageContext from JSON")?; + Ok(Some(ctx)) + } + None => Ok(None), + } +} + +pub async fn set_lineage_context_in_cache( + state: &SessionState, + user_id: &str, + lineage_context: LineageContext, +) -> UserResult<()> { + let connection = get_redis_connection(state)?; + let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); + let serialized_lineage_context: String = serde_json::to_string(&lineage_context) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to serialize LineageContext")?; + connection + .set_key_with_expiry( + &key.into(), + serialized_lineage_context, + LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to set lineage context in redis")?; + + Ok(()) +}
2025-04-22T14:54:00Z
## Description <!-- Describe your changes in detail --> This PR introduces lineage context caching to enhance login and account-switch flows with better continuity and reduced DB load. ### Key Changes - **During Login:** - Attempt to fetch the last used `LineageContext` from Redis (`LINEAGE_CONTEXT_<user_id>`). - If context is found: - Validate whether a matching user role exists (using both `V1` and `V2` role versions). - If a valid user_role is found → use this lineage context to issue the JWT token. - If not → fallback to the default user_role-based resolution logic. - If context is **not found in cache**, fallback to the existing login flow entirely. - **During Account Switch:** - After switching org/merchant/profile context and issuing the new JWT token, the new `LineageContext` is saved to Redis (`LINEAGE_CONTEXT_<user_id>`). - This allows restoring the last used org/merchant/profile on future logins. - **Redis Cache Expiry:** - Cached lineage context entries are stored with a TTL of **7 days**. - If the user is inactive beyond this duration, the system reverts to default logic. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Improves user experience by remembering their last used account context across sessions. - Reduces unnecessary DB lookups during login for returning users. - Ensures fallback safety in case of invalid or expired lineage context. # ### Test 1: - Log in to the merchant account. - Check redis using the key: ```GET LINEAGE_CONTEXT_<user_id>``` The value should contain the last used lineage context for the user. - Switch to another org/merchant/profile. - Recheck redis with the same key: ```GET LINEAGE_CONTEXT_<user_id>```. The lineage should now be changed. ### Test 2: - After the above test, log out and log in back, within the TTL for the lineage_context, which is 7 days. - You should be logged in to exactly the same lineage which you last used. ### Test 3 (optional): - Have a note of the lineage. - Do not use this account for 7 days. - Try logging in now. - You should be logged in to a random account (possibly the lineage which you have not used last) - This proves, that the key has expired and the default fallback login is now used.
776bde00efce8be35e0c63c1bdc6215921babddf
Tested locally with TTL as 1 minute, keys are getting stored in redis <img width="1065" alt="Screenshot 2025-04-22 at 7 40 32 PM" src="https://github.com/user-attachments/assets/1201a92b-7957-4075-8ec6-9a75376c842a" /> <img width="1369" alt="image" src="https://github.com/user-attachments/assets/2e8fbec0-a1e1-4ef9-b280-67ccbea7b1d1" /> ![Screenshot 2025-04-22 at 7 41 43 PM](https://github.com/user-attachments/assets/b0cdf010-0828-4982-98a4-91625d707c84) ### Test 1: - Log in to the merchant account. - Check redis using the key: ```GET LINEAGE_CONTEXT_<user_id>``` The value should contain the last used lineage context for the user. - Switch to another org/merchant/profile. - Recheck redis with the same key: ```GET LINEAGE_CONTEXT_<user_id>```. The lineage should now be changed. ### Test 2: - After the above test, log out and log in back, within the TTL for the lineage_context, which is 7 days. - You should be logged in to exactly the same lineage which you last used. ### Test 3 (optional): - Have a note of the lineage. - Do not use this account for 7 days. - Try logging in now. - You should be logged in to a random account (possibly the lineage which you have not used last) - This proves, that the key has expired and the default fallback login is now used.
[ "crates/router/src/consts/user.rs", "crates/router/src/core/user.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/types/domain/user/decision_manager.rs", "crates/router/src/utils/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7908
Bug: [REFACTOR] Refactor Merchant Payment Method List Refactor Merchant PML to list the wallets even after they are saved by the customer
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 2643b97904c..fc3ff05d864 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1922,7 +1922,10 @@ pub enum PaymentMethodType { impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { - matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) + matches!( + self, + Self::ApplePay | Self::GooglePay | Self::SamsungPay | Self::Paypal | Self::Klarna + ) } pub fn to_display_name(&self) -> String { let display_name = match self { diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index e9fefffbb07..14744cd2d56 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3459,61 +3459,6 @@ pub async fn list_payment_methods( response ); - // Filter out wallet payment method from mca if customer has already saved it - customer - .as_ref() - .async_map(|customer| async { - let wallet_pm_exists = response - .iter() - .any(|mca| mca.payment_method == enums::PaymentMethod::Wallet); - if wallet_pm_exists { - match db - .find_payment_method_by_customer_id_merchant_id_status( - &((&state).into()), - &key_store, - &customer.customer_id, - merchant_account.get_id(), - common_enums::PaymentMethodStatus::Active, - None, - merchant_account.storage_scheme, - ) - .await - { - Ok(customer_payment_methods) => { - let customer_wallet_pm = customer_payment_methods - .iter() - .filter(|cust_pm| { - cust_pm.get_payment_method_type() == Some(enums::PaymentMethod::Wallet) - }) - .collect::<Vec<_>>(); - - response.retain(|mca| { - !(mca.payment_method == enums::PaymentMethod::Wallet - && customer_wallet_pm.iter().any(|cust_pm| { - cust_pm.get_payment_method_subtype() == Some(mca.payment_method_type) - })) - }); - - logger::debug!("Filtered out wallet payment method from mca since customer has already saved it"); - Ok(()) - } - Err(error) => { - if error.current_context().is_db_not_found() { - Ok(()) - } else { - Err(error) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to find payment methods for a customer") - } - } - } - } else { - Ok(()) - } - }) - .await - .transpose()?; - let mut pmt_to_auth_connector: HashMap< enums::PaymentMethod, HashMap<enums::PaymentMethodType, String>,
2025-04-22T08:35:28Z
## Description - Earlier we used to support filtering of wallet payment methods for customer pml, if it has been saved by the merchant via off- session payments once , the changes were made in the following [PR](https://github.com/juspay/hyperswitch/pull/4038) - In this PR we are reverting the logic , the decision was taken to show the wallets in merchant pml even though a single entry in customer pml is present for that particular wallets , - internally the decision was taken to allow overriding of the wallets connector mandate id for the customer for off-session payments ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
9e82c40eed78ddabcbf0b0531b4fbbcc44d9142a
- Create MA and an MCA with wallets -Create a payment and Save one wallet (eg: Paypal) - Create a new payment intent - List the Merchant PML again, Paypal would still be there ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "paypal" ] }, { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "paypal" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "shipping.address.first_name": { "required_field": "shipping.address.first_name", "display_name": "shipping_first_name", "field_type": "user_shipping_name", "value": "PiX" }, "shipping.address.last_name": { "required_field": "shipping.address.last_name", "display_name": "shipping_last_name", "field_type": "user_shipping_name", "value": null }, "shipping.address.city": { "required_field": "shipping.address.city", "display_name": "city", "field_type": "user_shipping_address_city", "value": "San Fransico" }, "shipping.address.line1": { "required_field": "shipping.address.line1", "display_name": "line1", "field_type": "user_shipping_address_line1", "value": "1467" }, "shipping.address.country": { "required_field": "shipping.address.country", "display_name": "country", "field_type": { "user_shipping_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "shipping.address.state": { "required_field": "shipping.address.state", "display_name": "state", "field_type": "user_shipping_address_state", "value": "California" }, "shipping.address.zip": { "required_field": "shipping.address.zip", "display_name": "zip", "field_type": "user_shipping_address_pincode", "value": "94122" } }, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "paypal" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "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 }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "paypal" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "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_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_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_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ```
[ "crates/common_enums/src/enums.rs", "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7852
Bug: [CHORE] remove billing details are required fields from Worldpay Worldpay does not mandate sending billing address during payment create request. These fields are needed to be removed as required fields which are configured as a part of dynamic required fields for payment widget.
diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 175b82192b4..2f4fb7a8013 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1450,23 +1450,6 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { RequiredField::CardNumber, RequiredField::CardExpMonth, RequiredField::CardExpYear, - RequiredField::BillingAddressLine1, - RequiredField::BillingAddressCountries(vec![ - "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", - ]), - RequiredField::BillingAddressCity, - RequiredField::BillingAddressZip, ], ), ),
2025-04-18T11:38:10Z
## Description This PR removes billing details as required fields for Worldpay connector. ## Motivation and Context This change helps in not showing the billing details as required fields on the payment widget. #
eabef328c665cfbaf953a5eb15bd15484c62dcf7
Locally, by rendering payment links. <details> <summary>Fetch account payment method list</summary> cURL curl 'http://localhost:8080/account/payment_methods?client_secret=pay_62mvQc0WyVZ5pe8QxqhR_secret_K6C6bulFCe6jdm6GogvF' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:137.0) Gecko/20100101 Firefox/137.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate, br, zstd' -H 'Referer: http://localhost:9050/' -H 'api-key: pk_dev_36edab4ded2a4a8abdbcffaa254eb7e4' -H 'content-type: application/json' -H 'x-browser-name: Firefox' -H 'x-browser-version: 137.0' -H 'x-client-platform: web' -H 'x-client-version: 0.122.6' -H 'x-payment-confirm-source: sdk' -H 'Origin: http://localhost:9050' -H 'Connection: keep-alive' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-site' -H 'Priority: u=4' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' Response { "redirect_url": "https://google.com/success", "currency": "EUR", "payment_methods": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "worldpay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "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 } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "worldpay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "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 } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } </details>
[ "crates/payment_methods/src/configs/payment_connector_required_fields.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7899
Bug: [FEATURE] Flowbird Archipel connector ### Feature Description Initial contribution from Flowbird. ### Possible Implementation Implementation of the Archipel connector. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
2025-04-18T10:19:58Z
[Flowbird Archipel connector implementation](https://www.flowbird.group/smartcity/us/wp-content/uploads/2019/11/Brochure-PAYMENT-ACCEPTANCE-EN-4-pages.pdf) Closes #7899 Co-authored-by: Guillaume Bague <[email protected]>
1192bd5247dc099f647963a90ccc85a356b9f742
[]
juspay/hyperswitch
juspay__hyperswitch-7850
Bug: Update Postman Assertions for Payments API Responses for `Stripe` - `Sofort` `Sofort` Bank Redirect using `Stripe` has been deprecated, which fails Postman Test Cases for the same.
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json index f529af7b066..db5ff59100b 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json @@ -19,22 +19,21 @@ "Scenario13-BNPL-afterpay", "Scenario14-BNPL-affirm", "Scenario15-Bank Redirect-Ideal", - "Scenario16-Bank Redirect-sofort", - "Scenario17-Bank Redirect-eps", - "Scenario18-Bank Transfer-ach", - "Scenario19-Bank Debit-ach", - "Scenario20-Wallet-Wechatpay", - "Scenario21- Update address and List Payment method", - "Scenario22- Update Amount", - "Scenario23-Add card flow", - "Scenario24-Don't Pass CVV for save card flow and verifysuccess payment", - "Scenario25-Save card payment with manual capture", - "Scenario26-Create payment without customer_id and with billing address and shipping address", - "Scenario27-Confirm a payment with requires_customer_action status", - "Scenario28-Create payment with payment method billing", - "Scenario29-Update payment with payment method billing", - "Scenario30-Pass payment method billing in Confirm", - "Scenario31-Ensure API Contract for Payment Method Data", - "Scenario32-Check is payment checks are populated" + "Scenario16-Bank Redirect-eps", + "Scenario17-Bank Transfer-ach", + "Scenario18-Bank Debit-ach", + "Scenario19-Wallet-Wechatpay", + "Scenario20- Update address and List Payment method", + "Scenario21- Update Amount", + "Scenario22-Add card flow", + "Scenario23-Don't Pass CVV for save card flow and verifysuccess payment", + "Scenario24-Save card payment with manual capture", + "Scenario25-Create payment without customer_id and with billing address and shipping address", + "Scenario26-Confirm a payment with requires_customer_action status", + "Scenario27-Create payment with payment method billing", + "Scenario28-Update payment with payment method billing", + "Scenario29-Pass payment method billing in Confirm", + "Scenario30-Ensure API Contract for Payment Method Data", + "Scenario31-Check is payment checks are populated" ] } \ No newline at end of file diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/event.test.js 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/Scenario16-Bank Redirect-eps/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js deleted file mode 100644 index c2e29faee5a..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js +++ /dev/null @@ -1,123 +0,0 @@ -// 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 "failed" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'failed'", - function () { - pm.expect(jsonData.status).to.eql("failed"); - }, - ); -} - -// Response body should have "next_action" -pm.test( - "[POST]::/payments - Content check if 'next_action' exists", - function () { - pm.expect(typeof jsonData.next_action !== "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 "payment_method_not_available" for "error_code" -if (jsonData?.error_code) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'payment_method_not_available'", - function () { - pm.expect(jsonData.error_code).to.eql("payment_method_not_available"); - }, - ); -} - -// Response body should have value "Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort" for "error_message" -if (jsonData?.error_message) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort'", - function () { - pm.expect(jsonData.error_message).to.eql("Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/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"); - }, - ); -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/request.json deleted file mode 100644 index 686ac64b607..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/request.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{publishable_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "payment_method": "bank_redirect", - "payment_method_type": "sofort", - "payment_method_data": { - "bank_redirect": { - "sofort": { - "bank_name": "hypo_noe_lb_fur_niederosterreich_u_wien", - "preferred_language": "en" - } - } - }, - "client_secret": "{{client_secret}}" - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", - "host": ["{{baseUrl}}"], - "path": ["payments", ":id", "confirm"], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" -} diff --git a/postman/collection-dir/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 deleted file mode 100644 index 0b0c56d2660..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount": 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", - "host": ["{{baseUrl}}"], - "path": ["payments"] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js deleted file mode 100644 index e99ef624bf2..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js +++ /dev/null @@ -1,91 +0,0 @@ -// Validate status 2xx -pm.test("[GET]::/payments/:id - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[GET]::/payments/:id - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); -}); - -// Validate if response has JSON Body -pm.test("[GET]::/payments/:id - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log( - "- use {{payment_id}} as collection variable for value", - jsonData.payment_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", - ); -} - -// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id -if (jsonData?.mandate_id) { - pm.collectionVariables.set("mandate_id", jsonData.mandate_id); - console.log( - "- use {{mandate_id}} as collection variable for value", - jsonData.mandate_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", - ); -} - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log( - "- use {{client_secret}} as collection variable for value", - jsonData.client_secret, - ); -} else { - console.log( - "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", - ); -} - -// Response body should have value "failed" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments:id - Content check if value for 'status' matches 'failed'", - function () { - pm.expect(jsonData.status).to.eql("failed"); - }, - ); -} - -// Response body should have value "payment_method_not_available" for "error_code" -if (jsonData?.error_code) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'payment_method_not_available'", - function () { - pm.expect(jsonData.error_code).to.eql("payment_method_not_available"); - }, - ); -} - -// Response body should have value "Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort" for "error_message" -if (jsonData?.error_message) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort'", - function () { - pm.expect(jsonData.error_message).to.eql("Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort"); - }, - ); -} \ No newline at end of file diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/event.test.js 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/Scenario18-Bank Debit-ach/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/.event.meta.json deleted file mode 100644 index 220b1a6723d..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.test.js", "event.prerequest.js"] -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/.event.meta.json deleted file mode 100644 index 0731450e6b2..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.test.js"] -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/request.json deleted file mode 100644 index 6cd4b7d96c5..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/request.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", - "host": ["{{baseUrl}}"], - "path": ["payments", ":id"], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/.event.meta.json deleted file mode 100644 index 0731450e6b2..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.test.js"] -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/.meta.json deleted file mode 100644 index 57d3f8e2bc7..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/.meta.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "childrenOrder": [ - "Payments - Create", - "Payments - Confirm", - "Payments - Retrieve" - ] -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.test.js deleted file mode 100644 index 0444324000a..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.test.js +++ /dev/null @@ -1,71 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[POST]::/payments - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); -}); - -// Validate if response has JSON Body -pm.test("[POST]::/payments - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log( - "- use {{payment_id}} as collection variable for value", - jsonData.payment_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", - ); -} - -// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id -if (jsonData?.mandate_id) { - pm.collectionVariables.set("mandate_id", jsonData.mandate_id); - console.log( - "- use {{mandate_id}} as collection variable for value", - jsonData.mandate_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", - ); -} - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log( - "- use {{client_secret}} as collection variable for value", - jsonData.client_secret, - ); -} else { - console.log( - "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", - ); -} - -// Response body should have value "requires_payment_method" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'", - function () { - pm.expect(jsonData.status).to.eql("requires_payment_method"); - }, - ); -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/request.json
2025-04-17T18:42:29Z
## Description <!-- Describe your changes in detail --> ### Summary of Changes Simply, Removed the Sofort TestCase for Stripe, nothing else. And, because of this had to make some name changes. _And the Errors showing up in the Screenshot labelled as After is not due to this PR_ ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The Postman Test Cases for `Sofort` using `Stripe` are failing because `Sofort` has been deprecated. #
69ba651abd13de76e603dab8bbc56c5f3ee2176c
**Before** <img width="1058" alt="image" src="https://github.com/user-attachments/assets/4aa5f40d-6ce1-4c08-a807-e985816237f6" /> **After** ![image](https://github.com/user-attachments/assets/dd26e322-d6c5-4f56-90ff-a768eb7e7813)
[ "postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.prerequest.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.prerequest.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.prerequest.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.prerequest.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/response.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/request.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/request.json", "postman/collection-dir/stripe/Flow" ]
juspay/hyperswitch
juspay__hyperswitch-7838
Bug: Add hyperswitch-react-demo-app to docker-compose
diff --git a/docker-compose.yml b/docker-compose.yml index ca8434cf058..cc58c38e88a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,7 +11,12 @@ services: prestart-hook: image: curlimages/curl-base:latest container_name: prestart-hook - entrypoint: ["/bin/sh", "-c", "apk add --no-cache bash && /bin/bash /prestart_hook.sh"] + entrypoint: + [ + "/bin/sh", + "-c", + "apk add --no-cache bash && /bin/bash /prestart_hook.sh", + ] volumes: - ./scripts/prestart_hook.sh:/prestart_hook.sh networks: @@ -60,7 +65,7 @@ services: environment: # format -> postgresql://DB_USER:DB_PASSWORD@HOST:PORT/DATABASE_NAME - DATABASE_URL=postgresql://db_user:db_pass@pg:5432/hyperswitch_db - + mailhog: image: mailhog/mailhog networks: @@ -100,13 +105,18 @@ services: container_name: poststart-hook depends_on: hyperswitch-server: - condition: service_healthy # Ensures it only starts when `hyperswitch-server` is healthy - entrypoint: ["/bin/sh", "-c", "apk add --no-cache bash jq && /bin/bash /poststart_hook.sh"] + condition: service_healthy # Ensures it only starts when `hyperswitch-server` is healthy + entrypoint: + [ + "/bin/sh", + "-c", + "apk add --no-cache bash jq && /bin/bash /poststart_hook.sh", + ] volumes: - ./scripts/poststart_hook.sh:/poststart_hook.sh networks: - - router_net - + - router_net + hyperswitch-producer: image: docker.juspay.io/juspaydotin/hyperswitch-producer:standalone pull_policy: always @@ -174,20 +184,13 @@ services: pull_policy: always ports: - "9050:9050" - - "9060:9060" - - "5252:5252" networks: - router_net depends_on: hyperswitch-server: condition: service_healthy environment: - - HYPERSWITCH_PUBLISHABLE_KEY=placeholder_publishable_key - - HYPERSWITCH_SECRET_KEY=placeholder_api_key - - HYPERSWITCH_SERVER_URL=http://localhost:8080 - - HYPERSWITCH_SERVER_URL_FOR_DEMO_APP=http://hyperswitch-server:8080 - - HYPERSWITCH_CLIENT_URL=http://localhost:9050 - - SELF_SERVER_URL=http://localhost:5252 + - ENABLE_LOGGING=true - SDK_ENV=local - ENV_LOGGING_URL=http://localhost:3103 - ENV_BACKEND_URL=http://localhost:8080 @@ -442,3 +445,25 @@ services: volumes: - ./config/vector.yaml:/etc/vector/vector.yaml - /var/run/docker.sock:/var/run/docker.sock + + hyperswitch-demo: + image: docker.juspay.io/juspaydotin/hyperswitch-react-demo-app:latest + pull_policy: always + ports: + - "9060:9060" + - "5252:5252" + networks: + - router_net + depends_on: + hyperswitch-server: + condition: service_healthy + hyperswitch-web: + condition: service_healthy + environment: + - HYPERSWITCH_PUBLISHABLE_KEY=placeholder_publishable_key + - HYPERSWITCH_SECRET_KEY=placeholder_api_key + - PROFILE_ID=placeholder_profile_id + - HYPERSWITCH_CLIENT_URL=http://localhost:9050 + - HYPERSWITCH_SERVER_URL=http://localhost:8080 + labels: + logs: "promtail"
2025-04-17T08:35:03Z
## Description Added `hyperswitch-demo` to the Docker Compose setup to provide a visual interface for the SDK. ## Motivation and Context This addition enables merchants to preview and interact with the SDK in a demo environment, improving the overall developer experience. #
c3ac0d0bd63a349cee7100e6e06c1f65e411ad58
[ "docker-compose.yml" ]
juspay/hyperswitch
juspay__hyperswitch-7836
Bug: [FEATURE]: Add Refunds Retrieve and Rsync Flow in V2 apis. Add Refunds Retrieve and Rsync Flow in V2 apis.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 8b27fde3201..b6d6fb87e27 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3265,6 +3265,47 @@ ] } }, + "/v2/refunds/{id}": { + "get": { + "tags": [ + "Refunds" + ], + "summary": "Refunds - Retrieve", + "description": "Retrieves a Refund. This may be used to get the status of a previously initiated refund", + "operationId": "Retrieve a Refund", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The identifier for refund", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Refund retrieved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RefundResponse" + } + } + } + }, + "404": { + "description": "Refund does not exist in our records" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/v2/process_tracker/revenue_recovery_workflow/{revenue_recovery_id}": { "get": { "tags": [ diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rs index 14e1984a760..08c6dd52c39 100644 --- a/crates/api_models/src/events/refund.rs +++ b/crates/api_models/src/events/refund.rs @@ -59,6 +59,13 @@ impl ApiEventMetric for RefundsRetrieveRequest { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for refunds::RefundsRetrieveRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + None + } +} + #[cfg(feature = "v1")] impl ApiEventMetric for RefundUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index e8fcf39ca4e..775e0dfeef7 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -105,11 +105,19 @@ pub struct RefundsCreateRequest { pub metadata: Option<pii::SecretSerdeValue>, } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +#[derive(Default, Debug, Clone, Deserialize)] +pub struct RefundsRetrieveBody { + pub force_sync: Option<bool>, +} + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] 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. @@ -128,6 +136,22 @@ pub struct RefundsRetrieveRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +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. + #[schema( + max_length = 30, + min_length = 30, + example = "ref_mbabizu24mvu3mela5njyhpit4" + )] + pub refund_id: common_utils::id_type::GlobalRefundId, + + /// `force_sync` with the connector to get refund details + /// (defaults to false) + pub force_sync: Option<bool>, +} + #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundUpdateRequest { diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index e197bc3c211..927965a5338 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -757,6 +757,24 @@ impl RefundUpdate { processor_refund_data: connector_refund_id.extract_hashed_data(), } } + + pub fn build_error_update_for_refund_failure( + refund_status: Option<storage_enums::RefundStatus>, + refund_error_message: Option<String>, + refund_error_code: Option<String>, + storage_scheme: &storage_enums::MerchantStorageScheme, + ) -> Self { + Self::ErrorUpdate { + refund_status, + refund_error_message, + refund_error_code, + updated_by: storage_scheme.to_string(), + connector_refund_id: None, + processor_refund_data: None, + unified_code: None, + unified_message: None, + } + } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index dea3d5f7128..3cb9cf766d6 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -763,6 +763,10 @@ impl PaymentIntent { }) .transpose() } + + pub fn get_currency(&self) -> storage_enums::Currency { + self.amount_details.currency + } } #[cfg(feature = "v1")] diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index b7f88345484..bb48871190e 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -148,6 +148,7 @@ Never share your secret api keys. Keep them guarded and secure. //Routes for refunds routes::refunds::refunds_create, + routes::refunds::refunds_retrieve, // Routes for Revenue Recovery flow under Process Tracker routes::revenue_recovery::revenue_recovery_pt_retrieve_api diff --git a/crates/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs index 0ff0891ee54..5c55de2d177 100644 --- a/crates/openapi/src/routes/refunds.rs +++ b/crates/openapi/src/routes/refunds.rs @@ -64,6 +64,7 @@ pub async fn refunds_create() {} operation_id = "Retrieve a Refund", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub async fn refunds_retrieve() {} /// Refunds - Retrieve (POST) @@ -212,3 +213,23 @@ pub async fn refunds_filter_list() {} )] #[cfg(feature = "v2")] pub async fn refunds_create() {} + +/// Refunds - Retrieve +/// +/// Retrieves a Refund. This may be used to get the status of a previously initiated refund +#[utoipa::path( + get, + path = "/v2/refunds/{id}", + params( + ("id" = String, Path, description = "The identifier for refund") + ), + responses( + (status = 200, description = "Refund retrieved", body = RefundResponse), + (status = 404, description = "Refund does not exist in our records") + ), + tag = "Refunds", + operation_id = "Retrieve a Refund", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn refunds_retrieve() {} diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs index 89315006dc6..b6ccfe8376b 100644 --- a/crates/router/src/core/refunds_v2.rs +++ b/crates/router/src/core/refunds_v2.rs @@ -1,10 +1,17 @@ -use std::str::FromStr; +use std::{fmt::Debug, str::FromStr}; use api_models::{enums::Connector, refunds::RefundErrorDetails}; use common_utils::{id_type, types as common_utils_types}; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData}; -use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; +use hyperswitch_domain_models::{ + router_data::{ErrorResponse, RouterData}, + router_data_v2::RefundFlowData, +}; +use hyperswitch_interfaces::{ + api::{Connector as ConnectorTrait, ConnectorIntegration}, + connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2}, + integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}, +}; use router_env::{instrument, tracing}; use crate::{ @@ -202,20 +209,27 @@ pub async fn trigger_refund_to_gateway( Ok(response) } -async fn call_connector_service( +async fn call_connector_service<F>( state: &SessionState, connector: &api::ConnectorData, add_access_token_result: types::AddAccessTokenResult, - router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>, ) -> Result< - RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + RouterData<F, types::RefundsData, types::RefundsResponseData>, error_stack::Report<errors::ConnectorError>, -> { +> +where + F: Debug + Clone + 'static, + dyn ConnectorTrait + Sync: + ConnectorIntegration<F, types::RefundsData, types::RefundsResponseData>, + dyn ConnectorV2 + Sync: + ConnectorIntegrationV2<F, RefundFlowData, types::RefundsData, types::RefundsResponseData>, +{ if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< - api::Execute, + F, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); @@ -382,9 +396,12 @@ pub fn get_refund_update_for_refund_response_data( } } -pub fn perform_integrity_check( - mut router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, -) -> RouterData<api::Execute, types::RefundsData, types::RefundsResponseData> { +pub fn perform_integrity_check<F>( + mut router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>, +) -> RouterData<F, types::RefundsData, types::RefundsResponseData> +where + F: Debug + Clone + 'static, +{ // Initiating Integrity check let integrity_result = check_refund_integrity(&router_data.request, &router_data.response); router_data.integrity_check = integrity_result; @@ -447,6 +464,276 @@ where request.check_integrity(request, connector_refund_id.to_owned()) } +// ********************************************** REFUND SYNC ********************************************** + +#[instrument(skip_all)] +pub async fn refund_retrieve_core_with_refund_id( + state: SessionState, + merchant_context: domain::MerchantContext, + profile: domain::Profile, + request: refunds::RefundsRetrieveRequest, +) -> errors::RouterResponse<refunds::RefundResponse> { + let refund_id = request.refund_id.clone(); + let db = &*state.store; + let profile_id = profile.get_id().to_owned(); + let refund = db + .find_refund_by_id( + &refund_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; + + let response = Box::pin(refund_retrieve_core( + state.clone(), + merchant_context, + Some(profile_id), + request, + refund, + )) + .await?; + + api::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json) +} + +#[instrument(skip_all)] +pub async fn refund_retrieve_core( + state: SessionState, + merchant_context: domain::MerchantContext, + profile_id: Option<id_type::ProfileId>, + request: refunds::RefundsRetrieveRequest, + refund: storage::Refund, +) -> errors::RouterResult<storage::Refund> { + let db = &*state.store; + + let key_manager_state = &(&state).into(); + core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?; + let payment_id = &refund.payment_id; + let payment_intent = db + .find_payment_intent_by_id( + key_manager_state, + payment_id, + merchant_context.get_merchant_key_store(), + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + let active_attempt_id = payment_intent + .active_attempt_id + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Active attempt id not found")?; + + let payment_attempt = db + .find_payment_attempt_by_id( + key_manager_state, + merchant_context.get_merchant_key_store(), + &active_attempt_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + + let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = + (refund.unified_code.clone(), refund.unified_message.clone()) + { + helpers::get_unified_translation( + &state, + unified_code, + unified_message.clone(), + state.locale.to_string(), + ) + .await + .or(Some(unified_message)) + } else { + refund.unified_message + }; + + let refund = storage::Refund { + unified_message: unified_translated_message, + ..refund + }; + + let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { + Box::pin(sync_refund_with_gateway( + &state, + &merchant_context, + &payment_attempt, + &payment_intent, + &refund, + )) + .await + } else { + Ok(refund) + }?; + Ok(response) +} + +fn should_call_refund(refund: &diesel_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, + diesel_models::enums::RefundStatus::Failure + | diesel_models::enums::RefundStatus::Success + ); + + predicate1 && predicate2 +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +pub async fn sync_refund_with_gateway( + state: &SessionState, + merchant_context: &domain::MerchantContext, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, + refund: &storage::Refund, +) -> errors::RouterResult<storage::Refund> { + let db = &*state.store; + + let connector_id = refund.connector.to_string(); + let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_id, + api::GetToken::Connector, + payment_attempt.merchant_connector_id.clone(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get the connector")?; + + let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?; + + let mca = db + .find_merchant_connector_account_by_id( + &state.into(), + &mca_id, + merchant_context.get_merchant_key_store(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant connector account")?; + + let connector_enum = mca.connector_name; + + let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( + state, + connector_enum, + merchant_context, + payment_intent, + payment_attempt, + refund, + &mca, + ) + .await?; + + let add_access_token_result = + access_token::add_access_token(state, &connector, merchant_context, &router_data, None) + .await?; + + logger::debug!(refund_retrieve_router_data=?router_data); + + access_token::update_router_data_with_access_token_result( + &add_access_token_result, + &mut router_data, + &payments::CallConnectorAction::Trigger, + ); + + let connector_response = + call_connector_service(state, &connector, add_access_token_result, router_data) + .await + .to_refund_failed_response()?; + + let connector_response = perform_integrity_check(connector_response); + + let refund_update = + build_refund_update_for_rsync(&connector, merchant_context, connector_response); + + let response = state + .store + .update_refund( + refund.to_owned(), + refund_update, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) + .attach_printable_lazy(|| { + format!( + "Unable to update refund with refund_id: {}", + refund.id.get_string_repr() + ) + })?; + + // Implement outgoing webhook here + Ok(response) +} + +pub fn build_refund_update_for_rsync( + connector: &api::ConnectorData, + merchant_context: &domain::MerchantContext, + router_data_response: RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, +) -> storage::RefundUpdate { + let merchant_account = merchant_context.get_merchant_account(); + let storage_scheme = &merchant_context.get_merchant_account().storage_scheme; + + match router_data_response.response { + Err(error_message) => { + let refund_status = match error_message.status_code { + // marking failure for 2xx because this is genuine refund failure + 200..=299 => Some(enums::RefundStatus::Failure), + _ => None, + }; + let refund_error_message = error_message.reason.or(Some(error_message.message)); + let refund_error_code = Some(error_message.code); + + storage::RefundUpdate::build_error_update_for_refund_failure( + refund_status, + refund_error_message, + refund_error_code, + storage_scheme, + ) + } + Ok(response) => match router_data_response.integrity_check.clone() { + Err(err) => { + metrics::INTEGRITY_CHECK_FAILED.add( + 1, + router_env::metric_attributes!( + ("connector", connector.connector_name.to_string()), + ("merchant_id", merchant_account.get_id().clone()), + ), + ); + + let connector_refund_id = err + .connector_transaction_id + .map(common_utils_types::ConnectorTransactionId::from); + + storage::RefundUpdate::build_error_update_for_integrity_check_failure( + err.field_names, + connector_refund_id, + storage_scheme, + ) + } + Ok(()) => { + let connector_refund_id = + common_utils_types::ConnectorTransactionId::from(response.connector_refund_id); + + storage::RefundUpdate::build_refund_update( + connector_refund_id, + response.refund_status, + storage_scheme, + ) + } + }, + } +} + // ********************************************** VALIDATIONS ********************************************** #[instrument(skip_all)] diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index e123b792e75..d8b01bfd23e 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -252,7 +252,7 @@ pub async fn construct_refund_router_data<'a, F>( let status = payment_attempt.status; let payment_amount = payment_attempt.get_total_amount(); - let currency = payment_intent.amount_details.currency; + let currency = payment_intent.get_currency(); let payment_method_type = payment_attempt.payment_method_type; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9dc67be1d2d..68c88af3fd4 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1170,7 +1170,9 @@ impl Refunds { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/refunds").app_data(web::Data::new(state)); - route = route.service(web::resource("").route(web::post().to(refunds::refunds_create))); + route = route + .service(web::resource("").route(web::post().to(refunds::refunds_create))) + .service(web::resource("/{id}").route(web::get().to(refunds::refunds_retrieve))); route } diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index a7a4e5dddfb..65ea8720f99 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -168,6 +168,56 @@ pub async fn refunds_retrieve( .await } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[instrument(skip_all, fields(flow))] +pub async fn refunds_retrieve( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<common_utils::id_type::GlobalRefundId>, + 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, + }; + let flow = match query_params.force_sync { + Some(true) => Flow::RefundsRetrieveForceSync, + _ => Flow::RefundsRetrieve, + }; + + tracing::Span::current().record("flow", flow.to_string()); + + Box::pin(api::server_wrap( + flow, + state, + &req, + refund_request, + |state, auth: auth::AuthenticationData, refund_request, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + refund_retrieve_core_with_refund_id( + state, + merchant_context, + auth.profile, + refund_request, + ) + }, + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::ProfileRefundRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] /// Refunds - Retrieve (POST) /// diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index ff1f192fd45..8beaf7010f9 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -3,7 +3,8 @@ pub use api_models::refunds::RefundRequest; #[cfg(all(feature = "v2", feature = "refunds_v2"))] pub use api_models::refunds::RefundsCreateRequest; pub use api_models::refunds::{ - RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveRequest, + RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveBody, + RefundsRetrieveRequest, }; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync};
2025-04-17T07:30:53Z
## Description <!-- Describe your changes in detail --> This PR introduces support for Refunds Retrieve flow and Refunds Sync flow (Rsync) in V2 apis. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Upon merging this PR, users can be able to fetch a particular refund. Whether to check its status or fetch it from the gateway using force_sync query parameter. #
31e109a9a1367ef53786c146604b31fca69b15ef
- Create Payment Intent API call ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'api-key: dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'Authorization: api-key=dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"automatic", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` - Response from the above call ``` { "id":"12345_pay_019642a2b1bb7653ae08d3a9c5559177", "status":"requires_payment_method", "amount_details":{ "order_amount":100, "currency":"USD", "shipping_cost":null, "order_tax_amount":null, "external_tax_calculation":"skip", "surcharge_calculation":"skip", "surcharge_amount":null, "tax_on_surcharge":null }, "client_secret":"cs_019642a2b25a7301962eaf25dbdb22fd", "profile_id":"pro_OIQz3QuZDrhyUteOS41r", "merchant_reference_id":null, "routing_algorithm_id":null, "capture_method":"automatic", "authentication_type":"no_three_ds", "billing":{ "address":{ "city":null, "country":null, "line1":null, "line2":null, "line3":null, "zip":null, "state":null, "first_name":"John", "last_name":"Dough" }, "phone":null, "email":"[email protected]" }, "shipping":{ "address":{ "city":"Karwar", "country":null, "line1":null, "line2":null, "line3":null, "zip":"581301", "state":"Karnataka", "first_name":"John", "last_name":"Dough" }, "phone":null, "email":"[email protected]" }, "customer_id":null, "customer_present":"present", "description":null, "return_url":null, "setup_future_usage":"on_session", "apply_mit_exemption":"Skip", "statement_descriptor":null, "order_details":null, "allowed_payment_method_types":null, "metadata":null, "connector_metadata":null, "feature_metadata":null, "payment_link_enabled":"Skip", "payment_link_config":null, "request_incremental_authorization":"default", "expires_on":"2025-04-17T07:39:40.883Z", "frm_metadata":null, "request_external_three_ds_authentication":"Skip" } ``` - Confirm Intent API Call ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_019642a2b1bb7653ae08d3a9c5559177/confirm-intent' \ --header 'x-client-secret: cs_019642a2b25a7301962eaf25dbdb22fd' \ --header 'x-profile-id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'Content-Type: application/json' \ --header 'Authorization: publishable-key=pk_dev_ed28381f289249908a9fc946f11bf871,client-secret=cs_01963eaad7087700a02f86c215139747' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "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": "1x.x.x.31" } }' ``` - Response from the above call ``` { "id":"12345_pay_019642a2b1bb7653ae08d3a9c5559177", "status":"succeeded", "amount":{ "order_amount":100, "currency":"USD", "shipping_cost":null, "order_tax_amount":null, "external_tax_calculation":"skip", "surcharge_calculation":"skip", "surcharge_amount":null, "tax_on_surcharge":null, "net_amount":100, "amount_to_capture":null, "amount_capturable":0, "amount_captured":100 }, "customer_id":null, "connector":"stripe", "created":"2025-04-17T07:24:40.884Z", "payment_method_data":{ "billing":null }, "payment_method_type":"card", "payment_method_subtype":"credit", "connector_transaction_id":"pi_3REmpOD5R7gDAGff0MLPnmeN", "connector_reference_id":null, "merchant_connector_id":"mca_sank3uwIE62b8Fzr90a6", "browser_info":null, "error":null, "shipping":null, "billing":null, "attempts":null, "connector_token_details":{ "token":"pm_1REmpOD5R7gDAGffAT3f1rIN", "connector_token_request_reference_id":"Ow8Jd6RrV0u6t2qyST" }, "payment_method_id":null, "next_action":null, "return_url":"https://google.com/success", "authentication_type":"no_three_ds", "authentication_type_applied":"no_three_ds" } ``` - Refunds Create API call ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' \ --data '{ "payment_id":"12345_pay_019642a2b1bb7653ae08d3a9c5559177", "merchant_reference_id":"1744874778", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ``` { "id": "12345_ref_019642a487767f20bb8fa4a34d70da4a", "payment_id": "12345_pay_019642a2b1bb7653ae08d3a9c5559177", "merchant_reference_id": "1744874801", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-17T07:26:41.030Z", "updated_at": "2025-04-17T07:26:42.057Z", "connector": "stripe", "profile_id": "pro_OIQz3QuZDrhyUteOS41r", "merchant_connector_id": "mca_sank3uwIE62b8Fzr90a6", "connector_refund_reference_id": null } ``` - Refunds Retrieve API call ``` curl --location 'http://localhost:8080/v2/refunds/12345_ref_019642a487767f20bb8fa4a34d70da4a' \ --header 'x-profile-id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'api-key: dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' ``` - Response from the above call ``` { "id": "12345_ref_019642a487767f20bb8fa4a34d70da4a", "payment_id": "12345_pay_019642a2b1bb7653ae08d3a9c5559177", "merchant_reference_id": "1744874801", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-17T07:26:41.030Z", "updated_at": "2025-04-17T07:26:42.057Z", "connector": "stripe", "profile_id": "pro_OIQz3QuZDrhyUteOS41r", "merchant_connector_id": "mca_sank3uwIE62b8Fzr90a6", "connector_refund_reference_id": null } ``` - Refunds Retrieve api call with `force_sync=True` in query ``` curl --location 'http://localhost:8080/v2/refunds/12345_ref_019642a487767f20bb8fa4a34d70da4a?force_sync=true' \ --header 'x-profile-id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'api-key: dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' \ --data '' ``` - Response from the above call ``` { "id": "12345_ref_019642a487767f20bb8fa4a34d70da4a", "payment_id": "12345_pay_019642a2b1bb7653ae08d3a9c5559177", "merchant_reference_id": "1744874801", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-17T07:26:41.030Z", "updated_at": "2025-04-17T08:38:46.639Z", "connector": "stripe", "profile_id": "pro_OIQz3QuZDrhyUteOS41r", "merchant_connector_id": "mca_sank3uwIE62b8Fzr90a6", "connector_refund_reference_id": null } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/events/refund.rs", "crates/api_models/src/refunds.rs", "crates/diesel_models/src/refund.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/openapi/src/openapi_v2.rs", "crates/openapi/src/routes/refunds.rs", "crates/router/src/core/refunds_v2.rs", "crates/router/src/core/utils.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/refunds.rs", "crates/router/src/types/api/refunds.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7833
Bug: [BUG (CYPRESS)] Hard coded card expiry resulting in few tests to fail updating card expiry resulted in unintended after effects for specific connectors like adyen where it expects the user to pass a specific card expiry year (`30` instead of `55` or any other number). we cannot hard code connector names in spec files to exclude them from getting updated. neither we can go ahead and pull in another set of connector configs for this. so, i feel, it is better to just restrict that field from getting updated.
2025-04-17T06:20:59Z
## Description <!-- Describe your changes in detail --> the reason behind this pr is that there are a few connectors like adyen that expects the user to pass specific card expiry year and having it hard coded like we had until now results in unintended issues resulting the tests to fail. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> updating card expiry resulted in unintended after effects for specific connectors like adyen where it expects the user to pass a specific card expiry year. we cannot hard code connector names in spec files. neither we can go ahead and pull in another set of connector configs for this. so, it is more viable to remove the entire field from getting update since updating one field should be more than enough. closes https://github.com/juspay/hyperswitch/issues/7833 #
82bc46166b6157c43116e97a4b9bda8ecfd6285c
ran test against adyen since it was the one threw this error. not sure about other connectors but yeah, this change should fix them as well: <img width="524" alt="image" src="https://github.com/user-attachments/assets/3a9cf73f-0e60-4e0a-9e29-a2af8a63db3f" /> <img width="952" alt="image" src="https://github.com/user-attachments/assets/283eaf66-9233-4a20-83e1-e4eb808110fb" /> (failure is from ideal bank redirect redirection)
[]
juspay/hyperswitch
juspay__hyperswitch-7826
Bug: [CI]: remove private keys from configs
diff --git a/config/development.toml b/config/development.toml index 951cb44bd63..3a041db3574 100644 --- a/config/development.toml +++ b/config/development.toml @@ -106,35 +106,7 @@ 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----- -""" +vault_private_key = "" tunnel_private_key = "" [connectors.supported]
2025-04-16T07:00:23Z
This PR removes the `vault_private_key` from the configs.
9d1e0985a3e8df1e346005c1494c7cd44a5bd17f
[ "config/development.toml" ]
juspay/hyperswitch
juspay__hyperswitch-7813
Bug: [BUG(GlobalPay)] 5xx when making a failure payment ``` { "id": "TRN_OCPelRWxFohVEl0AuYglPyqG3fQ9r6_ca0584bb55bf", "time_created": "2025-04-14T14:54:57.880Z", "type": "SALE", "status": "DECLINED", "channel": "CNP", "capture_mode": "AUTO", "amount": "", "currency": "", "country": "DE", "merchant_id": "MER_c4c0df11039c48a9b63701adeaa296c3", "merchant_name": "Sandbox_merchant_2", "account_id": "TRA_6716058969854a48b33347043ff8225f", "account_name": "Transaction_Processing", "reference": "93459c78-f3f9-427c-84df-ca0584bb55bf", "payment_method": { "result": "108", "message": "Using test system. Please use pre-approved test cards ONLY", "entry_mode": "ECOM", "authentication": { "cavv_result": "" }, "card": { "brand": "VISA", "masked_number_last4": "XXXXXXXXXXXXXX0091", "authcode": "", "brand_reference": "", "brand_time_created": "", "cvv_result": "", "avs_address_result": "", "avs_postal_code_result": "", "avs_action": "", "provider": { "result": "108" } } }, "batch_id": "", "action": { "id": "ACT_OCPelRWxFohVEl0AuYglPyqG3fQ9r6", "type": "AUTHORIZE", "time_created": "2025-04-14T14:54:57.880Z", "result_code": "DECLINED", "app_id": "U1lRHKomEn7DN907RCDPxVhyMfiMLcfy", "app_name": "dev_portal_demo" } } ``` connector sends above response in case of failure (card decline). we get an empty currency. this results in deserialization failure and it is not intended.
diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs index f0f7851a419..11bd9e1a047 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs @@ -4,6 +4,7 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use super::requests; +use crate::utils::deserialize_optional_currency; #[derive(Debug, Serialize, Deserialize)] pub struct GlobalpayPaymentsResponse { @@ -31,6 +32,7 @@ pub struct GlobalpayPaymentsResponse { /// The country in ISO-3166-1(alpha-2 code) format. pub country: Option<String>, /// The currency of the amount in ISO-4217(alpha-3) + #[serde(deserialize_with = "deserialize_optional_currency")] pub currency: Option<Currency>, /// Information relating to a currency conversion. pub currency_conversion: Option<requests::CurrencyConversion>, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index ef5559d5453..60cb878d9a3 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -6073,3 +6073,21 @@ pub fn normalize_string(value: String) -> Result<String, regex::Error> { let normalized = regex.replace_all(&lowercase_value, "").to_string(); Ok(normalized) } + +/// Custom deserializer for Option<Currency> that treats empty strings as None +pub fn deserialize_optional_currency<'de, D>( + deserializer: D, +) -> Result<Option<enums::Currency>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let string_data: Option<String> = Option::deserialize(deserializer)?; + match string_data { + Some(ref value) if !value.is_empty() => value + .clone() + .parse_enum("Currency") + .map(Some) + .map_err(|_| serde::de::Error::custom(format!("Invalid currency code: {}", value))), + _ => Ok(None), + } +}
2025-04-15T07:59:49Z
## Description <!-- Describe your changes in detail --> This PR fixes an edge case with GlobalPay where, upon payment decline, we get a deserialization error and that is because `currency` field is not expected to be empty but rather a valid `Currency` enum. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes https://github.com/juspay/hyperswitch/issues/7813 #
e8e0b5df0e2d8e5d24fb8c1e98ce5b1049cc2f66
cards: ```txt // successful cards "card_number": "4012001038488884", "card_number": "4222000006285344", "card_number": "4012001037167778", "card_number": "4222000005218627", "card_number": "4222000009719489", // failure cards "card_number": "4242420000000091", "card_number": "5100000000000131", ``` create a payment: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5WtyfFxKHentO9ERR1HP8qrlIPzPP5s1Khs2G2q7mZBl1zJDOUFC3ZNzPcQtfynW' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242420000000091", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "101" } }, "billing": { "address": { "country": "US" } } }' ``` ```json { "payment_id": "pay_9iWUNJmnm8Le4l8iZCV9", "merchant_id": "postman_merchant_GHAction_95a905d4-93fe-42b4-b125-c1ddafa26313", "status": "failed", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "globalpay", "client_secret": "pay_9iWUNJmnm8Le4l8iZCV9_secret_RyifkSKcDrOFEEqC0OZ7", "created": "2025-04-15T09:21:39.674Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0091", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": null, "country": "US", "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": null, "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "111", "error_message": "(111)[ test system ] Strong Customer Authentication Required", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1744708899, "expires": 1744712499, "secret": "epk_24e7b6b84ca647aaa39a01fbdf5c0f42" }, "manual_retry_allowed": true, "connector_transaction_id": "TRN_uRk00jWtySUhGnJD4e7mZhEQQwZ6vF_Le4l8iZCV9_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_I2x5oXH0EQeuMaAZSe6G", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NN71g0D5WXMeggXKXhBM", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-15T09:36:39.674Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-15T09:21:41.821Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": "111", "issuer_error_message": "(111)[ test system ] Strong Customer Authentication Required" } ``` payment now fails with valid error message when `failure` cards are used. previously, we would get a 5xx: ``` {"error":{"type":"api","message":"Something went wrong","code":"HE_00"}} ├╴at crates/router/src/services/api.rs:806:14 │ ├─▶ {"error":{"type":"server_not_available","code":"HE_00","message":"Something went wrong"}} │ ╰╴at crates/router/src/core/errors/utils.rs:281:17 │ ├─▶ Failed to deserialize connector response │ ╰╴at crates/hyperswitch_connectors/src/connectors/globalpay.rs:757:14 │ ├─▶ Failed to parse struct: Globalpay PaymentsResponse │ ├╴at /router/crates/common_utils/src/ext_traits.rs:175:14 │ ╰╴Unable to parse hyperswitch_connectors::connectors::globalpay::response::GlobalpayPaymentsResponse from bytes b"{\"id\":\"TRN_dsWF5Tk8k8m1ylUC4Fz3319DPwyUt0_mCSfvURrUj_1\",\"time_created\":\"2025-04-14T14:43:41.794Z\",\"type\":\"SALE\",\"status\":\"DECLINED\",\"channel\":\"CNP\",\"capture_mode\":\"AUTO\",\"amount\":\"\",\"currency\":\"\",\"country\":\"US\",\"merchant_id\":\"MER_7e3e2c7df34f42819b3edee31022ee3f\",\"merchant_name\":\"Sandbox_merchant_3\",\"account_id\":\"TRA_c9967ad7d8ec4b46b6dd44a61cde9a91\",\"account_name\":\"transaction_processing\",\"reference\":\"pay_gO7eiUCttdmCSfvURrUj_1\",\"payment_method\":{\"result\":\"111\",\"message\":\"(111)[ test system ] Strong Customer Authentication Required\",\"entry_mode\":\"ECOM\",\"authentication\":{\"cavv_result\":\"\"},\"card\":{\"funding\":\"CREDIT\",\"brand\":\"MASTERCARD\",\"masked_number_last4\":\"XXXXXXXXXXXX0131\",\"authcode\":\"\",\"brand_reference\":\"YWLv8HtAwSh6aG8F\",\"brand_time_created\":\"\",\"tag_response\":\"\",\"cvv_result\":\"MATCHED\",\"avs_address_result\":\"MATCHED\",\"avs_postal_code_result\":\"MATCHED\",\"avs_action\":\"\",\"provider\":{\"result\":\"111\",\"cvv_result\":\"M\",\"avs_address_result\":\"M\",\"avs_postal_code_result\":\"M\"}}},\"risk_assessment\":[{\"mode\":\"ACTIVE\",\"result\":\"ACCEPTED\",\"rules\":[{\"reference\":\"0c93a6c9-7649-4822-b5ea-1efa356337fd\",\"description\":\"Cardholder Name Rule\",\"mode\":\"ACTIVE\",\"result\":\"ACCEPTED\"},{\"reference\":\"a539d51a-abc1-4fff-a38e-b34e00ad0cc3\",\"description\":\"CardNumber block\",\"mode\":\"ACTIVE\",\"result\":\"ACCEPTED\"},{\"reference\":\"d023a19e-6985-4fda-bb9b-5d4e0dedbb1e\",\"description\":\"Amount test\",\"mode\":\"ACTIVE\",\"result\":\"ACCEPTED\"}]}],\"currency_conversion\":{\"payer_amount\":\"\",\"payer_currency\":\"\",\"exchange_rate\":\"\",\"margin_rate_percentage\":\"\",\"commission_percentage\":\"\",\"exchange_rate_source\":\"\",\"exchange_rate_time_created\":\"\"},\"batch_id\":\"\",\"action\":{\"id\":\"ACT_dsWF5Tk8k8m1ylUC4Fz3319DPwyUt0\",\"type\":\"AUTHORIZE\",\"time_created\":\"2025-04-14T14:43:41.794Z\",\"result_code\":\"DECLINED\",\"app_id\":\"OXKlGGm6ecZLIqMyRgPHRfMxdUAiEcp8\",\"app_name\":\"rotate_again\"}}" │ ╰─▶ unknown variant ``, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLF`, `CLP`, `CNY`, `COP`, `CRC`, `CUC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STD`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL` at line 1 column 195 ╰╴at /router/crates/common_utils/src/ext_traits.rs:175:14 ```
[ "crates/hyperswitch_connectors/src/connectors/globalpay/response.rs", "crates/hyperswitch_connectors/src/utils.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7809
Bug: Deep health check failing because of OpenSearch When you don't have OpenSearch deployed for Global Search feature on dashboard , the `/health/ready` ( deep health check ) API which checks health of all the underlying queryable resources fails because if OpenSearch is not present the health check fails which should not be the case.
diff --git a/config/config.example.toml b/config/config.example.toml index 5f13eb1388d..b422892afc0 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -887,6 +887,7 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. [opensearch] host = "https://localhost:9200" +enabled = false [opensearch.auth] auth = "basic" diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index b2ee7f39741..5621a4940e8 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -242,6 +242,7 @@ region = "report_download_config_region" # Region of the buc [opensearch] host = "https://localhost:9200" +enabled = false [opensearch.auth] auth = "basic" diff --git a/config/development.toml b/config/development.toml index 89e35448af2..9bf2051b1d7 100644 --- a/config/development.toml +++ b/config/development.toml @@ -968,6 +968,7 @@ keys = "accept-language,user-agent,x-profile-id" [opensearch] host = "https://localhost:9200" +enabled = false [opensearch.auth] auth = "basic" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index cdf82f60936..59b36d73fe2 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -763,6 +763,7 @@ keys = "accept-language,user-agent,x-profile-id" [opensearch] host = "https://opensearch:9200" +enabled = false [opensearch.auth] auth = "basic" diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 726e38e5e16..20be0116d99 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -71,6 +71,8 @@ pub struct OpenSearchConfig { host: String, auth: OpenSearchAuth, indexes: OpenSearchIndexes, + #[serde(default)] + enabled: bool, } impl Default for OpenSearchConfig { @@ -91,12 +93,15 @@ impl Default for OpenSearchConfig { sessionizer_refunds: "sessionizer-refund-events".to_string(), sessionizer_disputes: "sessionizer-dispute-events".to_string(), }, + enabled: false, } } } #[derive(Debug, thiserror::Error)] pub enum OpenSearchError { + #[error("Opensearch is not enabled")] + NotEnabled, #[error("Opensearch connection error")] ConnectionError, #[error("Opensearch NON-200 response content: '{0}'")] @@ -176,6 +181,12 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError { "Access Forbidden error", None, )), + Self::NotEnabled => ApiErrorResponse::InternalServerError(ApiError::new( + "IR", + 8, + "Opensearch is not enabled", + None, + )), } } } @@ -408,15 +419,24 @@ impl OpenSearchAuth { } impl OpenSearchConfig { - pub async fn get_opensearch_client(&self) -> StorageResult<OpenSearchClient> { - Ok(OpenSearchClient::create(self) - .await - .map_err(|_| StorageError::InitializationError)?) + pub async fn get_opensearch_client(&self) -> StorageResult<Option<OpenSearchClient>> { + if !self.enabled { + return Ok(None); + } + Ok(Some( + OpenSearchClient::create(self) + .await + .change_context(StorageError::InitializationError)?, + )) } pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; + if !self.enabled { + return Ok(()); + } + when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch host must not be empty".into(), @@ -430,6 +450,7 @@ impl OpenSearchConfig { Ok(()) } } + #[derive(Debug, serde::Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum OpenSearchHealthStatus { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index cc242f86a5b..ca6b870f889 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -2245,7 +2245,10 @@ pub mod routes { .collect(); analytics::search::msearch_results( - &state.opensearch_client, + state + .opensearch_client + .as_ref() + .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?, req, search_params, SEARCH_INDEXES.to_vec(), @@ -2392,9 +2395,16 @@ pub mod routes { }) }) .collect(); - analytics::search::search_results(&state.opensearch_client, req, search_params) - .await - .map(ApplicationResponse::Json) + analytics::search::search_results( + state + .opensearch_client + .as_ref() + .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?, + req, + search_params, + ) + .await + .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index 2e5c2956013..c4892c94d6f 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -138,12 +138,15 @@ impl HealthCheckInterface for app::SessionState { async fn health_check_opensearch( &self, ) -> CustomResult<HealthState, errors::HealthCheckDBError> { - self.opensearch_client - .deep_health_check() - .await - .change_context(errors::HealthCheckDBError::OpensearchError)?; - - Ok(HealthState::Running) + if let Some(client) = self.opensearch_client.as_ref() { + client + .deep_health_check() + .await + .change_context(errors::HealthCheckDBError::OpensearchError)?; + Ok(HealthState::Running) + } else { + Ok(HealthState::NotApplicable) + } } async fn health_check_outgoing( diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f6386a9e2c5..4ecd093f250 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -118,7 +118,7 @@ pub struct SessionState { pub base_url: String, pub tenant: Tenant, #[cfg(feature = "olap")] - pub opensearch_client: Arc<OpenSearchClient>, + pub opensearch_client: Option<Arc<OpenSearchClient>>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, @@ -223,7 +223,7 @@ pub struct AppState { #[cfg(feature = "olap")] pub pools: HashMap<id_type::TenantId, AnalyticsProvider>, #[cfg(feature = "olap")] - pub opensearch_client: Arc<OpenSearchClient>, + pub opensearch_client: Option<Arc<OpenSearchClient>>, pub request_id: Option<RequestId>, pub file_storage_client: Arc<dyn FileStorageInterface>, pub encryption_client: Arc<dyn EncryptionManagementInterface>, @@ -342,12 +342,12 @@ impl AppState { #[allow(clippy::expect_used)] #[cfg(feature = "olap")] - let opensearch_client = Arc::new( - conf.opensearch - .get_opensearch_client() - .await - .expect("Failed to create opensearch client"), - ); + let opensearch_client = conf + .opensearch + .get_opensearch_client() + .await + .expect("Failed to initialize OpenSearch client.") + .map(Arc::new); #[allow(clippy::expect_used)] let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable) @@ -501,7 +501,7 @@ impl AppState { #[cfg(feature = "email")] email_client: Arc::clone(&self.email_client), #[cfg(feature = "olap")] - opensearch_client: Arc::clone(&self.opensearch_client), + opensearch_client: self.opensearch_client.clone(), grpc_client: Arc::clone(&self.grpc_client), theme_storage_client: self.theme_storage_client.clone(), locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()),
2025-04-14T15:46:42Z
## Description <!-- Describe your changes in detail --> Making `OpenSearchClient` optional based on the config for querying OpenSearch Server for dashboard based on the Deployment status of the same ( OpenSearch Server ). ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> When you don't have OpenSearch deployed for Global Search feature on dashboard , the `/health/ready` ( deep health check ) API which checks health of all the underlying queryable resources fails because OpenSearch is not present. To make it optional based on the deployment type needs changes and should be dependent on a config which should be given out on time of router deployment Currently if you don't have OpenSearch Deployment and have router running ```bash curl http://localhost:8080/health/ready -v * Host localhost:8080 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying [::1]:8080... * Connected to localhost (::1) port 8080 > GET /health/ready HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/8.7.1 > Accept: */* > * Request completely sent off < HTTP/1.1 500 Internal Server Error < content-length: 136 < access-control-expose-headers: x-request-id, content-type, via, strict-transport-security < via: HyperSwitch < x-request-id: 019634f7-a837-7d50-9a50-bb8e7651bd62 < content-type: application/json < vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers < strict-transport-security: max-age=31536000 < date: Mon, 14 Apr 2025 15:42:47 GMT < { [136 bytes data] 100 136 100 136 0 0 7613 0 --:--:-- --:--:-- --:--:-- 8000 * Connection #0 to host localhost left intact { "error": { "type": "api", "message": "Opensearch health check failed with error: Error while executing query in Opensearch", "code": "HE_00" } } ``` #
c58e93bfdba4cbd70d69e6d3947e0e1c68504e7e
```bash curl http://localhost:8080/health/ready -v | jq . * Host localhost:8080 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying [::1]:8080... * Connected to localhost (::1) port 8080 > GET /health/ready HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/8.7.1 > Accept: */* > * Request completely sent off < HTTP/1.1 200 OK < content-length: 90 < content-type: application/json < x-request-id: 01963e0a-e41d-7251-b20a-e9a0a6d1a67a < vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers < access-control-expose-headers: content-type, strict-transport-security, x-request-id, via < strict-transport-security: max-age=31536000 < via: HyperSwitch < date: Wed, 16 Apr 2025 10:00:23 GMT < { [90 bytes data] 100 90 100 90 0 0 236 0 --:--:-- --:--:-- --:--:-- 236 * Connection #0 to host localhost left intact { "database": true, "redis": true, "analytics": true, "opensearch": false, "outgoing_request": true } ```
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/analytics/src/opensearch.rs", "crates/router/src/analytics.rs", "crates/router/src/core/health_check.rs", "crates/router/src/routes/app.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7843
Bug: Fix Cypress v2 Core Flows Test Failures The Cypress tests for v2 failed due to the recent authentication changes introduced in [PR #7487](https://github.com/juspay/hyperswitch/pull/7487) and payment method config changes.
diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js index 228dfd2cfdd..a645ec5c555 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js @@ -54,10 +54,10 @@ const multiUseMandateData = { export const payment_methods_enabled = [ { - payment_method: "bank_debit", - payment_method_types: [ + payment_method_type: "bank_debit", + payment_method_subtypes: [ { - payment_method_type: "ach", + payment_method_subtype: "ach", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -68,7 +68,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "bacs", + payment_method_subtype: "bacs", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -79,7 +79,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "becs", + payment_method_subtype: "becs", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -90,7 +90,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "sepa", + payment_method_subtype: "sepa", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -103,10 +103,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "bank_redirect", - payment_method_types: [ + payment_method_type: "bank_redirect", + payment_method_subtypes: [ { - payment_method_type: "blik", + payment_method_subtype: "blik", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -117,7 +117,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "eps", + payment_method_subtype: "eps", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -128,7 +128,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "ideal", + payment_method_subtype: "ideal", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -139,7 +139,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "giropay", + payment_method_subtype: "giropay", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -150,7 +150,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "local_bank_redirect", + payment_method_subtype: "local_bank_redirect", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -161,7 +161,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "przelewy24", + payment_method_subtype: "przelewy24", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -172,7 +172,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "sofort", + payment_method_subtype: "sofort", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -185,10 +185,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "bank_transfer", - payment_method_types: [ + payment_method_type: "bank_transfer", + payment_method_subtypes: [ { - payment_method_type: "ach", + payment_method_subtype: "ach", payment_experience: "redirect_to_url", card_networks: null, accepted_currencies: null, @@ -199,7 +199,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "bacs", + payment_method_subtype: "bacs", payment_experience: "redirect_to_url", card_networks: null, accepted_currencies: null, @@ -210,14 +210,14 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "pix", + payment_method_subtype: "pix", minimum_amount: -1, maximum_amount: 68607706, recurring_enabled: false, installment_payment_enabled: true, }, { - payment_method_type: "sepa", + payment_method_subtype: "sepa", payment_experience: "redirect_to_url", card_networks: null, accepted_currencies: null, @@ -230,10 +230,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "card", - payment_method_types: [ + payment_method_type: "card", + payment_method_subtypes: [ { - payment_method_type: "credit", + payment_method_subtype: "credit", card_networks: [ "AmericanExpress", "Discover", @@ -251,7 +251,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "debit", + payment_method_subtype: "debit", card_networks: [ "AmericanExpress", "Discover", @@ -271,10 +271,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "card_redirect", - payment_method_types: [ + payment_method_type: "card_redirect", + payment_method_subtypes: [ { - payment_method_type: "card_redirect", + payment_method_subtype: "card_redirect", payment_experience: "redirect_to_url", card_networks: null, accepted_currencies: null, @@ -287,10 +287,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "real_time_payment", - payment_method_types: [ + payment_method_type: "real_time_payment", + payment_method_subtypes: [ { - payment_method_type: "duit_now", + payment_method_subtype: "duit_now", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -298,7 +298,7 @@ export const payment_methods_enabled = [ payment_experience: "redirect_to_url", }, { - payment_method_type: "fps", + payment_method_subtype: "fps", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -306,7 +306,7 @@ export const payment_methods_enabled = [ payment_experience: "redirect_to_url", }, { - payment_method_type: "prompt_pay", + payment_method_subtype: "prompt_pay", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -314,7 +314,7 @@ export const payment_methods_enabled = [ payment_experience: "redirect_to_url", }, { - payment_method_type: "viet_qr", + payment_method_subtype: "viet_qr", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -324,10 +324,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "upi", - payment_method_types: [ + payment_method_type: "upi", + payment_method_subtypes: [ { - payment_method_type: "upi_collect", + payment_method_subtype: "upi_collect", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -335,7 +335,7 @@ export const payment_methods_enabled = [ payment_experience: "redirect_to_url", }, { - payment_method_type: "upi_intent", + payment_method_subtype: "upi_intent", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index 33f8907ce3f..54e52495d67 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -55,7 +55,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, body: organizationCreateBody, failOnStatusCode: false, @@ -91,7 +91,7 @@ Cypress.Commands.add("organizationRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, failOnStatusCode: false, }).then((response) => { @@ -135,7 +135,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, body: organizationUpdateBody, failOnStatusCode: false, @@ -185,7 +185,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "X-Organization-Id": organization_id, }, body: merchantAccountCreateBody, @@ -230,7 +230,7 @@ Cypress.Commands.add("merchantAccountRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, failOnStatusCode: false, }).then((response) => { @@ -274,7 +274,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, body: merchantAccountUpdateBody, failOnStatusCode: false, @@ -310,7 +310,7 @@ Cypress.Commands.add( "businessProfileCreateCall", (businessProfileCreateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("apiKey"); + const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/profiles`; @@ -324,7 +324,8 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, + "x-merchant-id": merchant_id, ...customHeaders, }, body: businessProfileCreateBody, @@ -353,7 +354,7 @@ Cypress.Commands.add( ); Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("apiKey"); + const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); @@ -368,7 +369,7 @@ Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -395,7 +396,7 @@ Cypress.Commands.add( "businessProfileUpdateCall", (businessProfileUpdateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("apiKey"); + const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); @@ -410,7 +411,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: businessProfileUpdateBody, @@ -460,6 +461,7 @@ Cypress.Commands.add( const customHeaders = { "x-merchant-id": merchant_id, + "x-profile-id": profile_id, }; // Update request body @@ -501,7 +503,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: mcaCreateBody, @@ -536,10 +538,12 @@ Cypress.Commands.add("mcaRetrieveCall", (globalState) => { const connector_name = globalState.get("connectorId"); const merchant_connector_id = globalState.get("merchantConnectorId"); const merchant_id = globalState.get("merchantId"); + const profile_id = globalState.get("profileId"); const url = `${base_url}/v2/connector-accounts/${merchant_connector_id}`; const customHeaders = { "x-merchant-id": merchant_id, + "x-profile-id": profile_id, }; cy.request({ @@ -547,7 +551,7 @@ Cypress.Commands.add("mcaRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -607,7 +611,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: mcaUpdateBody, @@ -667,7 +671,7 @@ Cypress.Commands.add("apiKeyCreateCall", (apiKeyCreateBody, globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: apiKeyCreateBody, @@ -714,7 +718,7 @@ Cypress.Commands.add("apiKeyRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -764,7 +768,7 @@ Cypress.Commands.add("apiKeyUpdateCall", (apiKeyUpdateBody, globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: apiKeyUpdateBody, @@ -1172,7 +1176,7 @@ Cypress.Commands.add("merchantAccountsListCall", (globalState) => { method: "GET", url: url, headers: { - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "Content-Type": "application/json", }, failOnStatusCode: false, @@ -1214,7 +1218,7 @@ Cypress.Commands.add("businessProfilesListCall", (globalState) => { method: "GET", url: url, headers: { - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, }, @@ -1250,13 +1254,14 @@ Cypress.Commands.add("mcaListCall", (globalState, service_type) => { const customHeaders = { "x-merchant-id": merchant_id, + "x-profile-id": profile_id, }; cy.request({ method: "GET", url: url, headers: { - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, }, @@ -1318,7 +1323,7 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => { method: "GET", url: url, headers: { - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, },
2025-04-13T16:09:57Z
## Description <!-- Describe your changes in detail --> <details> <summary>Changes</summary> - Changed the Authorization in the `commands.js` because Authorization changes had been made recently. - Changed field names in `payment_methods_enabled` accordingly as accepted by v2 endpoints. </details> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The v2 Cypress Tests were failing due to the recent Authentication Changes in #7487. #
4f4e31db24652e72ce50745e9d64618c93c692bc
**_Before_** <img width="715" alt="image" src="https://github.com/user-attachments/assets/70f6ccfe-8094-47f0-b70f-34cb66cccc86" /> **_After_** <img width="714" alt="image" src="https://github.com/user-attachments/assets/3b1c6591-3667-468f-aa9d-01e8e01eb835" />
[ "cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js", "cypress-tests-v2/cypress/support/commands.js" ]
juspay/hyperswitch
juspay__hyperswitch-7906
Bug: Fix: One click docker setup We need a script for one click docker setup
diff --git a/README.md b/README.md index 21b5d4def23..3033263e578 100644 --- a/README.md +++ b/README.md @@ -69,15 +69,27 @@ Read more at [Hyperswitch docs](https://docs.hyperswitch.io/). ### 1. Local Setup -You can run Hyperswitch on your system using Docker compose after cloning this repository. -We recommend using Docker Desktop (Or Orbstack) for Windows and Mac OS. On Linux, you can install Docker Engine directly. +#### One-Click Setup (Recommended) + +You can run Hyperswitch on your system with a single command using our one-click setup script: + ```shell git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch cd hyperswitch -docker compose up -d -# This script verifies the setup and provides links to the individual components. -scripts/docker_output.sh +scripts/setup.sh ``` + +The above script will: +- Check for prerequisites (Docker Compose/Podman) +- Set up necessary configurations +- Let you select a deployment profile: + - **Standard**: Recommended - App server + Control Center + Web SDK. + - **Full**: Standard + Monitoring + Scheduler. + - **Standalone App Server**: Core services only (Hyperswitch server, PostgreSQL, Redis) +- Start the selected services +- Check service health +- Provide access information + The next step is to [configure a connector][configure-a-connector] with the Hyperswitch Control Center and [try a payment][try-a-payment]. Check out the [local setup guide][local-setup-guide] for more details on setting up the entire stack or component wise. diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 00000000000..c40c5365c90 --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,241 @@ +#! /usr/bin/env bash +set -euo pipefail + +# ANSI color codes for pretty output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +BLUE='\033[0;34m' +BOLD='\033[1m' +NC='\033[0m' # No Color + +# Alias for docker to use podman +alias docker=podman + +# Function to print colorful messages +echo_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +echo_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +echo_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +echo_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +show_banner() { + echo -e "${BLUE}${BOLD}" + echo "" + echo " # " + echo " # # # #### ##### ## # # " + echo " # # # # # # # # # # " + echo " # # # #### # # # # # " + echo " # # # # # ##### ###### # " + echo " # # # # # # # # # # " + echo " ##### #### #### # # # # " + echo "" + echo "" + echo " # # # # ##### ###### ##### #### # # # ##### #### # # " + echo " # # # # # # # # # # # # # # # # # # " + echo " # # # # # ##### # # #### # # # # # ###### " + echo " ####### # ##### # ##### # # ## # # # # # # " + echo " # # # # # # # # # ## ## # # # # # # " + echo " # # # # ###### # # #### # # # # #### # # " + echo "" + sleep 1 + echo -e "${NC}" + echo -e "🚀 ${BLUE}One-Click Docker Setup${NC} 🚀" + echo +} + +# Detect Docker Compose version +detect_docker_compose() { + # Check Docker or Podman + if command -v docker &> /dev/null; then + CONTAINER_ENGINE="docker" + echo_success "Docker is installed." + elif command -v podman &> /dev/null; then + CONTAINER_ENGINE="podman" + echo_success "Podman is installed." + else + echo_error "Neither Docker nor Podman is installed. Please install one of them to proceed." + echo_info "Visit https://docs.docker.com/get-docker/ or https://podman.io/docs/installation for installation instructions." + echo_info "After installation, re-run this script: scripts/setup.sh" + exit 1 + fi + + # Check Docker Compose or Podman Compose + if $CONTAINER_ENGINE compose version &> /dev/null; then + DOCKER_COMPOSE="$CONTAINER_ENGINE compose" + echo_success "Compose is installed for $CONTAINER_ENGINE." + else + echo_error "Compose is not installed for $CONTAINER_ENGINE. Please install $CONTAINER_ENGINE compose to proceed." + if [ "$CONTAINER_ENGINE" = "docker" ]; then + echo_info "Visit https://docs.docker.com/compose/install/ for installation instructions." + elif [ "$CONTAINER_ENGINE" = "podman" ]; then + echo_info "Visit https://podman-desktop.io/docs/compose/setting-up-compose for installation instructions." + fi + echo_info "After installation, re-run this script: scripts/setup.sh" + exit 1 + fi +} + +check_prerequisites() { + # Check curl + if ! command -v curl &> /dev/null; then + echo_error "curl is not installed. Please install curl to proceed." + exit 1 + fi + echo_success "curl is installed." + + # Check ports + required_ports=(8080 9000 9050 5432 6379 9060) + unavailable_ports=() + + for port in "${required_ports[@]}"; do + if command -v nc &> /dev/null; then + if nc -z localhost "$port" 2>/dev/null; then + unavailable_ports+=("$port") + fi + elif command -v lsof &> /dev/null; then + if lsof -i :"$port" &> /dev/null; then + unavailable_ports+=("$port") + fi + else + echo_warning "Neither nc nor lsof available to check ports. Skipping port check." + break + fi + done + + if [ ${#unavailable_ports[@]} -ne 0 ]; then + echo_warning "The following ports are already in use: ${unavailable_ports[*]}" + echo_warning "This might cause conflicts with Hyperswitch services." + read -p "Do you want to continue anyway? (y/n): " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + exit 1 + fi + else + echo_success "All required ports are available." + fi +} + +setup_config() { + if [ ! -f "config/docker_compose.toml" ]; then + echo_error "Configuration file 'config/docker_compose.toml' not found. Please ensure the file exists and is correctly configured." + exit 1 + fi +} + +select_profile() { + echo "" + echo "Select a setup option:" + echo -e "1) Standard Setup: ${BLUE}[Recommended]${NC} Ideal for quick trial. Services included: ${BLUE}App Server, Control Center, Unified Checkout, PostgreSQL and Redis${NC}" + echo -e "2) Full Stack Setup: Ideal for comprehensive end-to-end payment testing. Services included: ${BLUE}Everything in Standard, Monitoring and Scheduler${NC}" + echo -e "3) Standalone App Server: Ideal for API-first integration testing. Services included: ${BLUE}App server, PostgreSQL and Redis)${NC}" + echo "" + local profile_selected=false + while [ "$profile_selected" = false ]; do + read -p "Enter your choice (1-3): " profile_choice + profile_choice=${profile_choice:-1} + + case $profile_choice in + 1) + PROFILE="standard" + profile_selected=true + ;; + 2) + PROFILE="full" + profile_selected=true + ;; + 3) + PROFILE="standalone" + profile_selected=true + ;; + *) + echo_error "Invalid choice. Please enter 1, 2, or 3." + ;; + esac + done + + echo "Selected setup: $PROFILE" +} + +start_services() { + + case $PROFILE in + standalone) + $DOCKER_COMPOSE up -d pg redis-standalone migration_runner hyperswitch-server + ;; + standard) + $DOCKER_COMPOSE up -d + ;; + full) + $DOCKER_COMPOSE --profile scheduler --profile monitoring --profile olap up -d + ;; + esac +} + +check_services_health() { + # Wait for the hyperswitch-server to be healthy + MAX_RETRIES=30 + RETRY_INTERVAL=5 + RETRIES=0 + + while [ $RETRIES -lt $MAX_RETRIES ]; do + if curl --silent --head --request GET 'http://localhost:8080/health' | grep "200 OK" > /dev/null; then + echo_success "Hyperswitch server is healthy!" + print_access_info # Call print_access_info only when the server is healthy + return + fi + + RETRIES=$((RETRIES+1)) + if [ $RETRIES -eq $MAX_RETRIES ]; then + echo "" + echo_error "${RED}${BOLD}Hyperswitch server did not become healthy in the expected time." + echo -e "Check logs with: $DOCKER_COMPOSE logs hyperswitch-server, Or reach out to us on slack(https://hyperswitch-io.slack.com/) for help." + echo -e "The setup process will continue, but some services might not work correctly.${NC}" + echo "" + else + echo "Waiting for server to become healthy... ($RETRIES/$MAX_RETRIES)" + sleep $RETRY_INTERVAL + fi + done +} + +print_access_info() { + echo "" + echo -e "${GREEN}${BOLD}Setup complete! You can access Hyperswitch services at:${NC}" + echo "" + + if [ "$PROFILE" != "standalone" ]; then + echo -e " • ${GREEN}${BOLD}Control Center${NC}: ${BLUE}${BOLD}http://localhost:9000${NC}" + fi + + echo -e " • ${GREEN}${BOLD}App Server${NC}: ${BLUE}${BOLD}http://localhost:8080${NC}" + + if [ "$PROFILE" != "standalone" ]; then + echo -e " • ${GREEN}${BOLD}Unified Checkout${NC}: ${BLUE}${BOLD}http://localhost:9060${NC}" + fi + + if [ "$PROFILE" = "full" ]; then + echo -e " • ${GREEN}${BOLD}Monitoring (Grafana)${NC}: ${BLUE}${BOLD}http://localhost:3000${NC}" + fi + echo "" + echo_info "To stop all services, run: $DOCKER_COMPOSE down" +} + +# Main execution flow +show_banner +detect_docker_compose +check_prerequisites +setup_config +select_profile +start_services +check_services_health # This will call print_access_info if the server is healthy
2025-04-12T12:17:12Z
Implements a comprehensive bash script that simplifies the Hyperswitch Docker setup process with the following features: - Prerequisites checking for Docker and Docker Compose - Port availability validation - Multiple deployment profiles (Minimal, Standard, Full, Development) - Automatic configuration setup - Service health monitoring - Detailed documentation in README.md and docs/one_click_setup.md Resolves issue #7761 ## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
bbec7a41f7a088d6601195a2f4ce6d733924a443
Sharing SS from local: <img width="635" alt="Screenshot 2025-04-24 at 5 59 43 AM" src="https://github.com/user-attachments/assets/2450115e-bb2d-4bc4-91ee-c53be713f9e2" />
[ "README.md", "scripts/setup.sh" ]
juspay/hyperswitch
juspay__hyperswitch-7800
Bug: [ENHANCEMENT] add validation for return_url for Payment Links HyperSwitch should always validate the presence of return_url during payment link creation as it is a required field in payment link flows.
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index bdf7e9ec83f..e606291b8db 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -6338,16 +6338,19 @@ pub fn get_key_params_for_surcharge_details( } pub fn validate_payment_link_request( - confirm: Option<bool>, + request: &api::PaymentsRequest, ) -> Result<(), errors::ApiErrorResponse> { - if let Some(cnf) = confirm { - if !cnf { - return Ok(()); - } else { - return Err(errors::ApiErrorResponse::InvalidRequestData { - message: "cannot confirm a payment while creating a payment link".to_string(), - }); - } + #[cfg(feature = "v1")] + if request.confirm == Some(true) { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "cannot confirm a payment while creating a payment link".to_string(), + }); + } + + if request.return_url.is_none() { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "return_url must be sent while creating a payment link".to_string(), + }); } Ok(()) } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 801c6844f9b..f1b15be199e 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -979,7 +979,7 @@ impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentDat if let Some(payment_link) = &request.payment_link { if *payment_link { - helpers::validate_payment_link_request(request.confirm)?; + helpers::validate_payment_link_request(request)?; } };
2025-04-11T15:36:37Z
## Description This PR adds a validation for `return_url` when creating payment links. Return URL must be a required parameter as payment links is client side facing and needs to be redirected to an end URL post payment completion. ## Motivation and Context This PR fixes a bug in the payment links flow which allowed creating payment links without validating presence of `return_url`. This allows merchants to be careful of payment link integration. #
2123f63bc54030adf1d8f42f08240c71b03fc09c
<details> <summary>1. Create a payment link without return_url in the payments create request</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ddmeaxUlgRPHkcqtmZZm5nGMRhejMxXijYCnsp070Oqn2y4lrfUNBCb9UmedwgMt' \ --data-raw '{"customer_id":"cus_ttQVCva9zDC2q8jfJaiy","profile_id":"pro_510ieWUUX4pc0bUWmBW3","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":10,"currency":"EUR","payment_link":true,"capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"HK","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"}}' Response { "error": { "type": "invalid_request", "message": "return_url must be sent while creating a payment link", "code": "IR_06" } } </details> <details> <summary>2. Create a payment link with return_url in the payments create request</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ddmeaxUlgRPHkcqtmZZm5nGMRhejMxXijYCnsp070Oqn2y4lrfUNBCb9UmedwgMt' \ --data-raw '{"customer_id":"cus_ttQVCva9zDC2q8jfJaiy","profile_id":"pro_510ieWUUX4pc0bUWmBW3","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":10,"currency":"EUR","payment_link":true,"capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"HK","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com"}' Response {"payment_id":"pay_jqWIxxAzZ55ObDFPUi3u","merchant_id":"merchant_1744368926","status":"requires_payment_method","amount":10,"net_amount":10,"shipping_cost":null,"amount_capturable":10,"amount_received":null,"connector":null,"client_secret":"pay_jqWIxxAzZ55ObDFPUi3u_secret_R696m3FdANBfOlBHs7e3","created":"2025-04-11T15:32:20.593Z","currency":"EUR","customer_id":"cus_ttQVCva9zDC2q8jfJaiy","customer":{"id":"cus_ttQVCva9zDC2q8jfJaiy","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"HK","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_ttQVCva9zDC2q8jfJaiy","created_at":1744385540,"expires":1744389140,"secret":"epk_4687716462814249b8cad4ebb30c18a3"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1744368926/pay_jqWIxxAzZ55ObDFPUi3u?locale=en","secure_link":null,"payment_link_id":"plink_2tsEloeZ8SeUXyOQfRsu"},"profile_id":"pro_510ieWUUX4pc0bUWmBW3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-11T15:47:20.588Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-11T15:32:20.612Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details>
[ "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_create.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7794
Bug: [ENHANCEMENT] update payments API response This issue is around two specific fields in the payments API 1. Payments response -`error_code` and `error_message` HyperSwitch should not propagate the intermediary dummy error codes and error messages to the API response. Currently, `ErrorResponse` in connector integration mandates setting an error_code and error_message. But some connectors might not have this available during transaction failures. For this reason, current HyperSwitch integration uses NO_ERROR_CODE for `error_code` and NO_ERROR_MESSAGE for `error_message`. These are constant strings which are propagated from connector integration to core layer and later sent back in the response. It doesn't make sense to have these in the API response as HyperSwitch should not 'invent' new codes and messages. This should be removed from the API response in such cases. 2. Payments request - `return_url` HyperSwitch should always validate the presence of `return_url` during payment link creation as it is a required field in payment link flows.
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index f7167a607a2..7ce8ed6d710 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -892,11 +892,11 @@ impl<F> code: non_threeds_data .error_code .clone() - .unwrap_or_else(|| "NO_ERROR_CODE".to_string()), + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: non_threeds_data .error_desc .clone() - .unwrap_or_else(|| "NO_ERROR_MESSAGE".to_string()), + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: non_threeds_data.error_desc.clone(), status_code: item.http_code, attempt_status: None, @@ -941,11 +941,11 @@ impl<F> code: recurring_response .reason .clone() - .unwrap_or_else(|| "NO_ERROR_CODE".to_string()), + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: recurring_response .reason .clone() - .unwrap_or_else(|| "NO_ERROR_MESSAGE".to_string()), + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: recurring_response.reason.clone(), status_code: item.http_code, attempt_status: None, @@ -1480,19 +1480,17 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> }?; let capture_message_status = capture_status_codes(); let error_response = if status == enums::AttemptStatus::Failure { + let optional_message = capture_message_status + .get(status_code.as_str()) + .copied() + .map(String::from); Some(ErrorResponse { status_code: item.http_code, code: status_code.to_owned(), - message: capture_message_status - .get(status_code.as_str()) - .unwrap_or(&"NO_ERROR_MESSAGE") - .to_string(), - reason: Some( - capture_message_status - .get(status_code.as_str()) - .unwrap_or(&"NO_ERROR_REASON") - .to_string(), - ), + message: optional_message + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: optional_message, attempt_status: None, connector_transaction_id: Some(item.response.tran_id.clone()), network_advice_code: None, @@ -1596,19 +1594,18 @@ impl TryFrom<PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>> }?; let void_message_status = void_status_codes(); let error_response = if status == enums::AttemptStatus::VoidFailed { + let optional_message = void_message_status + .get(status_code.as_str()) + .copied() + .map(String::from); + Some(ErrorResponse { status_code: item.http_code, code: status_code.to_owned(), - message: void_message_status - .get(status_code.as_str()) - .unwrap_or(&"NO_ERROR_MESSAGE") - .to_string(), - reason: Some( - void_message_status - .get(status_code.as_str()) - .unwrap_or(&"NO_ERROR_REASON") - .to_string(), - ), + message: optional_message + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: optional_message, attempt_status: None, connector_transaction_id: Some(item.response.tran_id.clone()), network_advice_code: None, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 077a288c167..3001776cbfd 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2075,6 +2075,8 @@ where { use std::ops::Not; + use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}; + let payment_attempt = payment_data.get_payment_attempt().clone(); let payment_intent = payment_data.get_payment_intent().clone(); let payment_link_data = payment_data.get_payment_link_data(); @@ -2561,10 +2563,13 @@ where statement_descriptor_suffix: payment_intent.statement_descriptor_suffix, next_action: next_action_response, cancellation_reason: payment_attempt.cancellation_reason, - error_code: payment_attempt.error_code, + error_code: payment_attempt + .error_code + .filter(|code| code != NO_ERROR_CODE), error_message: payment_attempt .error_reason - .or(payment_attempt.error_message), + .or(payment_attempt.error_message) + .filter(|message| message != NO_ERROR_MESSAGE), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, payment_experience: payment_attempt.payment_experience,
2025-04-11T15:01:31Z
## Description This PR filters the `error_code` and `error_message` in Payments API response to ensure HyperSwitch does not send back any 'invented' codes or messages. This is achieved by filtering such error codes and error messages are not sent back in the API response. Details in ticket - https://github.com/juspay/hyperswitch/issues/7794 (point # 1) ## Motivation and Context This PR ensures HyperSwitch does not invent any new error codes or messages and send it back in the Payments API response. In case error codes and messages are not present, it will send back null in the response #
4f4e31db24652e72ce50745e9d64618c93c692bc
<details> <summary>1. Create card payment via Nexixpay (failed card txn)</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ddmeaxUlgRPHkcqtmZZm5nGMRhejMxXijYCnsp070Oqn2y4lrfUNBCb9UmedwgMt' \ --data-raw '{"amount":3000,"currency":"EUR","confirm":true,"profile_id":"pro_510ieWUUX4pc0bUWmBW3","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","connector":["nexixpay"],"email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_data":{"card":{"card_number":"4349940199997007","card_exp_month":"12","card_exp_year":"28","card_holder_name":"joseph Doe","card_cvc":"829"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":30,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"connector_metadata":{"noon":{"order_category":"pay"}},"session_expiry":60}' Response {"payment_id":"pay_CLMzDJcQecFlM3bTdeZQ","merchant_id":"merchant_1744368926","status":"requires_customer_action","amount":3000,"net_amount":3000,"shipping_cost":null,"amount_capturable":3000,"amount_received":null,"connector":"nexixpay","client_secret":"pay_CLMzDJcQecFlM3bTdeZQ_secret_WtxTUTQUXoYjF4Gt6f7a","created":"2025-04-11T14:28:21.682Z","currency":"EUR","customer_id":null,"customer":{"id":null,"name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"7007","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"434994","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"28","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":"token_KyWCvOf88BnnPydHsewF","shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":{"type":"redirect_to_url","redirect_to_url":"https://tame-bird-39.telebit.io/payments/redirect/pay_CLMzDJcQecFlM3bTdeZQ/merchant_1744368926/pay_CLMzDJcQecFlM3bTdeZQ_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":null,"connector_transaction_id":"pay_CLMzDJcQecFlM3bTdeZQ_1","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":{"order_category":"pay"},"braintree":null},"feature_metadata":null,"reference_id":"pay_CLMzDJcQecFlM3bTdeZQ_1","payment_link":null,"profile_id":"pro_510ieWUUX4pc0bUWmBW3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_d4eEG4Vgv2liRzTtsWKM","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-11T14:29:21.682Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":30,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-11T14:28:22.739Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} Open the link and complete the payment </details> <details> <summary>2. Retrieve the payment</summary> cURL curl --location --request GET 'http://localhost:8080/payments/pay_CLMzDJcQecFlM3bTdeZQ?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_ddmeaxUlgRPHkcqtmZZm5nGMRhejMxXijYCnsp070Oqn2y4lrfUNBCb9UmedwgMt' Response {"payment_id":"pay_CLMzDJcQecFlM3bTdeZQ","merchant_id":"merchant_1744368926","status":"failed","amount":3000,"net_amount":3000,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"nexixpay","client_secret":"pay_CLMzDJcQecFlM3bTdeZQ_secret_WtxTUTQUXoYjF4Gt6f7a","created":"2025-04-11T14:28:21.682Z","currency":"EUR","customer_id":null,"customer":{"id":null,"name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"7007","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"434994","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"28","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":"token_KyWCvOf88BnnPydHsewF","shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":"Declined","unified_code":"UE_9000","unified_message":"Something went wrong","payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":true,"connector_transaction_id":"pay_CLMzDJcQecFlM3bTdeZQ_1","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":{"order_category":"pay"},"braintree":null},"feature_metadata":null,"reference_id":"pay_CLMzDJcQecFlM3bTdeZQ_1","payment_link":null,"profile_id":"pro_510ieWUUX4pc0bUWmBW3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_d4eEG4Vgv2liRzTtsWKM","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-11T14:29:21.682Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":30,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-11T14:28:32.770Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} Things to verify 1. Error code must be null for this scenario 2. Error code in DB must be `No error code` <img width="413" alt="Screenshot 2025-04-11 at 9 52 43 PM" src="https://github.com/user-attachments/assets/f756f6e3-77f7-4e0a-9a78-c97f686b7b30" /> </details>
[ "crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs", "crates/router/src/core/payments/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7817
Bug: Hubspot api integration Closes issue https://github.com/juspay/hyperswitch-control-center-cloud/issues/28
diff --git a/Cargo.lock b/Cargo.lock index f0b8ce94980..d2ae0213703 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2936,6 +2936,7 @@ dependencies = [ "dyn-clone", "error-stack", "hex", + "http 0.2.12", "http-body-util", "hyper 0.14.30", "hyper-proxy", @@ -2945,6 +2946,8 @@ dependencies = [ "masking", "once_cell", "prost", + "quick-xml", + "reqwest 0.11.27", "router_env", "serde", "thiserror 1.0.63", @@ -2953,6 +2956,7 @@ dependencies = [ "tonic-build", "tonic-reflection", "tonic-types", + "url", "vaultrs", ] @@ -6531,7 +6535,6 @@ dependencies = [ "openssl", "payment_methods", "pm_auth", - "quick-xml", "rand", "rand_chacha", "rdkafka", diff --git a/config/config.example.toml b/config/config.example.toml index e505e9106f0..bd1a1639608 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -970,6 +970,13 @@ encryption_manager = "aws_kms" # Encryption manager client to be used key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. +[crm] +crm_manager = "hubspot_proxy" # Crm manager client to be used + +[crm.hubspot_proxy] +form_id="hubspot_proxy_form_id" # Form ID for Hubspot integration +request_url="hubspot_proxy_request_url" # Request URL for Hubspot API + [opensearch] host = "https://localhost:9200" enabled = false diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 5621a4940e8..7c1866b7794 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -303,6 +303,14 @@ encryption_manager = "aws_kms" # Encryption manager client to be used key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. +[crm] +crm_manager = "hubspot_proxy" # Crm manager client to be used + +[crm.hubspot_proxy] +form_id="" # Form ID for Hubspot integration +request_url="" # Request URL for Hubspot API + + [multitenancy] enabled = false global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index 8e734d31b53..fe590f6c7d5 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -99,12 +99,13 @@ pub struct ProdIntent { pub business_type: Option<String>, pub business_identifier: Option<String>, pub business_website: Option<String>, - pub poc_name: Option<String>, - pub poc_contact: Option<String>, + pub poc_name: Option<Secret<String>>, + pub poc_contact: Option<Secret<String>>, pub comments: Option<String>, pub is_completed: bool, #[serde(default)] pub product_type: MerchantProductType, + pub business_country_name: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index d722518154b..1606d731a21 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -176,3 +176,9 @@ pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600; /// SOAP 1.1 Envelope Namespace pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/"; + +/// The tag name used for identifying the host in metrics. +pub const METRICS_HOST_TAG_NAME: &str = "host"; + +/// API client request timeout (in seconds) +pub const REQUEST_TIME_OUT: u64 = 30; diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index ebab30eec70..9fdbbf133ca 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -41,6 +41,10 @@ tonic-reflection = { version = "0.12.2", optional = true } tonic-types = { version = "0.12.2", optional = true } hyper-util = { version = "0.1.9", optional = true } http-body-util = { version = "0.1.2", optional = true } +reqwest = { version = "0.11.27", features = ["rustls-tls"] } +http = "0.2.12" +url = { version = "2.5.0", features = ["serde"] } +quick-xml = { version = "0.31.0", features = ["serialize"] } # First party crates diff --git a/crates/external_services/src/crm.rs b/crates/external_services/src/crm.rs new file mode 100644 index 00000000000..ef2982fb380 --- /dev/null +++ b/crates/external_services/src/crm.rs @@ -0,0 +1,148 @@ +use std::sync::Arc; + +use common_utils::{ + errors::CustomResult, + ext_traits::ConfigExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; +use error_stack::ResultExt; +use http::header; +use hyperswitch_interfaces::{ + crm::{CrmInterface, CrmPayload}, + errors::HttpClientError, + types::Proxy, +}; +use reqwest; +use router_env::logger; + +use crate::{http_client, hubspot_proxy::HubspotRequest}; + +/// Hubspot Crm configuration +#[derive(Debug, Clone, serde::Deserialize)] +pub struct HubspotProxyConfig { + /// The ID of the Hubspot form to be submitted. + pub form_id: String, + + /// The URL to which the Hubspot form data will be sent. + pub request_url: String, +} + +impl HubspotProxyConfig { + /// Validates Hubspot configuration + pub(super) fn validate(&self) -> Result<(), InvalidCrmConfig> { + use common_utils::fp_utils::when; + + when(self.request_url.is_default_or_empty(), || { + Err(InvalidCrmConfig("request url must not be empty")) + })?; + + when(self.form_id.is_default_or_empty(), || { + Err(InvalidCrmConfig("form_id must not be empty")) + }) + } +} + +/// Error thrown when the crm config is invalid +#[derive(Debug, Clone)] +pub struct InvalidCrmConfig(pub &'static str); + +impl std::error::Error for InvalidCrmConfig {} + +impl std::fmt::Display for InvalidCrmConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "crm: {}", self.0) + } +} + +#[derive(Debug, Clone, Copy)] +/// NoCrm struct +pub struct NoCrm; + +/// Enum representing different Crm configurations +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(tag = "crm_manager")] +#[serde(rename_all = "snake_case")] +pub enum CrmManagerConfig { + /// Hubspot Crm configuration + HubspotProxy { + /// Hubspot Crm configuration + hubspot_proxy: HubspotProxyConfig, + }, + + /// No Crm configuration + #[default] + NoCrm, +} + +impl CrmManagerConfig { + /// Verifies that the client configuration is usable + pub fn validate(&self) -> Result<(), InvalidCrmConfig> { + match self { + Self::HubspotProxy { hubspot_proxy } => hubspot_proxy.validate(), + Self::NoCrm => Ok(()), + } + } + + /// Retrieves the appropriate Crm client based on the configuration. + pub async fn get_crm_client(&self) -> Arc<dyn CrmInterface> { + match self { + Self::HubspotProxy { hubspot_proxy } => Arc::new(hubspot_proxy.clone()), + Self::NoCrm => Arc::new(NoCrm), + } + } +} + +#[async_trait::async_trait] +impl CrmInterface for NoCrm { + async fn make_body(&self, _details: CrmPayload) -> RequestContent { + RequestContent::Json(Box::new(())) + } + + async fn make_request(&self, _body: RequestContent, _origin_base_url: String) -> Request { + RequestBuilder::default().build() + } + + async fn send_request( + &self, + _proxy: &Proxy, + _request: Request, + ) -> CustomResult<reqwest::Response, HttpClientError> { + logger::info!("No CRM configured!"); + Err(HttpClientError::UnexpectedState).attach_printable("No CRM configured!") + } +} + +#[async_trait::async_trait] +impl CrmInterface for HubspotProxyConfig { + async fn make_body(&self, details: CrmPayload) -> RequestContent { + RequestContent::FormUrlEncoded(Box::new(HubspotRequest::new( + details.business_country_name.unwrap_or_default(), + self.form_id.clone(), + details.poc_name.unwrap_or_default(), + details.poc_email.clone().unwrap_or_default(), + details.legal_business_name.unwrap_or_default(), + details.business_website.unwrap_or_default(), + ))) + } + + async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request { + RequestBuilder::new() + .method(Method::Post) + .url(self.request_url.as_str()) + .set_body(body) + .attach_default_headers() + .headers(vec![( + header::ORIGIN.to_string(), + format!("{origin_base_url}/dashboard").into(), + )]) + .build() + } + + async fn send_request( + &self, + proxy: &Proxy, + request: Request, + ) -> CustomResult<reqwest::Response, HttpClientError> { + http_client::send_request(proxy, request, None).await + } +} diff --git a/crates/external_services/src/http_client.rs b/crates/external_services/src/http_client.rs new file mode 100644 index 00000000000..dedeb0c1983 --- /dev/null +++ b/crates/external_services/src/http_client.rs @@ -0,0 +1,182 @@ +use common_utils::{consts, errors::CustomResult, request::Request}; +use hyperswitch_interfaces::{errors::HttpClientError, types::Proxy}; +use request::{HeaderExt, RequestBuilderExt}; +use router_env::{instrument, logger, tracing}; +/// client module +pub mod client; +/// metrics module +pub mod metrics; +/// request module +pub mod request; +use std::{error::Error, time::Duration}; + +use common_utils::request::RequestContent; +pub use common_utils::request::{ContentType, Method, RequestBuilder}; +use error_stack::ResultExt; + +#[allow(missing_docs)] +#[instrument(skip_all)] +pub async fn send_request( + client_proxy: &Proxy, + request: Request, + option_timeout_secs: Option<u64>, +) -> CustomResult<reqwest::Response, HttpClientError> { + logger::info!(method=?request.method, headers=?request.headers, payload=?request.body, ?request); + + let url = url::Url::parse(&request.url).change_context(HttpClientError::UrlParsingFailed)?; + + let client = client::create_client(client_proxy, request.certificate, request.certificate_key)?; + + let headers = request.headers.construct_header_map()?; + let metrics_tag = router_env::metric_attributes!(( + consts::METRICS_HOST_TAG_NAME, + url.host_str().unwrap_or_default().to_owned() + )); + let request = { + match request.method { + Method::Get => client.get(url), + Method::Post => { + let client = client.post(url); + match request.body { + Some(RequestContent::Json(payload)) => client.json(&payload), + Some(RequestContent::FormData(form)) => client.multipart(form), + Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), + Some(RequestContent::Xml(payload)) => { + let body = quick_xml::se::to_string(&payload) + .change_context(HttpClientError::BodySerializationFailed)?; + client.body(body).header("Content-Type", "application/xml") + } + Some(RequestContent::RawBytes(payload)) => client.body(payload), + None => client, + } + } + Method::Put => { + let client = client.put(url); + match request.body { + Some(RequestContent::Json(payload)) => client.json(&payload), + Some(RequestContent::FormData(form)) => client.multipart(form), + Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), + Some(RequestContent::Xml(payload)) => { + let body = quick_xml::se::to_string(&payload) + .change_context(HttpClientError::BodySerializationFailed)?; + client.body(body).header("Content-Type", "application/xml") + } + Some(RequestContent::RawBytes(payload)) => client.body(payload), + None => client, + } + } + Method::Patch => { + let client = client.patch(url); + match request.body { + Some(RequestContent::Json(payload)) => client.json(&payload), + Some(RequestContent::FormData(form)) => client.multipart(form), + Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), + Some(RequestContent::Xml(payload)) => { + let body = quick_xml::se::to_string(&payload) + .change_context(HttpClientError::BodySerializationFailed)?; + client.body(body).header("Content-Type", "application/xml") + } + Some(RequestContent::RawBytes(payload)) => client.body(payload), + None => client, + } + } + Method::Delete => client.delete(url), + } + .add_headers(headers) + .timeout(Duration::from_secs( + option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT), + )) + }; + + // We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here. + let cloned_send_request = request.try_clone().map(|cloned_request| async { + cloned_request + .send() + .await + .map_err(|error| match error { + error if error.is_timeout() => { + metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag); + HttpClientError::RequestTimeoutReceived + } + error if is_connection_closed_before_message_could_complete(&error) => { + metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag); + HttpClientError::ConnectionClosedIncompleteMessage + } + _ => HttpClientError::RequestNotSent(error.to_string()), + }) + .attach_printable("Unable to send request to connector") + }); + + let send_request = async { + request + .send() + .await + .map_err(|error| match error { + error if error.is_timeout() => { + metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag); + HttpClientError::RequestTimeoutReceived + } + error if is_connection_closed_before_message_could_complete(&error) => { + metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag); + HttpClientError::ConnectionClosedIncompleteMessage + } + _ => HttpClientError::RequestNotSent(error.to_string()), + }) + .attach_printable("Unable to send request to connector") + }; + + let response = common_utils::metrics::utils::record_operation_time( + send_request, + &metrics::EXTERNAL_REQUEST_TIME, + metrics_tag, + ) + .await; + // Retry once if the response is connection closed. + // + // This is just due to the racy nature of networking. + // hyper has a connection pool of idle connections, and it selected one to send your request. + // Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool. + // But occasionally, a connection will be selected from the pool + // and written to at the same time the server is deciding to close the connection. + // Since hyper already wrote some of the request, + // it can’t really retry it automatically on a new connection, since the server may have acted already + match response { + Ok(response) => Ok(response), + Err(error) + if error.current_context() == &HttpClientError::ConnectionClosedIncompleteMessage => + { + metrics::AUTO_RETRY_CONNECTION_CLOSED.add(1, metrics_tag); + match cloned_send_request { + Some(cloned_request) => { + logger::info!( + "Retrying request due to connection closed before message could complete" + ); + common_utils::metrics::utils::record_operation_time( + cloned_request, + &metrics::EXTERNAL_REQUEST_TIME, + metrics_tag, + ) + .await + } + None => { + logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable"); + Err(error) + } + } + } + err @ Err(_) => err, + } +} + +fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool { + let mut source = error.source(); + while let Some(err) = source { + if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() { + if hyper_err.is_incomplete_message() { + return true; + } + } + source = err.source(); + } + false +} diff --git a/crates/external_services/src/http_client/client.rs b/crates/external_services/src/http_client/client.rs new file mode 100644 index 00000000000..0696c9e76b9 --- /dev/null +++ b/crates/external_services/src/http_client/client.rs @@ -0,0 +1,131 @@ +use std::time::Duration; + +use base64::Engine; +use common_utils::consts::BASE64_ENGINE; +pub use common_utils::errors::CustomResult; +use error_stack::ResultExt; +use hyperswitch_interfaces::{errors::HttpClientError, types::Proxy}; +use masking::ExposeInterface; +use once_cell::sync::OnceCell; + +static DEFAULT_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); + +// We may need to use outbound proxy to connect to external world. +// Precedence will be the environment variables, followed by the config. +#[allow(missing_docs)] +pub fn create_client( + proxy_config: &Proxy, + client_certificate: Option<masking::Secret<String>>, + client_certificate_key: Option<masking::Secret<String>>, +) -> CustomResult<reqwest::Client, HttpClientError> { + match (client_certificate, client_certificate_key) { + (Some(encoded_certificate), Some(encoded_certificate_key)) => { + let client_builder = get_client_builder(proxy_config)?; + + let identity = create_identity_from_certificate_and_key( + encoded_certificate.clone(), + encoded_certificate_key, + )?; + let certificate_list = create_certificate(encoded_certificate)?; + let client_builder = certificate_list + .into_iter() + .fold(client_builder, |client_builder, certificate| { + client_builder.add_root_certificate(certificate) + }); + client_builder + .identity(identity) + .use_rustls_tls() + .build() + .change_context(HttpClientError::ClientConstructionFailed) + .attach_printable("Failed to construct client with certificate and certificate key") + } + _ => get_base_client(proxy_config), + } +} + +#[allow(missing_docs)] +pub fn get_client_builder( + proxy_config: &Proxy, +) -> CustomResult<reqwest::ClientBuilder, HttpClientError> { + let mut client_builder = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .pool_idle_timeout(Duration::from_secs( + proxy_config + .idle_pool_connection_timeout + .unwrap_or_default(), + )); + + let proxy_exclusion_config = + reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default()); + + // Proxy all HTTPS traffic through the configured HTTPS proxy + if let Some(url) = proxy_config.https_url.as_ref() { + client_builder = client_builder.proxy( + reqwest::Proxy::https(url) + .change_context(HttpClientError::InvalidProxyConfiguration) + .attach_printable("HTTPS proxy configuration error")? + .no_proxy(proxy_exclusion_config.clone()), + ); + } + + // Proxy all HTTP traffic through the configured HTTP proxy + if let Some(url) = proxy_config.http_url.as_ref() { + client_builder = client_builder.proxy( + reqwest::Proxy::http(url) + .change_context(HttpClientError::InvalidProxyConfiguration) + .attach_printable("HTTP proxy configuration error")? + .no_proxy(proxy_exclusion_config), + ); + } + + Ok(client_builder) +} + +#[allow(missing_docs)] +pub fn create_identity_from_certificate_and_key( + encoded_certificate: masking::Secret<String>, + encoded_certificate_key: masking::Secret<String>, +) -> Result<reqwest::Identity, error_stack::Report<HttpClientError>> { + let decoded_certificate = BASE64_ENGINE + .decode(encoded_certificate.expose()) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let decoded_certificate_key = BASE64_ENGINE + .decode(encoded_certificate_key.expose()) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let certificate = String::from_utf8(decoded_certificate) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let certificate_key = String::from_utf8(decoded_certificate_key) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let key_chain = format!("{}{}", certificate_key, certificate); + reqwest::Identity::from_pem(key_chain.as_bytes()) + .change_context(HttpClientError::CertificateDecodeFailed) +} + +#[allow(missing_docs)] +pub fn create_certificate( + encoded_certificate: masking::Secret<String>, +) -> Result<Vec<reqwest::Certificate>, error_stack::Report<HttpClientError>> { + let decoded_certificate = BASE64_ENGINE + .decode(encoded_certificate.expose()) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let certificate = String::from_utf8(decoded_certificate) + .change_context(HttpClientError::CertificateDecodeFailed)?; + reqwest::Certificate::from_pem_bundle(certificate.as_bytes()) + .change_context(HttpClientError::CertificateDecodeFailed) +} + +fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, HttpClientError> { + Ok(DEFAULT_CLIENT + .get_or_try_init(|| { + get_client_builder(proxy_config)? + .build() + .change_context(HttpClientError::ClientConstructionFailed) + .attach_printable("Failed to construct base client") + })? + .clone()) +} diff --git a/crates/external_services/src/http_client/metrics.rs b/crates/external_services/src/http_client/metrics.rs new file mode 100644 index 00000000000..5b6f48334f2 --- /dev/null +++ b/crates/external_services/src/http_client/metrics.rs @@ -0,0 +1,9 @@ +use router_env::{counter_metric, global_meter, histogram_metric_f64}; + +global_meter!(GLOBAL_METER, "ROUTER_API"); + +counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER); + +histogram_metric_f64!(EXTERNAL_REQUEST_TIME, GLOBAL_METER); + +counter_metric!(AUTO_RETRY_CONNECTION_CLOSED, GLOBAL_METER); diff --git a/crates/external_services/src/http_client/request.rs b/crates/external_services/src/http_client/request.rs new file mode 100644 index 00000000000..cf2727f0668 --- /dev/null +++ b/crates/external_services/src/http_client/request.rs @@ -0,0 +1,45 @@ +use std::str::FromStr; + +use common_utils::request::Headers; +pub use common_utils::{errors::CustomResult, request::ContentType}; +use error_stack::ResultExt; +use hyperswitch_interfaces::errors::HttpClientError; +pub use masking::{Mask, Maskable}; +use router_env::{instrument, tracing}; + +#[allow(missing_docs)] +pub trait HeaderExt { + fn construct_header_map(self) -> CustomResult<reqwest::header::HeaderMap, HttpClientError>; +} + +impl HeaderExt for Headers { + fn construct_header_map(self) -> CustomResult<reqwest::header::HeaderMap, HttpClientError> { + use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; + + self.into_iter().try_fold( + HeaderMap::new(), + |mut header_map, (header_name, header_value)| { + let header_name = HeaderName::from_str(&header_name) + .change_context(HttpClientError::HeaderMapConstructionFailed)?; + let header_value = header_value.into_inner(); + let header_value = HeaderValue::from_str(&header_value) + .change_context(HttpClientError::HeaderMapConstructionFailed)?; + header_map.append(header_name, header_value); + Ok(header_map) + }, + ) + } +} + +#[allow(missing_docs)] +pub trait RequestBuilderExt { + fn add_headers(self, headers: reqwest::header::HeaderMap) -> Self; +} + +impl RequestBuilderExt for reqwest::RequestBuilder { + #[instrument(skip_all)] + fn add_headers(mut self, headers: reqwest::header::HeaderMap) -> Self { + self = self.headers(headers); + self + } +} diff --git a/crates/external_services/src/hubspot_proxy.rs b/crates/external_services/src/hubspot_proxy.rs new file mode 100644 index 00000000000..17817676410 --- /dev/null +++ b/crates/external_services/src/hubspot_proxy.rs @@ -0,0 +1,78 @@ +use masking::Secret; + +/// Lead source constant for Hubspot +pub const HUBSPOT_LEAD_SOURCE: &str = "Hyperswitch Dashboard"; + +/// Struct representing a request to Hubspot +#[derive(Clone, Debug, serde::Serialize, Default)] +pub struct HubspotRequest { + /// Indicates whether Hubspot should be used. + #[serde(rename = "useHubspot")] + pub use_hubspot: bool, + + /// The country of the user or company. + pub country: String, + + /// The ID of the Hubspot form being submitted. + #[serde(rename = "hubspotFormId")] + pub hubspot_form_id: String, + + /// The first name of the user. + pub firstname: Secret<String>, + + /// The last name of the user. + pub lastname: Secret<String>, + + /// The email address of the user. + pub email: Secret<String>, + + /// The name of the company. + #[serde(rename = "companyName")] + pub company_name: String, + + /// The source of the lead, typically set to "Hyperswitch Dashboard". + pub lead_source: String, + + /// The website URL of the company. + pub website: String, + + /// The phone number of the user. + pub phone: Secret<String>, + + /// The role or designation of the user. + pub role: String, + + /// The monthly GMV (Gross Merchandise Value) of the company. + #[serde(rename = "monthlyGMV")] + pub monthly_gmv: String, + + /// Notes from the business development team. + pub bd_notes: String, + + /// Additional message or comments. + pub message: String, +} + +#[allow(missing_docs)] +impl HubspotRequest { + pub fn new( + country: String, + hubspot_form_id: String, + firstname: Secret<String>, + email: Secret<String>, + company_name: String, + website: String, + ) -> Self { + Self { + use_hubspot: true, + country, + hubspot_form_id, + firstname, + email, + company_name, + lead_source: HUBSPOT_LEAD_SOURCE.to_string(), + website, + ..Default::default() + } + } +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 304ce248317..f3b1b330e16 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -17,8 +17,17 @@ pub mod no_encryption; /// Building grpc clients to communicate with the server pub mod grpc_client; +/// http_client module +pub mod http_client; + +/// hubspot_proxy module +pub mod hubspot_proxy; + pub mod managers; +/// crm module +pub mod crm; + /// Crate specific constants #[cfg(feature = "aws_kms")] pub mod consts { diff --git a/crates/hyperswitch_interfaces/src/crm.rs b/crates/hyperswitch_interfaces/src/crm.rs new file mode 100644 index 00000000000..40eb56e9e6b --- /dev/null +++ b/crates/hyperswitch_interfaces/src/crm.rs @@ -0,0 +1,69 @@ +use common_enums::CountryAlpha2; +use common_utils::{ + errors::CustomResult, + request::{Request, RequestContent}, +}; +use masking::Secret; + +use super::types::Proxy; +use crate::errors::HttpClientError; + +/// Crm Payload structure +#[derive(Clone, Debug, serde::Serialize, Default)] +pub struct CrmPayload { + /// The legal name of the business. + pub legal_business_name: Option<String>, + + /// A label or tag associated with the business. + pub business_label: Option<String>, + + /// The location of the business, represented as a country code (ISO Alpha-2 format). + pub business_location: Option<CountryAlpha2>, + + /// The display name of the business. + pub display_name: Option<String>, + + /// The email address of the point of contact (POC) for the business. + pub poc_email: Option<Secret<String>>, + + /// The type of business (e.g., LLC, Corporation, etc.). + pub business_type: Option<String>, + + /// A unique identifier for the business. + pub business_identifier: Option<String>, + + /// The website URL of the business. + pub business_website: Option<String>, + + /// The name of the point of contact (POC) for the business. + pub poc_name: Option<Secret<String>>, + + /// The contact number of the point of contact (POC) for the business. + pub poc_contact: Option<Secret<String>>, + + /// Additional comments or notes about the business. + pub comments: Option<String>, + + /// Indicates whether the Crm process for the business is completed. + pub is_completed: bool, + + /// The name of the country where the business is located. + pub business_country_name: Option<String>, +} + +/// Trait defining the interface for encryption management +#[async_trait::async_trait] +pub trait CrmInterface: Send + Sync { + /// Make body for the request + async fn make_body(&self, details: CrmPayload) -> RequestContent; + + /// Encrypt the given input data + async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request; + + /// Decrypt the given input data + async fn send_request( + &self, + proxy: &Proxy, + request: Request, + ) -> CustomResult<reqwest::Response, HttpClientError>; +} diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs index 466186ae368..1a11c2d761d 100644 --- a/crates/hyperswitch_interfaces/src/errors.rs +++ b/crates/hyperswitch_interfaces/src/errors.rs @@ -1,5 +1,6 @@ //! Errors interface +use common_enums::ApiClientError; use common_utils::errors::ErrorSwitch; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; @@ -156,3 +157,73 @@ impl ErrorSwitch<ApiErrorResponse> for ConnectorError { } } } + +// http client errors +#[allow(missing_docs, missing_debug_implementations)] +#[derive(Debug, Clone, thiserror::Error, PartialEq)] +pub enum HttpClientError { + #[error("Header map construction failed")] + HeaderMapConstructionFailed, + #[error("Invalid proxy configuration")] + InvalidProxyConfiguration, + #[error("Client construction failed")] + ClientConstructionFailed, + #[error("Certificate decode failed")] + CertificateDecodeFailed, + #[error("Request body serialization failed")] + BodySerializationFailed, + #[error("Unexpected state reached/Invariants conflicted")] + UnexpectedState, + + #[error("Failed to parse URL")] + UrlParsingFailed, + #[error("URL encoding of request payload failed")] + UrlEncodingFailed, + #[error("Failed to send request to connector {0}")] + RequestNotSent(String), + #[error("Failed to decode response")] + ResponseDecodingFailed, + + #[error("Server responded with Request Timeout")] + RequestTimeoutReceived, + + #[error("connection closed before a message could complete")] + ConnectionClosedIncompleteMessage, + + #[error("Server responded with Internal Server Error")] + InternalServerErrorReceived, + #[error("Server responded with Bad Gateway")] + BadGatewayReceived, + #[error("Server responded with Service Unavailable")] + ServiceUnavailableReceived, + #[error("Server responded with Gateway Timeout")] + GatewayTimeoutReceived, + #[error("Server responded with unexpected response")] + UnexpectedServerResponse, +} + +impl ErrorSwitch<ApiClientError> for HttpClientError { + fn switch(&self) -> ApiClientError { + match self { + Self::HeaderMapConstructionFailed => ApiClientError::HeaderMapConstructionFailed, + Self::InvalidProxyConfiguration => ApiClientError::InvalidProxyConfiguration, + Self::ClientConstructionFailed => ApiClientError::ClientConstructionFailed, + Self::CertificateDecodeFailed => ApiClientError::CertificateDecodeFailed, + Self::BodySerializationFailed => ApiClientError::BodySerializationFailed, + Self::UnexpectedState => ApiClientError::UnexpectedState, + Self::UrlParsingFailed => ApiClientError::UrlParsingFailed, + Self::UrlEncodingFailed => ApiClientError::UrlEncodingFailed, + Self::RequestNotSent(reason) => ApiClientError::RequestNotSent(reason.clone()), + Self::ResponseDecodingFailed => ApiClientError::ResponseDecodingFailed, + Self::RequestTimeoutReceived => ApiClientError::RequestTimeoutReceived, + Self::ConnectionClosedIncompleteMessage => { + ApiClientError::ConnectionClosedIncompleteMessage + } + Self::InternalServerErrorReceived => ApiClientError::InternalServerErrorReceived, + Self::BadGatewayReceived => ApiClientError::BadGatewayReceived, + Self::ServiceUnavailableReceived => ApiClientError::ServiceUnavailableReceived, + Self::GatewayTimeoutReceived => ApiClientError::GatewayTimeoutReceived, + Self::UnexpectedServerResponse => ApiClientError::UnexpectedServerResponse, + } + } +} diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs index a9eb2997c89..b9c16f6d82f 100644 --- a/crates/hyperswitch_interfaces/src/lib.rs +++ b/crates/hyperswitch_interfaces/src/lib.rs @@ -23,3 +23,6 @@ pub mod metrics; pub mod secrets_interface; pub mod types; pub mod webhooks; + +/// Crm interface +pub mod crm; diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index 27f50609da2..e41e8cd9bcf 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -282,3 +282,31 @@ pub type BillingConnectorInvoiceSyncTypeV2 = dyn ConnectorIntegrationV2< BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; + +/// Proxy configuration structure +#[derive(Debug, serde::Deserialize, Clone)] +#[serde(default)] +pub struct Proxy { + /// The URL of the HTTP proxy server. + pub http_url: Option<String>, + + /// The URL of the HTTPS proxy server. + pub https_url: Option<String>, + + /// The timeout duration (in seconds) for idle connections in the proxy pool. + pub idle_pool_connection_timeout: Option<u64>, + + /// A comma-separated list of hosts that should bypass the proxy. + pub bypass_proxy_hosts: Option<String>, +} + +impl Default for Proxy { + fn default() -> Self { + Self { + http_url: Default::default(), + https_url: Default::default(), + idle_pool_connection_timeout: Some(90), + bypass_proxy_hosts: Default::default(), + } + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 30b520eb58b..5395e538c29 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -85,7 +85,6 @@ num-traits = "0.2.19" once_cell = "1.19.0" openidconnect = "3.5.0" # TODO: remove reqwest openssl = "0.10.70" -quick-xml = { version = "0.31.0", features = ["serialize"] } rand = "0.8.5" rand_chacha = "0.3.1" rdkafka = "0.36.2" diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index ac3a446b01f..dee7dfbb03c 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -49,18 +49,6 @@ impl Default for super::settings::Database { } } } - -impl Default for super::settings::Proxy { - fn default() -> Self { - Self { - http_url: Default::default(), - https_url: Default::default(), - idle_pool_connection_timeout: Some(90), - bypass_proxy_hosts: Default::default(), - } - } -} - impl Default for super::settings::Locker { fn default() -> Self { Self { diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 3ae171545bc..308cbe417bb 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -525,6 +525,7 @@ pub(crate) async fn fetch_raw_secrets( decision: conf.decision, locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors, grpc_client: conf.grpc_client, + crm: conf.crm, #[cfg(feature = "v2")] cell_information: conf.cell_information, network_tokenization_supported_card_networks: conf diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index b0fd269bf79..f7120ff4545 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -13,6 +13,7 @@ use error_stack::ResultExt; #[cfg(feature = "email")] use external_services::email::EmailSettings; use external_services::{ + crm::CrmManagerConfig, file_storage::FileStorageConfig, grpc_client::GrpcClientSettings, managers::{ @@ -21,8 +22,11 @@ use external_services::{ }, }; pub use hyperswitch_interfaces::configs::Connectors; -use hyperswitch_interfaces::secrets_interface::secret_state::{ - RawSecret, SecretState, SecretStateContainer, SecuredSecret, +use hyperswitch_interfaces::{ + secrets_interface::secret_state::{ + RawSecret, SecretState, SecretStateContainer, SecuredSecret, + }, + types::Proxy, }; use masking::Secret; pub use payment_methods::configs::settings::{ @@ -96,6 +100,7 @@ pub struct Settings<S: SecretState> { #[cfg(feature = "email")] pub email: EmailSettings, pub user: UserSettings, + pub crm: CrmManagerConfig, pub cors: CorsSettings, pub mandates: Mandates, pub zero_mandates: ZeroMandates, @@ -714,15 +719,6 @@ pub struct Jwekey { pub tunnel_private_key: Secret<String>, } -#[derive(Debug, Deserialize, Clone)] -#[serde(default)] -pub struct Proxy { - pub http_url: Option<String>, - pub https_url: Option<String>, - pub idle_pool_connection_timeout: Option<u64>, - pub bypass_proxy_hosts: Option<String>, -} - #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { @@ -988,6 +984,10 @@ impl Settings<SecuredSecret> { .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + self.crm + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + self.lock_settings.validate()?; self.events.validate()?; diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 43041ef01b6..f728e6aedc8 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -54,7 +54,6 @@ pub(crate) const API_KEY_LENGTH: usize = 64; // OID (Object Identifier) for the merchant ID field extension. pub(crate) const MERCHANT_ID_FIELD_EXTENSION_ID: &str = "1.2.840.113635.100.6.32"; -pub(crate) const METRICS_HOST_TAG_NAME: &str = "host"; pub const MAX_ROUTING_CONFIGS_PER_MERCHANT: usize = 100; pub const ROUTING_CONFIG_ID_LENGTH: usize = 10; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 27c8a9fb8ff..694bfe08cb9 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -15,6 +15,7 @@ use diesel_models::configs; #[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))] use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge}; use error_stack::{report, FutureExt, ResultExt}; +use external_services::http_client::client; use hyperswitch_domain_models::merchant_connector_account::{ FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount, }; @@ -39,7 +40,7 @@ use crate::{ routes::{metrics, SessionState}, services::{ self, - api::{self as service_api, client}, + api::{self as service_api}, authentication, pm_auth as payment_initiation_service, }, types::{ diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs index 98aef1e3064..407f62f1ec9 100644 --- a/crates/router/src/core/connector_onboarding/paypal.rs +++ b/crates/router/src/core/connector_onboarding/paypal.rs @@ -1,6 +1,7 @@ use api_models::{admin::MerchantConnectorUpdate, connector_onboarding as api}; use common_utils::ext_traits::Encode; use error_stack::ResultExt; +pub use external_services::http_client; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ @@ -8,7 +9,7 @@ use crate::{ admin, errors::{ApiErrorResponse, RouterResult}, }, - services::{send_request, ApplicationResponse, Request}, + services::{ApplicationResponse, Request}, types::{self as oss_types, api as oss_api_types, api::connector_onboarding as types}, utils::connector_onboarding as utils, SessionState, @@ -47,7 +48,7 @@ pub async fn get_action_url_from_paypal( return_url, )) .await?; - let referral_response = send_request(&state, referral_request, None) + let referral_response = http_client::send_request(&state.conf.proxy, referral_request, None) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to send request to paypal referrals")?; @@ -97,10 +98,11 @@ pub async fn sync_merchant_onboarding_status( let merchant_details_request = utils::paypal::build_paypal_get_request(merchant_details_url, access_token.token.expose())?; - let merchant_details_response = send_request(&state, merchant_details_request, None) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to send request to paypal merchant details")?; + let merchant_details_response = + http_client::send_request(&state.conf.proxy, merchant_details_request, None) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to send request to paypal merchant details")?; let parsed_response: types::paypal::SellerStatusDetailsResponse = merchant_details_response .json() @@ -121,10 +123,11 @@ async fn find_paypal_merchant_by_tracking_id( merchant_onboarding_status_url(state.clone(), tracking_id), access_token.token.peek().to_string(), )?; - let seller_status_response = send_request(&state, seller_status_request, None) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to send request to paypal onboarding status")?; + let seller_status_response = + http_client::send_request(&state.conf.proxy, seller_status_request, None) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to send request to paypal onboarding status")?; if seller_status_response.status().is_success() { return Ok(Some( diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index 17e86dc41ca..16418ad83a9 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -17,6 +17,7 @@ use crate::{ storage, transformers::ForeignTryFrom, }, + utils::user as user_utils, SessionState, }; @@ -80,7 +81,7 @@ pub async fn send_recon_request( state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -211,7 +212,7 @@ pub async fn recon_merchant_account_update( let _ = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 9802edfd346..1097f57b198 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -32,8 +32,6 @@ use user_api::dashboard_metadata::SetMetaDataRequest; #[cfg(feature = "v1")] use super::admin; use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; -#[cfg(feature = "email")] -use crate::services::email::types as email_types; #[cfg(feature = "v1")] use crate::types::transformers::ForeignFrom; use crate::{ @@ -51,6 +49,8 @@ use crate::{ user::{theme as theme_utils, two_factor_auth as tfa_utils}, }, }; +#[cfg(feature = "email")] +use crate::{services::email::types as email_types, utils::user as user_utils}; pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] @@ -99,7 +99,7 @@ pub async fn signup_with_merchant_id( let send_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -319,7 +319,7 @@ pub async fn connect_account( let send_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -374,7 +374,7 @@ pub async fn connect_account( let magic_link_result = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(magic_link_email), state.conf.proxy.https_url.as_ref(), ) @@ -390,7 +390,7 @@ pub async fn connect_account( let welcome_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(welcome_to_community_email), state.conf.proxy.https_url.as_ref(), ) @@ -525,7 +525,7 @@ pub async fn forgot_password( state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -937,7 +937,7 @@ async fn handle_existing_user_invitation( is_email_sent = state .email_client .compose_and_send_email( - email_types::get_base_url(state), + user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1092,7 +1092,7 @@ async fn handle_new_user_invitation( let send_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(state), + user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1247,7 +1247,7 @@ pub async fn resend_invite( state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1967,7 +1967,7 @@ pub async fn send_verification_mail( state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index a4068fc4fad..ece4c601694 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -8,10 +8,10 @@ use diesel_models::{ enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata, }; use error_stack::{report, ResultExt}; +use hyperswitch_interfaces::crm::CrmPayload; #[cfg(feature = "email")] use masking::ExposeInterface; use masking::PeekInterface; -#[cfg(feature = "email")] use router_env::logger; use crate::{ @@ -19,7 +19,7 @@ use crate::{ routes::{app::ReqState, SessionState}, services::{authentication::UserFromToken, ApplicationResponse}, types::domain::{self, user::dashboard_metadata as types, MerchantKeyStore}, - utils::user::dashboard_metadata as utils, + utils::user::{self as user_utils, dashboard_metadata as utils}, }; #[cfg(feature = "email")] use crate::{services::email::types as email_types, utils::user::theme as theme_utils}; @@ -501,7 +501,7 @@ async fn insert_metadata( .await?; let email_contents = email_types::BizEmailProd::new( state, - data, + data.clone(), theme.as_ref().map(|theme| theme.theme_id.clone()), theme .map(|theme| theme.email_config()) @@ -510,7 +510,7 @@ async fn insert_metadata( let send_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(state), + user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -519,6 +519,43 @@ async fn insert_metadata( } } + // Hubspot integration + let hubspot_body = state + .crm_client + .make_body(CrmPayload { + legal_business_name: data.legal_business_name, + business_label: data.business_label, + business_location: data.business_location, + display_name: data.display_name, + poc_email: data.poc_email, + business_type: data.business_type, + business_identifier: data.business_identifier, + business_website: data.business_website, + poc_name: data.poc_name, + poc_contact: data.poc_contact, + comments: data.comments, + is_completed: data.is_completed, + business_country_name: data.business_country_name, + }) + .await; + let base_url = user_utils::get_base_url(state); + let hubspot_request = state + .crm_client + .make_request(hubspot_body, base_url.to_string()) + .await; + + let _ = state + .crm_client + .send_request(&state.conf.proxy, hubspot_request) + .await + .inspect_err(|err| { + logger::error!( + "An error occurred while sending data to hubspot for user_id {}: {:?}", + user.user_id, + err + ); + }); + metadata } types::MetaData::SPTestPayment(data) => { diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9cb83192f6f..82a91f468c5 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -17,6 +17,7 @@ use external_services::{ grpc_client::{GrpcClients, GrpcHeaders}, }; use hyperswitch_interfaces::{ + crm::CrmInterface, encryption_interface::EncryptionManagementInterface, secrets_interface::secret_state::{RawSecret, SecuredSecret}, }; @@ -124,6 +125,7 @@ pub struct SessionState { pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, + pub crm_client: Arc<dyn CrmInterface>, } impl scheduler::SchedulerSessionState for SessionState { fn get_db(&self) -> Box<dyn SchedulerInterface> { @@ -235,6 +237,7 @@ pub struct AppState { pub encryption_client: Arc<dyn EncryptionManagementInterface>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, + pub crm_client: Arc<dyn CrmInterface>, } impl scheduler::SchedulerAppState for AppState { fn get_tenants(&self) -> Vec<id_type::TenantId> { @@ -396,6 +399,7 @@ impl AppState { let file_storage_client = conf.file_storage.get_file_storage_client().await; let theme_storage_client = conf.theme.storage.get_file_storage_client().await; + let crm_client = conf.crm.get_crm_client().await; let grpc_client = conf.grpc_client.get_grpc_client_interface().await; @@ -418,6 +422,7 @@ impl AppState { encryption_client, grpc_client, theme_storage_client, + crm_client, } }) .await @@ -511,6 +516,7 @@ impl AppState { grpc_client: Arc::clone(&self.grpc_client), theme_storage_client: self.theme_storage_client.clone(), locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()), + crm_client: self.crm_client.clone(), }) } } diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 63ef0b876f3..e8aeef3e406 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -11,7 +11,6 @@ counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses // API Level Metrics counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER); histogram_metric_f64!(REQUEST_TIME, GLOBAL_METER); -histogram_metric_f64!(EXTERNAL_REQUEST_TIME, GLOBAL_METER); // Operation Level Metrics counter_metric!(PAYMENT_OPS_COUNT, GLOBAL_METER); @@ -99,7 +98,6 @@ counter_metric!(APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT, GLOBAL_METER); counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT, GLOBAL_METER); // Metrics for Payment Auto Retries -counter_metric!(AUTO_RETRY_CONNECTION_CLOSED, GLOBAL_METER); counter_metric!(AUTO_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_MISS_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER); diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index a9193160263..3fef01a8c21 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -3,7 +3,6 @@ pub mod generic_link_response; pub mod request; use std::{ collections::{HashMap, HashSet}, - error::Error, fmt::Debug, future::Future, str, @@ -52,7 +51,6 @@ use serde::Serialize; use serde_json::json; use tera::{Context, Error as TeraError, Tera}; -use self::request::{HeaderExt, RequestBuilderExt}; use super::{ authentication::AuthenticateAndFetch, connector_integration_interface::BoxedConnectorIntegrationInterface, @@ -431,178 +429,6 @@ pub async fn call_connector_api( handle_response(response).await } -#[instrument(skip_all)] -pub async fn send_request( - state: &SessionState, - request: Request, - option_timeout_secs: Option<u64>, -) -> CustomResult<reqwest::Response, errors::ApiClientError> { - logger::info!(method=?request.method, headers=?request.headers, payload=?request.body, ?request); - - let url = - url::Url::parse(&request.url).change_context(errors::ApiClientError::UrlParsingFailed)?; - - let client = client::create_client( - &state.conf.proxy, - request.certificate, - request.certificate_key, - )?; - - let headers = request.headers.construct_header_map()?; - let metrics_tag = router_env::metric_attributes!(( - consts::METRICS_HOST_TAG_NAME, - url.host_str().unwrap_or_default().to_owned() - )); - let request = { - match request.method { - Method::Get => client.get(url), - Method::Post => { - let client = client.post(url); - match request.body { - Some(RequestContent::Json(payload)) => client.json(&payload), - Some(RequestContent::FormData(form)) => client.multipart(form), - Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), - Some(RequestContent::Xml(payload)) => { - let body = quick_xml::se::to_string(&payload) - .change_context(errors::ApiClientError::BodySerializationFailed)?; - client.body(body).header("Content-Type", "application/xml") - } - Some(RequestContent::RawBytes(payload)) => client.body(payload), - None => client, - } - } - Method::Put => { - let client = client.put(url); - match request.body { - Some(RequestContent::Json(payload)) => client.json(&payload), - Some(RequestContent::FormData(form)) => client.multipart(form), - Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), - Some(RequestContent::Xml(payload)) => { - let body = quick_xml::se::to_string(&payload) - .change_context(errors::ApiClientError::BodySerializationFailed)?; - client.body(body).header("Content-Type", "application/xml") - } - Some(RequestContent::RawBytes(payload)) => client.body(payload), - None => client, - } - } - Method::Patch => { - let client = client.patch(url); - match request.body { - Some(RequestContent::Json(payload)) => client.json(&payload), - Some(RequestContent::FormData(form)) => client.multipart(form), - Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), - Some(RequestContent::Xml(payload)) => { - let body = quick_xml::se::to_string(&payload) - .change_context(errors::ApiClientError::BodySerializationFailed)?; - client.body(body).header("Content-Type", "application/xml") - } - Some(RequestContent::RawBytes(payload)) => client.body(payload), - None => client, - } - } - Method::Delete => client.delete(url), - } - .add_headers(headers) - .timeout(Duration::from_secs( - option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT), - )) - }; - - // We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here. - let cloned_send_request = request.try_clone().map(|cloned_request| async { - cloned_request - .send() - .await - .map_err(|error| match error { - error if error.is_timeout() => { - metrics::REQUEST_BUILD_FAILURE.add(1, &[]); - errors::ApiClientError::RequestTimeoutReceived - } - error if is_connection_closed_before_message_could_complete(&error) => { - metrics::REQUEST_BUILD_FAILURE.add(1, &[]); - errors::ApiClientError::ConnectionClosedIncompleteMessage - } - _ => errors::ApiClientError::RequestNotSent(error.to_string()), - }) - .attach_printable("Unable to send request to connector") - }); - - let send_request = async { - request - .send() - .await - .map_err(|error| match error { - error if error.is_timeout() => { - metrics::REQUEST_BUILD_FAILURE.add(1, &[]); - errors::ApiClientError::RequestTimeoutReceived - } - error if is_connection_closed_before_message_could_complete(&error) => { - metrics::REQUEST_BUILD_FAILURE.add(1, &[]); - errors::ApiClientError::ConnectionClosedIncompleteMessage - } - _ => errors::ApiClientError::RequestNotSent(error.to_string()), - }) - .attach_printable("Unable to send request to connector") - }; - - let response = common_utils::metrics::utils::record_operation_time( - send_request, - &metrics::EXTERNAL_REQUEST_TIME, - metrics_tag, - ) - .await; - // Retry once if the response is connection closed. - // - // This is just due to the racy nature of networking. - // hyper has a connection pool of idle connections, and it selected one to send your request. - // Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool. - // But occasionally, a connection will be selected from the pool - // and written to at the same time the server is deciding to close the connection. - // Since hyper already wrote some of the request, - // it can’t really retry it automatically on a new connection, since the server may have acted already - match response { - Ok(response) => Ok(response), - Err(error) - if error.current_context() - == &errors::ApiClientError::ConnectionClosedIncompleteMessage => - { - metrics::AUTO_RETRY_CONNECTION_CLOSED.add(1, &[]); - match cloned_send_request { - Some(cloned_request) => { - logger::info!( - "Retrying request due to connection closed before message could complete" - ); - common_utils::metrics::utils::record_operation_time( - cloned_request, - &metrics::EXTERNAL_REQUEST_TIME, - metrics_tag, - ) - .await - } - None => { - logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable"); - Err(error) - } - } - } - err @ Err(_) => err, - } -} - -fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool { - let mut source = error.source(); - while let Some(err) = source { - if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() { - if hyper_err.is_incomplete_message() { - return true; - } - } - source = err.source(); - } - false -} - #[instrument(skip_all)] async fn handle_response( response: CustomResult<reqwest::Response, errors::ApiClientError>, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index 096c5ed45d1..d690ebd3277 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -1,139 +1,20 @@ use std::time::Duration; -use base64::Engine; +use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; +pub use external_services::http_client::{self, client}; use http::{HeaderValue, Method}; -use masking::{ExposeInterface, PeekInterface}; -use once_cell::sync::OnceCell; +use hyperswitch_interfaces::types::Proxy; +use masking::PeekInterface; use reqwest::multipart::Form; use router_env::tracing_actix_web::RequestId; use super::{request::Maskable, Request}; use crate::{ - configs::settings::Proxy, - consts::BASE64_ENGINE, core::errors::{ApiClientError, CustomResult}, routes::SessionState, }; -static DEFAULT_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); - -fn get_client_builder( - proxy_config: &Proxy, -) -> CustomResult<reqwest::ClientBuilder, ApiClientError> { - let mut client_builder = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .pool_idle_timeout(Duration::from_secs( - proxy_config - .idle_pool_connection_timeout - .unwrap_or_default(), - )); - - let proxy_exclusion_config = - reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default()); - - // Proxy all HTTPS traffic through the configured HTTPS proxy - if let Some(url) = proxy_config.https_url.as_ref() { - client_builder = client_builder.proxy( - reqwest::Proxy::https(url) - .change_context(ApiClientError::InvalidProxyConfiguration) - .attach_printable("HTTPS proxy configuration error")? - .no_proxy(proxy_exclusion_config.clone()), - ); - } - - // Proxy all HTTP traffic through the configured HTTP proxy - if let Some(url) = proxy_config.http_url.as_ref() { - client_builder = client_builder.proxy( - reqwest::Proxy::http(url) - .change_context(ApiClientError::InvalidProxyConfiguration) - .attach_printable("HTTP proxy configuration error")? - .no_proxy(proxy_exclusion_config), - ); - } - - Ok(client_builder) -} - -fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, ApiClientError> { - Ok(DEFAULT_CLIENT - .get_or_try_init(|| { - get_client_builder(proxy_config)? - .build() - .change_context(ApiClientError::ClientConstructionFailed) - .attach_printable("Failed to construct base client") - })? - .clone()) -} - -// We may need to use outbound proxy to connect to external world. -// Precedence will be the environment variables, followed by the config. -pub fn create_client( - proxy_config: &Proxy, - client_certificate: Option<masking::Secret<String>>, - client_certificate_key: Option<masking::Secret<String>>, -) -> CustomResult<reqwest::Client, ApiClientError> { - match (client_certificate, client_certificate_key) { - (Some(encoded_certificate), Some(encoded_certificate_key)) => { - let client_builder = get_client_builder(proxy_config)?; - - let identity = create_identity_from_certificate_and_key( - encoded_certificate.clone(), - encoded_certificate_key, - )?; - let certificate_list = create_certificate(encoded_certificate)?; - let client_builder = certificate_list - .into_iter() - .fold(client_builder, |client_builder, certificate| { - client_builder.add_root_certificate(certificate) - }); - client_builder - .identity(identity) - .use_rustls_tls() - .build() - .change_context(ApiClientError::ClientConstructionFailed) - .attach_printable("Failed to construct client with certificate and certificate key") - } - _ => get_base_client(proxy_config), - } -} - -pub fn create_identity_from_certificate_and_key( - encoded_certificate: masking::Secret<String>, - encoded_certificate_key: masking::Secret<String>, -) -> Result<reqwest::Identity, error_stack::Report<ApiClientError>> { - let decoded_certificate = BASE64_ENGINE - .decode(encoded_certificate.expose()) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let decoded_certificate_key = BASE64_ENGINE - .decode(encoded_certificate_key.expose()) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let certificate = String::from_utf8(decoded_certificate) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let certificate_key = String::from_utf8(decoded_certificate_key) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let key_chain = format!("{}{}", certificate_key, certificate); - reqwest::Identity::from_pem(key_chain.as_bytes()) - .change_context(ApiClientError::CertificateDecodeFailed) -} - -pub fn create_certificate( - encoded_certificate: masking::Secret<String>, -) -> Result<Vec<reqwest::Certificate>, error_stack::Report<ApiClientError>> { - let decoded_certificate = BASE64_ENGINE - .decode(encoded_certificate.expose()) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let certificate = String::from_utf8(decoded_certificate) - .change_context(ApiClientError::CertificateDecodeFailed)?; - reqwest::Certificate::from_pem_bundle(certificate.as_bytes()) - .change_context(ApiClientError::CertificateDecodeFailed) -} - pub trait RequestBuilder: Send + Sync { fn json(&mut self, body: serde_json::Value); fn url_encoded_form(&mut self, body: serde_json::Value); @@ -196,7 +77,8 @@ pub struct ProxyClient { impl ProxyClient { pub fn new(proxy_config: &Proxy) -> CustomResult<Self, ApiClientError> { - let client = get_client_builder(proxy_config)? + let client = client::get_client_builder(proxy_config) + .switch()? .build() .change_context(ApiClientError::InvalidProxyConfiguration)?; Ok(Self { @@ -213,9 +95,10 @@ impl ProxyClient { ) -> CustomResult<reqwest::Client, ApiClientError> { match (client_certificate, client_certificate_key) { (Some(certificate), Some(certificate_key)) => { - let client_builder = get_client_builder(&self.proxy_config)?; + let client_builder = client::get_client_builder(&self.proxy_config).switch()?; let identity = - create_identity_from_certificate_and_key(certificate, certificate_key)?; + client::create_identity_from_certificate_and_key(certificate, certificate_key) + .switch()?; Ok(client_builder .identity(identity) .build() @@ -314,7 +197,9 @@ impl ApiClient for ProxyClient { option_timeout_secs: Option<u64>, _forward_to_kafka: bool, ) -> CustomResult<reqwest::Response, ApiClientError> { - crate::services::send_request(state, request, option_timeout_secs).await + http_client::send_request(&state.conf.proxy, request, option_timeout_secs) + .await + .switch() } fn add_request_id(&mut self, request_id: RequestId) { diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index ed53da0d971..7cf35ff0d87 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -1,48 +1,2 @@ -use std::str::FromStr; - pub use common_utils::request::ContentType; -use common_utils::request::Headers; -use error_stack::ResultExt; pub use masking::{Mask, Maskable}; -use router_env::{instrument, tracing}; - -use crate::core::errors::{self, CustomResult}; - -pub(super) trait HeaderExt { - fn construct_header_map( - self, - ) -> CustomResult<reqwest::header::HeaderMap, errors::ApiClientError>; -} - -impl HeaderExt for Headers { - fn construct_header_map( - self, - ) -> CustomResult<reqwest::header::HeaderMap, errors::ApiClientError> { - use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; - - self.into_iter().try_fold( - HeaderMap::new(), - |mut header_map, (header_name, header_value)| { - let header_name = HeaderName::from_str(&header_name) - .change_context(errors::ApiClientError::HeaderMapConstructionFailed)?; - let header_value = header_value.into_inner(); - let header_value = HeaderValue::from_str(&header_value) - .change_context(errors::ApiClientError::HeaderMapConstructionFailed)?; - header_map.append(header_name, header_value); - Ok(header_map) - }, - ) - } -} - -pub(super) trait RequestBuilderExt { - fn add_headers(self, headers: reqwest::header::HeaderMap) -> Self; -} - -impl RequestBuilderExt for reqwest::RequestBuilder { - #[instrument(skip_all)] - fn add_headers(mut self, headers: reqwest::header::HeaderMap) -> Self { - self = self.headers(headers); - self - } -} diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 0328ea988d4..73c42818439 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -320,15 +320,6 @@ pub fn get_link_with_token( email_url } - -pub fn get_base_url(state: &SessionState) -> &str { - if !state.conf.multitenancy.enabled { - &state.conf.user.base_url - } else { - &state.tenant.user.control_center_url - } -} - pub struct VerifyEmail { pub recipient_email: domain::UserEmail, pub settings: std::sync::Arc<configs::Settings>, @@ -576,7 +567,7 @@ impl BizEmailProd { state.conf.email.prod_intent_recipient_email.clone(), )?, settings: state.conf.clone(), - user_name: data.poc_name.unwrap_or_default().into(), + user_name: data.poc_name.unwrap_or_default(), poc_email: data.poc_email.unwrap_or_default(), legal_business_name: data.legal_business_name.unwrap_or_default(), business_location: data diff --git a/crates/router/src/services/openidconnect.rs b/crates/router/src/services/openidconnect.rs index c4dd0df6e13..f9a76a0ada2 100644 --- a/crates/router/src/services/openidconnect.rs +++ b/crates/router/src/services/openidconnect.rs @@ -1,4 +1,6 @@ +use common_utils::errors::ErrorSwitch; use error_stack::ResultExt; +use external_services::http_client::client; use masking::{ExposeInterface, Secret}; use oidc::TokenResponse; use openidconnect::{self as oidc, core as oidc_core}; @@ -9,7 +11,6 @@ use crate::{ consts, core::errors::{UserErrors, UserResult}, routes::SessionState, - services::api::client, types::domain::user::UserEmail, }; @@ -156,7 +157,7 @@ async fn get_oidc_reqwest_client( request: oidc::HttpRequest, ) -> Result<oidc::HttpResponse, ApiClientError> { let client = client::create_client(&state.conf.proxy, None, None) - .map_err(|e| e.current_context().to_owned())?; + .map_err(|e| e.current_context().switch())?; let mut request_builder = client .request(request.method, request.url) diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index ea3edd8dfc7..18e227912ef 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -380,3 +380,11 @@ pub fn generate_env_specific_merchant_id(value: String) -> UserResult<id_type::M Ok(id_type::MerchantId::new_from_unix_timestamp()) } } + +pub fn get_base_url(state: &SessionState) -> &str { + if !state.conf.multitenancy.enabled { + &state.conf.user.base_url + } else { + &state.tenant.user.control_center_url + } +} diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index 4df78847b39..51e862681ae 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -9,9 +9,12 @@ use crate::{ consts, errors, logger::error, routes::{metrics, SessionState}, - services::email::types::{self as email_types, ApiKeyExpiryReminder}, + services::email::types::ApiKeyExpiryReminder, types::{api, domain::UserEmail, storage}, - utils::{user::theme as theme_utils, OptionExt}, + utils::{ + user::{self as user_utils, theme as theme_utils}, + OptionExt, + }, }; pub struct ApiKeyExpiryWorkflow; @@ -110,7 +113,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { .email_client .clone() .compose_and_send_email( - email_types::get_base_url(state), + user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), )
2025-04-11T12:48:38Z
## Description <!-- Describe your changes in detail --> This PR includes - HubSpot proxy integration for `prod_intent` triggered from the dashboard - New CRM interface with two implementations: NoCrm and HubspotProxy. - Includes refactoring to move `http_client send_request` and `client` from the `router` module to `external_services` to support this integration. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Add hubspot tracking in dashboard prod intent #
1dabfe3e2c0d9b72e41a5bd61c5a394248b7997b
Through dashboard FE - SIgnin in dashboard - Create a prod intent for a merchant - This will trigger hubspot tracking from BE and this should be visible in hubspot dashboard
[ "Cargo.lock", "config/config.example.toml", "config/deployments/env_specific.toml", "crates/api_models/src/user/dashboard_metadata.rs", "crates/common_utils/src/consts.rs", "crates/external_services/Cargo.toml", "crates/external_services/src/crm.rs", "crates/external_services/src/http_client.rs", "crates/external_services/src/http_client/client.rs", "crates/external_services/src/http_client/metrics.rs", "crates/external_services/src/http_client/request.rs", "crates/external_services/src/hubspot_proxy.rs", "crates/external_services/src/lib.rs", "crates/hyperswitch_interfaces/src/crm.rs", "crates/hyperswitch_interfaces/src/errors.rs", "crates/hyperswitch_interfaces/src/lib.rs", "crates/hyperswitch_interfaces/src/types.rs", "crates/router/Cargo.toml", "crates/router/src/configs/defaults.rs", "crates/router/src/configs/secrets_transformers.rs", "crates/router/src/configs/settings.rs", "crates/router/src/consts.rs", "crates/router/src/core/admin.rs", "crates/router/src/core/connector_onboarding/paypal.rs", "crates/router/src/core/recon.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user/dashboard_metadata.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/metrics.rs", "crates/router/src/services/api.rs", "crates/router/src/services/api/client.rs", "crates/router/src/services/api/request.rs", "crates/router/src/services/email/types.rs", "crates/router/src/services/openidconnect.rs", "crates/router/src/utils/user.rs", "crates/router/src/workflows/api_key_expiry.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7796
Bug: open router integration of success rate based routing add an api integration with open-router service. * decide-gateway * update-gateway-score
diff --git a/config/config.example.toml b/config/config.example.toml index 11d64093ab6..0ff30da45f4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -969,4 +969,8 @@ primary_color = "#006DF9" background_color = "#FFFFFF" # Email background color [billing_connectors_payment_sync] -billing_connectors_which_require_payment_sync = "stripebilling, recurly" # List of billing connectors which has payment sync api call \ No newline at end of file +billing_connectors_which_require_payment_sync = "stripebilling, recurly" # List of billing connectors which has payment sync api call + +[open_router] +enabled = true # Enable or disable Open Router +url = "http://localhost:8080" # Open Router URL diff --git a/config/development.toml b/config/development.toml index 535850f0d9b..b2a9f7c7cbd 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1033,3 +1033,7 @@ background_color = "#FFFFFF" [platform] enabled = true + +[open_router] +enabled = false +url = "http://localhost:8080" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c8d01502899..05685fcc5fc 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -788,9 +788,9 @@ enabled = false global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } [multitenancy.tenants.public] -base_url = "http://localhost:8080" -schema = "public" -accounts_schema = "public" +base_url = "http://localhost:8080" +schema = "public" +accounts_schema = "public" redis_key_prefix = "" clickhouse_database = "default" @@ -874,3 +874,6 @@ background_color = "#FFFFFF" [platform] enabled = true + +[open_router] +enabled = false diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 171bcb67753..1d5bfd58467 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -23,6 +23,8 @@ pub mod gsm; pub mod health_check; pub mod locker_migration; pub mod mandates; +#[cfg(feature = "dynamic_routing")] +pub mod open_router; pub mod organization; pub mod payment_methods; pub mod payments; diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs new file mode 100644 index 00000000000..c33365df169 --- /dev/null +++ b/crates/api_models/src/open_router.rs @@ -0,0 +1,122 @@ +use std::{collections::HashMap, fmt::Debug}; + +use common_utils::{id_type, types::MinorUnit}; +pub use euclid::{ + dssa::types::EuclidAnalysable, + frontend::{ + ast, + dir::{DirKeyKind, EuclidDirFilter}, + }, +}; +use serde::{Deserialize, Serialize}; + +use crate::enums::{Currency, PaymentMethod, RoutableConnectors}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OpenRouterDecideGatewayRequest { + pub payment_info: PaymentInfo, + pub merchant_id: id_type::ProfileId, + pub eligible_gateway_list: Option<Vec<RoutableConnectors>>, + pub ranking_algorithm: Option<RankingAlgorithm>, + pub elimination_enabled: Option<bool>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum RankingAlgorithm { + SrBasedRouting, + PlBasedRouting, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInfo { + pub payment_id: id_type::PaymentId, + pub amount: MinorUnit, + pub currency: Currency, + // customerId: Option<ETCu::CustomerId>, + // preferredGateway: Option<ETG::Gateway>, + pub payment_type: String, + // metadata: Option<String>, + // internalMetadata: Option<String>, + // isEmi: Option<bool>, + // emiBank: Option<String>, + // emiTenure: Option<i32>, + pub payment_method_type: String, + pub payment_method: PaymentMethod, + // paymentSource: Option<String>, + // authType: Option<ETCa::txn_card_info::AuthType>, + // cardIssuerBankName: Option<String>, + // cardIsin: Option<String>, + // cardType: Option<ETCa::card_type::CardType>, + // cardSwitchProvider: Option<Secret<String>>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct DecidedGateway { + pub gateway_priority_map: Option<HashMap<String, f64>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct ErrorResponse { + pub status: String, + pub error_code: String, + pub error_message: String, + pub priority_logic_tag: Option<String>, + pub filter_wise_gateways: Option<serde_json::Value>, + pub error_info: UnifiedError, + pub is_dynamic_mga_enabled: bool, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct UnifiedError { + pub code: String, + pub user_message: String, + pub developer_message: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct UpdateScorePayload { + pub merchant_id: id_type::ProfileId, + pub gateway: RoutableConnectors, + pub status: TxnStatus, + pub payment_id: id_type::PaymentId, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum TxnStatus { + Started, + AuthenticationFailed, + JuspayDeclined, + PendingVBV, + VBVSuccessful, + Authorized, + AuthorizationFailed, + Charged, + Authorizing, + CODInitiated, + Voided, + VoidInitiated, + Nop, + CaptureInitiated, + CaptureFailed, + VoidFailed, + AutoRefunded, + PartialCharged, + ToBeCharged, + Pending, + Failure, + Declined, +} + +impl From<bool> for TxnStatus { + fn from(value: bool) -> Self { + match value { + true => Self::Charged, + _ => Self::Failure, + } + } +} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 7cd4ce2d4bd..1dfaf1e84ac 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -550,5 +550,6 @@ pub(crate) async fn fetch_raw_secrets( network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors, theme: conf.theme, platform: conf.platform, + open_router: conf.open_router, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 83591b15e36..de0bafcdd3d 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -139,8 +139,14 @@ pub struct Settings<S: SecretState> { pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, pub theme: ThemeSettings, pub platform: Platform, + pub open_router: OpenRouter, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct OpenRouter { + pub enabled: bool, + pub url: String, +} #[derive(Debug, Deserialize, Clone, Default)] pub struct Platform { pub enabled: bool, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index a574d84fdcb..622802a5b0a 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -407,6 +407,10 @@ pub enum RoutingError { ContractRoutingClientInitializationError, #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")] InvalidContractBasedConnectorLabel(String), + #[error("Failed to perform {algo} in open_router")] + OpenRouterCallFailed { algo: String }, + #[error("Error from open_router: {0}")] + OpenRouterError(String), } #[derive(Debug, Clone, thiserror::Error)] diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 38f4823e068..40b2e34d612 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -7268,6 +7268,9 @@ where .await .change_context(errors::ApiErrorResponse::InternalServerError)?; + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] + let payment_attempt = transaction_data.payment_attempt.clone(); + let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, @@ -7282,33 +7285,42 @@ where // dynamic success based connector selection #[cfg(all(feature = "v1", feature = "dynamic_routing"))] - let connectors = { - if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() { - let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo - .parse_value("DynamicRoutingAlgorithmRef") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?; - let dynamic_split = api_models::routing::RoutingVolumeSplit { - routing_type: api_models::routing::RoutingType::Dynamic, - split: dynamic_routing_config - .dynamic_routing_volume_split - .unwrap_or_default(), + let connectors = if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() { + let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo + .parse_value("DynamicRoutingAlgorithmRef") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?; + let dynamic_split = api_models::routing::RoutingVolumeSplit { + routing_type: api_models::routing::RoutingType::Dynamic, + split: dynamic_routing_config + .dynamic_routing_volume_split + .unwrap_or_default(), + }; + let static_split: api_models::routing::RoutingVolumeSplit = + api_models::routing::RoutingVolumeSplit { + routing_type: api_models::routing::RoutingType::Static, + split: consts::DYNAMIC_ROUTING_MAX_VOLUME + - dynamic_routing_config + .dynamic_routing_volume_split + .unwrap_or_default(), }; - let static_split: api_models::routing::RoutingVolumeSplit = - api_models::routing::RoutingVolumeSplit { - routing_type: api_models::routing::RoutingType::Static, - split: consts::DYNAMIC_ROUTING_MAX_VOLUME - - dynamic_routing_config - .dynamic_routing_volume_split - .unwrap_or_default(), - }; - let volume_split_vec = vec![dynamic_split, static_split]; - let routing_choice = - routing::perform_dynamic_routing_volume_split(volume_split_vec, None) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to perform volume split on routing type")?; + let volume_split_vec = vec![dynamic_split, static_split]; + let routing_choice = routing::perform_dynamic_routing_volume_split(volume_split_vec, None) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to perform volume split on routing type")?; - if routing_choice.routing_type.is_dynamic_routing() { + if routing_choice.routing_type.is_dynamic_routing() { + if state.conf.open_router.enabled { + routing::perform_open_routing( + state, + connectors.clone(), + business_profile, + payment_attempt, + ) + .await + .map_err(|e| logger::error!(open_routing_error=?e)) + .unwrap_or(connectors) + } else { let dynamic_routing_config_params_interpolator = routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_data.get_payment_attempt().payment_method, @@ -7350,12 +7362,12 @@ where .await .map_err(|e| logger::error!(dynamic_routing_error=?e)) .unwrap_or(connectors) - } else { - connectors } } else { connectors } + } else { + connectors }; let connector_data = connectors diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 889525ec6d5..4db49e8d44f 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -6,15 +6,21 @@ use std::collections::hash_map; use std::hash::{Hash, Hasher}; use std::{collections::HashMap, str::FromStr, sync::Arc}; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use api_models::routing as api_routing; use api_models::{ admin as admin_api, enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; -#[cfg(feature = "dynamic_routing")] -use common_utils::ext_traits::AsyncExt; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::{ + open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest}, + routing as api_routing, +}; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use common_utils::{ + ext_traits::{AsyncExt, BytesExt}, + request, +}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ @@ -48,11 +54,10 @@ use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE}; use crate::core::admin; #[cfg(feature = "payouts")] use crate::core::payouts; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use crate::{core::routing::transformers::OpenRouterDecideGatewayRequestExt, headers, services}; use crate::{ - core::{ - errors, errors as oss_errors, - routing::{self}, - }, + core::{errors, errors as oss_errors, routing}, logger, types::{ api::{self, routing as routing_types}, @@ -1484,6 +1489,53 @@ pub fn make_dsl_input_for_surcharge( Ok(backend_input) } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn perform_open_routing( + state: &SessionState, + routable_connectors: Vec<api_routing::RoutableConnectorChoice>, + profile: &domain::Profile, + payment_data: oss_storage::PaymentAttempt, +) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { + let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::RoutingError::DeserializationError { + from: "JSON".to_string(), + to: "DynamicRoutingAlgorithmRef".to_string(), + }) + .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? + .ok_or(errors::RoutingError::GenericNotFoundError { + field: "dynamic_routing_algorithm".to_string(), + })?; + + logger::debug!( + "performing dynamic_routing with open_router for profile {}", + profile.get_id().get_string_repr() + ); + + let connectors = dynamic_routing_algo_ref + .success_based_algorithm + .async_map(|algo| { + perform_success_based_routing_with_open_router( + state, + routable_connectors.clone(), + profile.get_id(), + algo, + payment_data, + ) + }) + .await + .transpose() + .inspect_err(|e| logger::error!(dynamic_routing_error=?e)) + .ok() + .flatten() + .unwrap_or(routable_connectors); + + Ok(connectors) +} + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn perform_dynamic_routing( state: &SessionState, @@ -1555,6 +1607,165 @@ pub async fn perform_dynamic_routing( Ok(connector_list) } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn perform_success_based_routing_with_open_router( + state: &SessionState, + mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>, + profile_id: &common_utils::id_type::ProfileId, + success_based_algo_ref: api_routing::SuccessBasedAlgorithm, + payment_attempt: oss_storage::PaymentAttempt, +) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { + if success_based_algo_ref.enabled_feature + == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection + { + logger::debug!( + "performing success_based_routing with open_router for profile {}", + profile_id.get_string_repr() + ); + + let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request( + payment_attempt, + routable_connectors + .iter() + .map(|gateway| gateway.connector) + .collect::<Vec<_>>(), + Some(or_types::RankingAlgorithm::SrBasedRouting), + ); + + let url = format!("{}/{}", &state.conf.open_router.url, "decide-gateway"); + let mut request = request::Request::new(services::Method::Post, &url); + request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header( + headers::X_TENANT_ID, + state.tenant.tenant_id.get_string_repr().to_owned().into(), + ); + request.set_body(request::RequestContent::Json(Box::new( + open_router_req_body, + ))); + + let response = services::call_connector_api(state, request, "open_router_sr_call") + .await + .change_context(errors::RoutingError::OpenRouterCallFailed { + algo: "success_rate".into(), + })?; + + let sr_sorted_connectors = match response { + Ok(resp) => { + let decided_gateway: DecidedGateway = resp + .response + .parse_struct("DecidedGateway") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + + if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map { + logger::debug!( + "Open router gateway_priority_map response: {:?}", + gateway_priority_map + ); + routable_connectors.sort_by(|connector_choice_a, connector_choice_b| { + let connector_choice_a_score = gateway_priority_map + .get(&connector_choice_a.connector.to_string()) + .copied() + .unwrap_or(0.0); + let connector_choice_b_score = gateway_priority_map + .get(&connector_choice_b.connector.to_string()) + .copied() + .unwrap_or(0.0); + connector_choice_b_score + .partial_cmp(&connector_choice_a_score) + .unwrap_or(std::cmp::Ordering::Equal) + }); + } + Ok(routable_connectors) + } + Err(err) => { + let err_resp: or_types::ErrorResponse = err + .response + .parse_struct("ErrorResponse") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + logger::error!("open_router_error_response: {:?}", err_resp); + Err(errors::RoutingError::OpenRouterError( + "Failed to perform success based routing in open router".into(), + )) + } + }?; + + Ok(sr_sorted_connectors) + } else { + Ok(routable_connectors) + } +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn update_success_rate_score_with_open_router( + state: &SessionState, + payment_connector: common_enums::RoutableConnectors, + profile_id: &common_utils::id_type::ProfileId, + payment_id: &common_utils::id_type::PaymentId, + payment_status: bool, +) -> RoutingResult<()> { + let open_router_req_body = or_types::UpdateScorePayload { + merchant_id: profile_id.clone(), + gateway: payment_connector, + status: payment_status.into(), + payment_id: payment_id.clone(), + }; + + let url = format!("{}/{}", &state.conf.open_router.url, "update-gateway-score"); + let mut request = request::Request::new(services::Method::Post, &url); + request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header( + headers::X_TENANT_ID, + state.tenant.tenant_id.get_string_repr().to_owned().into(), + ); + request.set_body(request::RequestContent::Json(Box::new( + open_router_req_body, + ))); + + let response = + services::call_connector_api(state, request, "open_router_update_gateway_score_call") + .await + .change_context(errors::RoutingError::OpenRouterCallFailed { + algo: "success_rate".into(), + })?; + + match response { + Ok(resp) => { + let update_score_resp = String::from_utf8(resp.response.to_vec()).change_context( + errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ), + )?; + + logger::debug!( + "Open router update_gateway_score response: {:?}", + update_score_resp + ); + + Ok(()) + } + Err(err) => { + let err_resp: or_types::ErrorResponse = err + .response + .parse_struct("ErrorResponse") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + logger::error!("open_router_error_response: {:?}", err_resp); + Err(errors::RoutingError::OpenRouterError( + "Failed to update gateway score for success based routing in open router".into(), + )) + } + }?; + + Ok(()) +} + /// success based dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index ec86102eba0..6bb0ba5878f 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -46,7 +46,10 @@ use crate::{ utils::StringExt, }; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] -use crate::{core::metrics as core_metrics, types::transformers::ForeignInto}; +use crate::{ + core::{metrics as core_metrics, routing}, + types::transformers::ForeignInto, +}; pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = "Success rate based dynamic routing algorithm"; pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = @@ -688,6 +691,28 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( }, )?; + let payment_status_attribute = + get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); + + let should_route_to_open_router = state.conf.open_router.enabled; + + if should_route_to_open_router { + routing::payments_routing::update_success_rate_score_with_open_router( + state, + common_enums::RoutableConnectors::from_str(payment_connector.as_str()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + profile_id, + &payment_attempt.payment_id, + payment_status_attribute == common_enums::AttemptStatus::Charged, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to update gateway score in open router service")?; + + return Ok(()); + } + let success_based_routing_configs = fetch_dynamic_routing_configs::< routing_types::SuccessBasedRoutingConfig, >( @@ -732,9 +757,6 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( "unable to calculate/fetch success rate from dynamic routing service", )?; - let payment_status_attribute = - get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); - let first_merchant_success_based_connector = &success_based_connectors .entity_scores_with_labels .first() @@ -932,6 +954,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( .attach_printable( "unable to update success based routing window in dynamic routing service", )?; + Ok(()) } else { Ok(()) diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs index 652422086b7..d73e0d28671 100644 --- a/crates/router/src/core/routing/transformers.rs +++ b/crates/router/src/core/routing/transformers.rs @@ -1,12 +1,18 @@ +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm}; use api_models::routing::{ MerchantRoutingAlgorithm, RoutingAlgorithm as Algorithm, RoutingAlgorithmKind, RoutingDictionaryRecord, }; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use common_enums::RoutableConnectors; use common_utils::ext_traits::ValueExt; use diesel_models::{ enums as storage_enums, routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata}, }; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; use crate::{ core::{errors, routing}, @@ -98,3 +104,39 @@ impl From<&routing::TransactionData<'_>> for storage_enums::TransactionType { } } } + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub trait OpenRouterDecideGatewayRequestExt { + fn construct_sr_request( + attempt: PaymentAttempt, + eligible_gateway_list: Vec<RoutableConnectors>, + ranking_algorithm: Option<RankingAlgorithm>, + ) -> Self + where + Self: Sized; +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { + fn construct_sr_request( + attempt: PaymentAttempt, + eligible_gateway_list: Vec<RoutableConnectors>, + ranking_algorithm: Option<RankingAlgorithm>, + ) -> Self { + Self { + payment_info: PaymentInfo { + payment_id: attempt.payment_id, + amount: attempt.net_amount.get_order_amount(), + currency: attempt.currency.unwrap_or(storage_enums::Currency::USD), + payment_type: "ORDER_PAYMENT".to_string(), + // payment_method_type: attempt.payment_method_type.clone().unwrap(), + payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt + payment_method: attempt.payment_method.unwrap_or_default(), + }, + merchant_id: attempt.profile_id, + eligible_gateway_list: Some(eligible_gateway_list), + ranking_algorithm, + elimination_enabled: None, + } + } +}
2025-04-11T09:33:58Z
## Description <!-- Describe your changes in detail --> This PR adds an api integration with open-router service. * decide-gateway * update-gateway-score ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
e677b1389f7ab2518f176e5c5cfcba44fc185bbc
Create merchant_account, api_key, mca 1. Enable SR for merchant ``` curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'api-key: dev_a4XMpNXd3Yriz5DPsiwU6UbxEkiRkXdqHhwnJPolnVhssLaDEbOg6f5kE6B2hx1f' ``` 2. Enable Volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/set_volume_split?split=100' \ --header 'api-key: dev_a4XMpNXd3Yriz5DPsiwU6UbxEkiRkXdqHhwnJPolnVhssLaDEbOg6f5kE6B2hx1f' ``` 3. Create a Payment Search for the log "Open router gateway_priority_map response" <img width="1360" alt="image" src="https://github.com/user-attachments/assets/b7c8e95e-3661-4097-bd25-3072148449ed" /> <img width="1364" alt="image" src="https://github.com/user-attachments/assets/be8ad1d1-38a8-408f-99c6-82816ae202fe" />
[ "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/lib.rs", "crates/api_models/src/open_router.rs", "crates/router/src/configs/secrets_transformers.rs", "crates/router/src/configs/settings.rs", "crates/router/src/core/errors.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/core/routing/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7792
Bug: Point v2 to v1 dashboard_metadata table Point v2 to v1 dashboard_metadata table Move dashboard_metadata into accounts_schema.
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index d98f834e7b5..34e9fb4530b 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -169,6 +169,7 @@ pub trait AccountsStorageInterface: + business_profile::ProfileInterface + merchant_connector_account::MerchantConnectorAccountInterface + merchant_key_store::MerchantKeyStoreInterface + + dashboard_metadata::DashboardMetadataInterface + 'static { } diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs index 4f1624f3457..1b6b7417ded 100644 --- a/crates/router/src/db/dashboard_metadata.rs +++ b/crates/router/src/db/dashboard_metadata.rs @@ -62,7 +62,7 @@ impl DashboardMetadataInterface for Store { &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_accounts_connection_write(self).await?; metadata .insert(&conn) .await @@ -78,7 +78,7 @@ impl DashboardMetadataInterface for Store { data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::update( &conn, user_id, @@ -99,7 +99,7 @@ impl DashboardMetadataInterface for Store { org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; + let conn = connection::pg_accounts_connection_read(self).await?; storage::DashboardMetadata::find_user_scoped_dashboard_metadata( &conn, user_id.to_owned(), @@ -118,7 +118,7 @@ impl DashboardMetadataInterface for Store { org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; + let conn = connection::pg_accounts_connection_read(self).await?; storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata( &conn, merchant_id.to_owned(), @@ -135,7 +135,7 @@ impl DashboardMetadataInterface for Store { user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id( &conn, user_id.to_owned(), @@ -152,7 +152,7 @@ impl DashboardMetadataInterface for Store { merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &conn, user_id.to_owned(),
2025-04-10T18:26:41Z
## Description <!-- Describe your changes in detail --> This PR moves the dashboard_metadata table to `accounts_schema` and points v2 to the v1 public schema - dashboard_metadata table. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To store all the data regarding dashboard_metadata in a common table irrespective of v1 and v2. #
c58e93bfdba4cbd70d69e6d3947e0e1c68504e7e
Tested by deploying this branch on v2 integ-router and hitting the following 2 API's. The entries from the POST API populated the integ v1 public schema - dashboard metadata table. <img width="1728" alt="image" src="https://github.com/user-attachments/assets/2b73d3ff-2055-438c-a7d6-f1d865b57403" /> The highlighted entry in the v1 public schema dashboard_metadata table is the entry populated by hitting the v2 API, given by the curl below. Hit the following curl: - The entry for ProdIntent should be created in v1 public schema - dashboard_metadata table. ```bash curl --location 'http://localhost:8080/v2/user/data' \ --header 'accept: */*' \ --header 'accept-language: en-US,en;q=0.9' \ --header 'api-key: hyperswitch' \ --header 'content-type: application/json' \ --header 'origin: https://app.hyperswitch.io' \ --header 'priority: u=1, i' \ --header 'referer: https://app.hyperswitch.io/dashboard/home' \ --header 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'sec-fetch-dest: empty' \ --header 'sec-fetch-mode: cors' \ --header 'sec-fetch-site: same-origin' \ --header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \ --header 'x-merchant-id: merchant_1715600622' \ --header 'x-profile-id: pro_CqAdpUQBUUam1n0g56mB' \ --header 'cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjY2YzZlYWQtMWUzZi00ZTY4LWI5NjQtMGNiZTdkMWQ0OTk4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjkzMzU5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDQ2NjE2Niwib3JnX2lkIjoib3JnX0hzNWNLM0RlSDByRTJGcTMwSmp5IiwicHJvZmlsZV9pZCI6InByb190Nml0cjE3TkR3cWJOdHV5OG44diIsInRlbmFudF9pZCI6InB1YmxpYyJ9.sckbBxvWK6MtuAAoi4rZaeOwfU2AibyLz8GR7ZcF0pc' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjY2YzZlYWQtMWUzZi00ZTY4LWI5NjQtMGNiZTdkMWQ0OTk4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjkzMzU5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDQ2NjE2Niwib3JnX2lkIjoib3JnX0hzNWNLM0RlSDByRTJGcTMwSmp5IiwicHJvZmlsZV9pZCI6InByb190Nml0cjE3TkR3cWJOdHV5OG44diIsInRlbmFudF9pZCI6InB1YmxpYyJ9.sckbBxvWK6MtuAAoi4rZaeOwfU2AibyLz8GR7ZcF0pc' \ --data-raw '{ "ProdIntent": { "poc_email": "[email protected]", "is_completed": true, "legal_business_name": "blueberry", "business_location": "IN", "business_website": "https://google.com", "poc_name": "berry", "comments": "tx123", "product_type": "vault" } }' ``` Expected Response: 200 OK, no body in the response The following curl is supposed to read data from v1 public schema dashboard_metadata table and return the entry whether or not a prod_intent has been raised for a particular merchant_account. ```bash curl --location 'http://localhost:8080/v2/user/data?keys=ProdIntent' \ --header 'X-Merchant-Id: ddcd_oBuAVsHl0XMLag9JsHCV' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2RlMDFhYWYtOWVkMi00YTY5LTg3YWItNWU1YmI2ZWFiNGQ5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQyMjEyMzQxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Mjk4MDgyOCwib3JnX2lkIjoib3JnX3pMQmRNTnpLaDZrNmhiT2tockdJIiwicHJvZmlsZV9pZCI6InByb19LWnhHZ21rUHFkMldQdXBFa2psWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.aD185AZEOcIjHnLnZZ9GJ2ujSHIdRPbPtrYhzNo0V4M' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'Referer: https://integ.hyperswitch.io/dashboard/v2/recon' \ --header 'sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"' \ --header 'X-Profile-Id: pro_UaxaxwTw4A0a9D0QNBrf' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: hyperswitch' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' ``` Expected Response: ```json [ { "ProdIntent": { "legal_business_name": "blueberry", "business_label": null, "business_location": "IN", "display_name": null, "poc_email": "[email protected]", "business_type": null, "business_identifier": null, "business_website": "https://google.com", "poc_name": "berry", "poc_contact": null, "comments": "tx123", "is_completed": true, "product_type": "vault" } } ] ```
[ "crates/router/src/db.rs", "crates/router/src/db/dashboard_metadata.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7790
Bug: Modify List Merchant Accounts in Org with org_id (v1) hotfix Modify List Merchant Accounts in Org with org_id (v1) as v2 merchant accounts will hav merchant_id as Null, and they cant be deserialized into v1. This will cause terminate_2fa API to fail and cant obtain the merchant_id required to generate the jwt token.
diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs index c40af7f6535..ab51953b6ef 100644 --- a/crates/diesel_models/src/query/merchant_account.rs +++ b/crates/diesel_models/src/query/merchant_account.rs @@ -1,4 +1,5 @@ -use diesel::{associations::HasTable, ExpressionMethods, Table}; +use common_types::consts::API_VERSION; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] @@ -101,7 +102,9 @@ impl MerchantAccount { _, >( conn, - dsl::organization_id.eq(organization_id.to_owned()), + dsl::organization_id + .eq(organization_id.to_owned()) + .and(dsl::version.eq(API_VERSION)), None, None, None,
2025-04-10T13:41:31Z
## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7782](https://github.com/juspay/hyperswitch/pull/7782) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
0a5d2495435ff737dd952c97e5dcd0fc52839258
[ "crates/diesel_models/src/query/merchant_account.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7789
Bug: ProdIntent Changes for v1 and v2 merchant accounts hotfix ProdIntent changes for providing context of product_type and also converting it into merchant-scope from user scope.
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index fa550d671fb..8e734d31b53 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -1,4 +1,4 @@ -use common_enums::CountryAlpha2; +use common_enums::{CountryAlpha2, MerchantProductType}; use common_utils::{id_type, pii}; use masking::Secret; use strum::EnumString; @@ -103,6 +103,8 @@ pub struct ProdIntent { pub poc_contact: Option<String>, pub comments: Option<String>, pub is_completed: bool, + #[serde(default)] + pub product_type: MerchantProductType, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs index d9c83312d6b..e5b3ef733c6 100644 --- a/crates/common_enums/src/enums/accounts.rs +++ b/crates/common_enums/src/enums/accounts.rs @@ -1,6 +1,7 @@ use serde; use utoipa::ToSchema; #[derive( + Copy, Default, Clone, Debug, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b9ebdf13028..91b20621da8 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2974,7 +2974,7 @@ pub async fn list_merchants_for_user_in_org( .map(|merchant_account| user_api::UserMerchantAccountResponse { merchant_name: merchant_account.merchant_name.clone(), merchant_id: merchant_account.get_id().to_owned(), - product_type: merchant_account.product_type.clone(), + product_type: merchant_account.product_type, version: merchant_account.version, }) .collect::<Vec<_>>(), diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index d79d155cba9..a4068fc4fad 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -38,7 +38,6 @@ pub async fn set_metadata( Ok(ApplicationResponse::StatusOk) } -#[cfg(feature = "v1")] pub async fn get_multiple_metadata( state: SessionState, user: UserFromToken, @@ -462,7 +461,7 @@ async fn insert_metadata( pii::Email::from_str(inner_poc_email) .change_context(UserErrors::EmailParsingError)?; } - let mut metadata = utils::insert_user_scoped_metadata_to_db( + let mut metadata = utils::insert_merchant_scoped_metadata_to_db( state, user.user_id.clone(), user.merchant_id.clone(), @@ -473,7 +472,7 @@ async fn insert_metadata( .await; if utils::is_update_required(&metadata) { - metadata = utils::update_user_scoped_metadata( + metadata = utils::update_merchant_scoped_metadata( state, user.user_id.clone(), user.merchant_id.clone(), @@ -500,7 +499,6 @@ async fn insert_metadata( EntityType::Merchant, ) .await?; - let email_contents = email_types::BizEmailProd::new( state, data, @@ -662,7 +660,6 @@ async fn fetch_metadata( Ok(dashboard_metadata) } -#[cfg(feature = "v1")] pub async fn backfill_metadata( state: &SessionState, user: &UserFromToken, @@ -705,6 +702,11 @@ pub async fn backfill_metadata( return Ok(None); }; + #[cfg(feature = "v1")] + let processor_name = mca.connector_name.clone(); + + #[cfg(feature = "v2")] + let processor_name = mca.connector_name.to_string().clone(); Some( insert_metadata( state, @@ -712,13 +714,14 @@ pub async fn backfill_metadata( DBEnum::StripeConnected, types::MetaData::StripeConnected(api::ProcessorConnected { processor_id: mca.get_id(), - processor_name: mca.connector_name, + processor_name, }), ) .await, ) .transpose() } + DBEnum::PaypalConnected => { let mca = if let Some(paypal_connected) = get_merchant_connector_account_by_name( state, @@ -745,6 +748,11 @@ pub async fn backfill_metadata( return Ok(None); }; + #[cfg(feature = "v1")] + let processor_name = mca.connector_name.clone(); + + #[cfg(feature = "v2")] + let processor_name = mca.connector_name.to_string().clone(); Some( insert_metadata( state, @@ -752,7 +760,7 @@ pub async fn backfill_metadata( DBEnum::PaypalConnected, types::MetaData::PaypalConnected(api::ProcessorConnected { processor_id: mca.get_id(), - processor_name: mca.connector_name, + processor_name, }), ) .await, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 2200567ddf9..1879d19de04 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2136,6 +2136,12 @@ impl User { ), ); + route = route.service( + web::resource("/data") + .route(web::get().to(user::get_multiple_dashboard_metadata)) + .route(web::post().to(user::set_dashboard_metadata)), + ); + route } } diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 1af22d0338a..d075048ddb6 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -197,7 +197,6 @@ pub async fn set_dashboard_metadata( .await } -#[cfg(feature = "v1")] pub async fn get_multiple_dashboard_metadata( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html index 3645c953a02..2c973f2d622 100644 --- a/crates/router/src/services/email/assets/bizemailprod.html +++ b/crates/router/src/services/email/assets/bizemailprod.html @@ -104,6 +104,10 @@ <strong>Business Website:</strong> {business_website} </li> + <li> + <strong>Product Type:</strong> + {product_type} + </li> </ol> </td> </tr> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 5f611bc1b3a..d663f72cec7 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,5 +1,5 @@ use api_models::user::dashboard_metadata::ProdIntent; -use common_enums::EntityType; +use common_enums::{EntityType, MerchantProductType}; use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; @@ -64,6 +64,7 @@ pub enum EmailBody { legal_business_name: String, business_location: String, business_website: String, + product_type: MerchantProductType, }, ReconActivation { user_name: String, @@ -199,6 +200,7 @@ pub mod html { legal_business_name, business_location, business_website, + product_type, } => { format!( include_str!("assets/bizemailprod.html"), @@ -207,6 +209,7 @@ pub mod html { business_location = business_location, business_website = business_website, username = user_name, + product_type = product_type ) } EmailBody::ProFeatureRequest { @@ -558,6 +561,7 @@ pub struct BizEmailProd { pub settings: std::sync::Arc<configs::Settings>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, + pub product_type: MerchantProductType, } impl BizEmailProd { @@ -582,6 +586,7 @@ impl BizEmailProd { business_website: data.business_website.unwrap_or_default(), theme_id, theme_config, + product_type: data.product_type, }) } } @@ -595,6 +600,7 @@ impl EmailData for BizEmailProd { legal_business_name: self.legal_business_name.clone(), business_location: self.business_location.clone(), business_website: self.business_website.clone(), + product_type: self.product_type, }); Ok(EmailContents { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 4854d1b4786..8bf177035ef 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -417,7 +417,7 @@ impl NewUserMerchant { } pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> { - self.product_type.clone() + self.product_type } pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { @@ -703,11 +703,18 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { } else { id_type::MerchantId::new_from_unix_timestamp() }; + let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, - company_name: Some(UserCompanyName::new(value.1.company_name.clone())?), - product_type: value.1.product_type.clone(), - new_organization: NewUserOrganization::from(value), + company_name: Some(UserCompanyName::new( + user_merchant_create.company_name.clone(), + )?), + product_type: user_merchant_create.product_type, + new_organization: NewUserOrganization::from(( + user_from_storage, + user_merchant_create, + user_from_token, + )), }) } } diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index c19b52b6f86..a91a3fe917b 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -218,10 +218,9 @@ pub fn separate_metadata_type_based_on_scope( | DBEnum::SetupWoocomWebhook | DBEnum::OnboardingSurvey | DBEnum::IsMultipleConfiguration - | DBEnum::ReconStatus => merchant_scoped.push(key), - DBEnum::Feedback | DBEnum::ProdIntent | DBEnum::IsChangePasswordRequired => { - user_scoped.push(key) - } + | DBEnum::ReconStatus + | DBEnum::ProdIntent => merchant_scoped.push(key), + DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key), } } (merchant_scoped, user_scoped)
2025-04-10T13:41:15Z
## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7638](https://github.com/juspay/hyperswitch/pull/7638) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
0676341b6bc34b26ec839c533664580b775e99a8
[ "crates/api_models/src/user/dashboard_metadata.rs", "crates/common_enums/src/enums/accounts.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user/dashboard_metadata.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/user.rs", "crates/router/src/services/email/assets/bizemailprod.html", "crates/router/src/services/email/types.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/utils/user/dashboard_metadata.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7767
Bug: Modify List Merchant Accounts in Org with org_id (v1) Modify List Merchant Accounts in Org with org_id (v1) as v2 merchant accounts will hav merchant_id as `Null`, and they cant be deserialized into v1. This will cause terminate_2fa API to fail and cant obtain the merchant_id required to generate the jwt token.
diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs index c40af7f6535..ab51953b6ef 100644 --- a/crates/diesel_models/src/query/merchant_account.rs +++ b/crates/diesel_models/src/query/merchant_account.rs @@ -1,4 +1,5 @@ -use diesel::{associations::HasTable, ExpressionMethods, Table}; +use common_types::consts::API_VERSION; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] @@ -101,7 +102,9 @@ impl MerchantAccount { _, >( conn, - dsl::organization_id.eq(organization_id.to_owned()), + dsl::organization_id + .eq(organization_id.to_owned()) + .and(dsl::version.eq(API_VERSION)), None, None, None,
2025-04-10T08:32:56Z
## Description <!-- Describe your changes in detail --> Modified the v1 merchant list query to list only v1 merchant accounts, v2 merchants cannot deserialize in v1 application code. This change is required, since now, both v1 and v2 merchant accounts are stored in the same schema. This will affect the following flows: - list merchant accounts for user in org - list merchant accounts (admin API) - get single merchant id (during sign-in, to create JWT token) - switch org for user ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fix the deserialization issues when listing merchant accounts using v1 routes. # #### List Merchant Accounts for User in Org: ```bash curl --location 'http://localhost:8080/user/list/merchant' \ --header 'x-feature: integ-custom' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' ``` #### Sign in and Terminate 2fa: (while sign-in, to create the jwt user-info token): - Sign-in: ```bash curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "[email protected]", "password": "Hyperswitch@123" }' ``` - Terminate 2fa: ```bash curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NDM5ODQ3NiwidGVuYW50X2lkIjoicHVibGljIn0.1p4cqrxgCDvPde5vq7nuuvApXQkaeoZX7ThvMFeiqFU' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' ``` #### Switch Org for User (for tenant level): ```bash curl --location 'https://integ-api.hyperswitch.io/user/switch/org' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' \ --data '{ "org_id": "some_org_id" }' ``` #### List Merchant Accounts (Admin API): ```bash curl --location 'https://integ.hyperswitch.io/api/accounts/list?organization_id=org_pEDRnaMediEZaJcU888G' \ --header 'api-key: <admin-api-key>' ```
7088fd565e426375d54c95e64e58ba6cadc414a7
Hit the following curls after creating a v1 merchant account and a v2 merchant account in the same organization. The following APIs should only return v1 merchant accounts in the organization (and not the v2 merchant accounts). #### List Merchant Accounts for User in Org: ```bash curl --location 'http://localhost:8080/user/list/merchant' \ --header 'x-feature: integ-custom' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' ``` #### Sign in and Terminate 2fa: (while sign-in, to create the jwt user-info token): - Sign-in: ```bash curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "[email protected]", "password": "Hyperswitch@123" }' ``` - Terminate 2fa: ```bash curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NDM5ODQ3NiwidGVuYW50X2lkIjoicHVibGljIn0.1p4cqrxgCDvPde5vq7nuuvApXQkaeoZX7ThvMFeiqFU' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' ``` #### Switch Org for User (for tenant level): ```bash curl --location 'https://integ-api.hyperswitch.io/user/switch/org' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' \ --data '{ "org_id": "some_org_id" }' ``` #### List Merchant Accounts (Admin API): ```bash curl --location 'https://integ.hyperswitch.io/api/accounts/list?organization_id=org_pEDRnaMediEZaJcU888G' \ --header 'api-key: <admin-api-key>' ```
[ "crates/diesel_models/src/query/merchant_account.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7778
Bug: [DOCS] Updated Intelligent router open api ### Feature Description Updated open api spec for Intelligent router ### Possible Implementation Updated open api spec for Intelligent router ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
2025-04-09T14:10:07Z
## Description <!-- Describe your changes in detail --> Updated open-api spec for Intelligent routing ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
ec147d5e7316c5fa5a5ac90ca7bc9318dc2dcaab
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/63adbc60-e89b-417f-ad4e-b8241ebdebbf" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/2a50d145-c50b-4aba-b9ce-e19a67416b6c" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/112ca2eb-d015-43e1-a916-6ea76227ab80" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/9714570d-c8e6-41ce-932d-3562a5fc9603" />
[]
juspay/hyperswitch
juspay__hyperswitch-7791
Bug: refactor(gsm): introduce `feature` and `feature_data` to gsm Refactor gsm to add `feature` and `feature_data` columns so that it case used to introduce new features
diff --git a/crates/api_models/src/gsm.rs b/crates/api_models/src/gsm.rs index 7ffc9c69413..1b2800d11ea 100644 --- a/crates/api_models/src/gsm.rs +++ b/crates/api_models/src/gsm.rs @@ -1,12 +1,12 @@ -use common_enums::ErrorCategory; use utoipa::ToSchema; -use crate::enums::Connector; +use crate::enums as api_enums; #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmCreateRequest { /// The connector through which payment has gone through - pub connector: Connector, + #[schema(value_type = Connector)] + pub connector: api_enums::Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector @@ -20,23 +20,41 @@ pub struct GsmCreateRequest { /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow - pub decision: GsmDecision, + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] + #[schema(value_type = GsmDecision)] + pub decision: api_enums::GsmDecision, /// indicates if step_up retry is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to - pub error_category: Option<ErrorCategory>, + #[schema(value_type = Option<ErrorCategory>)] + pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub clear_pan_possible: bool, + /// Indicates the GSM feature associated with the request, + /// such as retry mechanisms or other specific functionalities provided by the system. + #[schema(value_type = Option<GsmFeature>)] + pub feature: Option<api_enums::GsmFeature>, + /// Contains the data relevant to the specified GSM feature, if applicable. + /// For example, if the `feature` is `Retry`, this will include configuration + /// details specific to the retry behavior. + #[schema(value_type = Option<GsmFeatureData>)] + pub feature_data: Option<common_types::domain::GsmFeatureData>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmRetrieveRequest { /// The connector through which payment has gone through - pub connector: Connector, + #[schema(value_type = Connector)] + pub connector: api_enums::Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector @@ -47,28 +65,6 @@ pub struct GsmRetrieveRequest { pub message: String, } -#[derive( - Default, - Clone, - Copy, - Debug, - strum::Display, - PartialEq, - Eq, - serde::Serialize, - serde::Deserialize, - strum::EnumString, - ToSchema, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum GsmDecision { - Retry, - Requeue, - #[default] - DoDefault, -} - #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmUpdateRequest { /// The connector through which payment has gone through @@ -86,17 +82,34 @@ pub struct GsmUpdateRequest { /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow - pub decision: Option<GsmDecision>, + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] + #[schema(value_type = Option<GsmDecision>)] + pub decision: Option<api_enums::GsmDecision>, /// indicates if step_up retry is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub step_up_possible: Option<bool>, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to - pub error_category: Option<ErrorCategory>, + #[schema(value_type = Option<ErrorCategory>)] + pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub clear_pan_possible: Option<bool>, + /// Indicates the GSM feature associated with the request, + /// such as retry mechanisms or other specific functionalities provided by the system. + #[schema(value_type = Option<GsmFeature>)] + pub feature: Option<api_enums::GsmFeature>, + /// Contains the data relevant to the specified GSM feature, if applicable. + /// For example, if the `feature` is `Retry`, this will include configuration + /// details specific to the retry behavior. + #[schema(value_type = Option<GsmFeatureData>)] + pub feature_data: Option<common_types::domain::GsmFeatureData>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -143,15 +156,32 @@ pub struct GsmResponse { /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow - pub decision: String, + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] + #[schema(value_type = GsmDecision)] + pub decision: api_enums::GsmDecision, /// indicates if step_up retry is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to - pub error_category: Option<ErrorCategory>, + #[schema(value_type = Option<ErrorCategory>)] + pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub clear_pan_possible: bool, + /// Indicates the GSM feature associated with the request, + /// such as retry mechanisms or other specific functionalities provided by the system. + #[schema(value_type = GsmFeature)] + pub feature: api_enums::GsmFeature, + /// Contains the data relevant to the specified GSM feature, if applicable. + /// For example, if the `feature` is `Retry`, this will include configuration + /// details specific to the retry behavior. + #[schema(value_type = GsmFeatureData)] + pub feature_data: Option<common_types::domain::GsmFeatureData>, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 4daa373c016..6b35bbaf9ce 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -267,6 +267,46 @@ pub enum RevenueRecoveryAlgorithmType { Cascading, } +#[derive( + Default, + Clone, + Copy, + Debug, + strum::Display, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::EnumString, + ToSchema, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum GsmDecision { + Retry, + #[default] + DoDefault, +} + +#[derive( + Clone, + Copy, + Debug, + strum::Display, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::EnumString, + ToSchema, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +#[router_derive::diesel_enum(storage_type = "text")] +pub enum GsmFeature { + Retry, +} + /// Specifies the type of cardholder authentication to be applied for a payment. /// /// - `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer. diff --git a/crates/common_types/src/domain.rs b/crates/common_types/src/domain.rs index e800cb9cb61..3836aaabe75 100644 --- a/crates/common_types/src/domain.rs +++ b/crates/common_types/src/domain.rs @@ -113,3 +113,71 @@ pub struct ConnectorResponseData { /// Stringified connector raw response body pub raw_connector_response: Option<Secret<String>>, } + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, AsExpression, ToSchema)] +#[diesel(sql_type = Jsonb)] +#[serde(rename_all = "snake_case")] +/// Contains the data relevant to the specified GSM feature, if applicable. +/// For example, if the `feature` is `Retry`, this will include configuration +/// details specific to the retry behavior. +pub enum GsmFeatureData { + /// Represents the data associated with a retry feature in GSM. + Retry(RetryFeatureData), +} + +/// Represents the data associated with a retry feature in GSM. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, AsExpression, ToSchema)] +#[diesel(sql_type = Jsonb)] +pub struct RetryFeatureData { + /// indicates if step_up retry is possible + pub step_up_possible: bool, + /// indicates if retry with pan is possible + pub clear_pan_possible: bool, + /// indicates if retry with alternate network possible + pub alternate_network_possible: bool, + /// decision to be taken for auto retries flow + #[schema(value_type = GsmDecision)] + pub decision: common_enums::GsmDecision, +} + +impl_to_sql_from_sql_json!(GsmFeatureData); +impl_to_sql_from_sql_json!(RetryFeatureData); + +impl GsmFeatureData { + /// Retrieves the retry feature data if it exists. + pub fn get_retry_feature_data(&self) -> Option<RetryFeatureData> { + match self { + Self::Retry(data) => Some(data.clone()), + } + } + + /// Retrieves the decision from the retry feature data. + pub fn get_decision(&self) -> common_enums::GsmDecision { + match self { + Self::Retry(data) => data.decision, + } + } +} + +/// Implementation of methods for `RetryFeatureData` +impl RetryFeatureData { + /// Checks if step-up retry is possible. + pub fn is_step_up_possible(&self) -> bool { + self.step_up_possible + } + + /// Checks if retry with PAN is possible. + pub fn is_clear_pan_possible(&self) -> bool { + self.clear_pan_possible + } + + /// Checks if retry with alternate network is possible. + pub fn is_alternate_network_possible(&self) -> bool { + self.alternate_network_possible + } + + /// Retrieves the decision to be taken for auto retries flow. + pub fn get_decision(&self) -> common_enums::GsmDecision { + self.decision + } +} diff --git a/crates/diesel_models/src/gsm.rs b/crates/diesel_models/src/gsm.rs index 46583a5b22c..b75b0e6ce86 100644 --- a/crates/diesel_models/src/gsm.rs +++ b/crates/diesel_models/src/gsm.rs @@ -1,5 +1,4 @@ //! Gateway status mapping - use common_enums::ErrorCategory; use common_utils::{ custom_serde, @@ -15,8 +14,6 @@ use crate::schema::gateway_status_map; Debug, Eq, PartialEq, - Ord, - PartialOrd, router_derive::DebugAsDisplay, Identifiable, Queryable, @@ -42,6 +39,8 @@ pub struct GatewayStatusMap { pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: bool, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable)] @@ -60,6 +59,8 @@ pub struct GatewayStatusMappingNew { pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: bool, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, } #[derive( @@ -81,6 +82,8 @@ pub struct GatewayStatusMapperUpdateInternal { pub error_category: Option<ErrorCategory>, pub last_modified: PrimitiveDateTime, pub clear_pan_possible: Option<bool>, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, } #[derive(Debug)] @@ -93,6 +96,8 @@ pub struct GatewayStatusMappingUpdate { pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: Option<bool>, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, } impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { @@ -106,6 +111,8 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { unified_message, error_category, clear_pan_possible, + feature_data, + feature, } = value; Self { status, @@ -122,6 +129,8 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { code: None, message: None, clear_pan_possible, + feature_data, + feature, } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6788f478274..c141f765536 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -595,6 +595,9 @@ diesel::table! { #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, + feature_data -> Nullable<Jsonb>, + #[max_length = 64] + feature -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index c5579b6c67b..e434e43b2c6 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -607,6 +607,9 @@ diesel::table! { #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, + feature_data -> Nullable<Jsonb>, + #[max_length = 64] + feature -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/gsm.rs b/crates/hyperswitch_domain_models/src/gsm.rs new file mode 100644 index 00000000000..59319c89e5d --- /dev/null +++ b/crates/hyperswitch_domain_models/src/gsm.rs @@ -0,0 +1,129 @@ +use common_utils::{errors::ValidationError, ext_traits::StringExt}; +use serde::{self, Deserialize, Serialize}; + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct GatewayStatusMap { + pub connector: String, + pub flow: String, + pub sub_flow: String, + pub code: String, + pub message: String, + pub status: String, + pub router_error: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub error_category: Option<common_enums::ErrorCategory>, + pub feature_data: common_types::domain::GsmFeatureData, + pub feature: common_enums::GsmFeature, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct GatewayStatusMappingUpdate { + pub status: Option<String>, + pub router_error: Option<Option<String>>, + pub decision: Option<common_enums::GsmDecision>, + pub step_up_possible: Option<bool>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub error_category: Option<common_enums::ErrorCategory>, + pub clear_pan_possible: Option<bool>, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, +} + +impl TryFrom<GatewayStatusMap> for diesel_models::gsm::GatewayStatusMappingNew { + type Error = error_stack::Report<ValidationError>; + + fn try_from(value: GatewayStatusMap) -> Result<Self, Self::Error> { + Ok(Self { + connector: value.connector.to_string(), + flow: value.flow, + sub_flow: value.sub_flow, + code: value.code, + message: value.message, + status: value.status.clone(), + router_error: value.router_error, + decision: value.feature_data.get_decision().to_string(), + step_up_possible: value + .feature_data + .get_retry_feature_data() + .map(|retry_feature_data| retry_feature_data.is_step_up_possible()) + .unwrap_or(false), + unified_code: value.unified_code, + unified_message: value.unified_message, + error_category: value.error_category, + clear_pan_possible: value + .feature_data + .get_retry_feature_data() + .map(|retry_feature_data| retry_feature_data.is_clear_pan_possible()) + .unwrap_or(false), + feature_data: Some(value.feature_data), + feature: Some(value.feature), + }) + } +} + +impl TryFrom<GatewayStatusMappingUpdate> for diesel_models::gsm::GatewayStatusMappingUpdate { + type Error = error_stack::Report<ValidationError>; + + fn try_from(value: GatewayStatusMappingUpdate) -> Result<Self, Self::Error> { + Ok(Self { + status: value.status, + router_error: value.router_error, + decision: value.decision.map(|gsm_decision| gsm_decision.to_string()), + step_up_possible: value.step_up_possible, + unified_code: value.unified_code, + unified_message: value.unified_message, + error_category: value.error_category, + clear_pan_possible: value.clear_pan_possible, + feature_data: value.feature_data, + feature: value.feature, + }) + } +} + +impl TryFrom<diesel_models::gsm::GatewayStatusMap> for GatewayStatusMap { + type Error = ValidationError; + + fn try_from(item: diesel_models::gsm::GatewayStatusMap) -> Result<Self, Self::Error> { + let decision = + StringExt::<common_enums::GsmDecision>::parse_enum(item.decision, "GsmDecision") + .map_err(|_| ValidationError::InvalidValue { + message: "Failed to parse GsmDecision".to_string(), + })?; + let db_feature_data = item.feature_data; + + // The only case where `FeatureData` can be null is for legacy records + // (i.e., records created before `FeatureData` and related features were introduced). + // At that time, the only supported feature was `Retry`, so it's safe to default to it. + let feature_data = match db_feature_data { + Some(common_types::domain::GsmFeatureData::Retry(data)) => { + common_types::domain::GsmFeatureData::Retry(data) + } + None => common_types::domain::GsmFeatureData::Retry( + common_types::domain::RetryFeatureData { + step_up_possible: item.step_up_possible, + clear_pan_possible: item.clear_pan_possible, + alternate_network_possible: false, + decision, + }, + ), + }; + + let feature = item.feature.unwrap_or(common_enums::GsmFeature::Retry); + Ok(Self { + connector: item.connector, + flow: item.flow, + sub_flow: item.sub_flow, + code: item.code, + message: item.message, + status: item.status, + router_error: item.router_error, + unified_code: item.unified_code, + unified_message: item.unified_message, + error_category: item.error_category, + feature_data, + feature, + }) + } +} diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index c7df1e3749b..30d0913a716 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -14,6 +14,7 @@ pub mod customer; pub mod disputes; pub mod errors; pub mod ext_traits; +pub mod gsm; pub mod mandates; pub mod merchant_account; pub mod merchant_connector_account; diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index efa92af978a..bb2937a653e 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -400,7 +400,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::gsm::GsmDeleteRequest, api_models::gsm::GsmDeleteResponse, api_models::gsm::GsmResponse, - api_models::gsm::GsmDecision, + api_models::enums::GsmDecision, + api_models::enums::GsmFeature, + common_types::domain::GsmFeatureData, + common_types::domain::RetryFeatureData, api_models::payments::AddressDetails, api_models::payments::BankDebitData, api_models::payments::AliPayQr, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 81e8f10dcdc..23f0fa2d0d2 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -352,7 +352,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::gsm::GsmDeleteRequest, api_models::gsm::GsmDeleteResponse, api_models::gsm::GsmResponse, - api_models::gsm::GsmDecision, + api_models::enums::GsmDecision, + api_models::enums::GsmFeature, + common_types::domain::GsmFeatureData, + common_types::domain::RetryFeatureData, api_models::payments::NullObject, api_models::payments::AddressDetails, api_models::payments::BankDebitData, diff --git a/crates/router/src/core/gsm.rs b/crates/router/src/core/gsm.rs index 6c544791a18..4bd93a4e0e0 100644 --- a/crates/router/src/core/gsm.rs +++ b/crates/router/src/core/gsm.rs @@ -1,16 +1,12 @@ use api_models::gsm as gsm_api_types; -use diesel_models::gsm as storage; use error_stack::ResultExt; use router_env::{instrument, tracing}; use crate::{ - core::{ - errors, - errors::{RouterResponse, StorageErrorExt}, - }, + core::errors::{self, RouterResponse, StorageErrorExt}, db::gsm::GsmInterface, services, - types::transformers::ForeignInto, + types::transformers::{ForeignFrom, ForeignInto}, SessionState, }; @@ -55,6 +51,24 @@ pub async fn update_gsm_rule( gsm_request: gsm_api_types::GsmUpdateRequest, ) -> RouterResponse<gsm_api_types::GsmResponse> { let db = state.store.as_ref(); + let connector = gsm_request.connector.clone(); + let flow = gsm_request.flow.clone(); + let code = gsm_request.code.clone(); + let sub_flow = gsm_request.sub_flow.clone(); + let message = gsm_request.message.clone(); + + let gsm_db_record = + GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "GSM with given key does not exist in our records".to_string(), + })?; + + let inferred_feature_info = <( + common_enums::GsmFeature, + common_types::domain::GsmFeatureData, + )>::foreign_from((&gsm_request, gsm_db_record)); + let gsm_api_types::GsmUpdateRequest { connector, flow, @@ -69,6 +83,8 @@ pub async fn update_gsm_rule( unified_message, error_category, clear_pan_possible, + feature, + feature_data, } = gsm_request; GsmInterface::update_gsm_rule( db, @@ -77,15 +93,25 @@ pub async fn update_gsm_rule( sub_flow, code, message, - storage::GatewayStatusMappingUpdate { - decision: decision.map(|d| d.to_string()), + hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate { + decision, status, router_error: Some(router_error), - step_up_possible, + step_up_possible: feature_data + .as_ref() + .and_then(|feature_data| feature_data.get_retry_feature_data()) + .map(|retry_feature_data| retry_feature_data.is_step_up_possible()) + .or(step_up_possible), unified_code, unified_message, error_category, - clear_pan_possible, + clear_pan_possible: feature_data + .as_ref() + .and_then(|feature_data| feature_data.get_retry_feature_data()) + .map(|retry_feature_data| retry_feature_data.is_clear_pan_possible()) + .or(clear_pan_possible), + feature_data: feature_data.or(Some(inferred_feature_info.1)), + feature: feature.or(Some(inferred_feature_info.0)), }, ) .await diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 458fe4bc5b2..ca8a9708651 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -6441,7 +6441,7 @@ pub async fn get_gsm_record( error_message: Option<String>, connector_name: String, flow: String, -) -> Option<storage::gsm::GatewayStatusMap> { +) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> { let get_gsm = || async { state.store.find_gsm_rule( connector_name.clone(), diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index aafe25aea67..b435bd191ef 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -1,8 +1,8 @@ -use std::{str::FromStr, vec::IntoIter}; +use std::vec::IntoIter; use common_utils::{ext_traits::Encode, types::MinorUnit}; use diesel_models::enums as storage_enums; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use router_env::{ logger, tracing::{self, instrument}, @@ -65,10 +65,10 @@ where let mut initial_gsm = get_gsm(state, &router_data).await?; - //Check if step-up to threeDS is possible and merchant has enabled let step_up_possible = initial_gsm - .clone() - .map(|gsm| gsm.step_up_possible) + .as_ref() + .and_then(|data| data.feature_data.get_retry_feature_data()) + .map(|data| data.is_step_up_possible()) .unwrap_or(false); #[cfg(feature = "v1")] @@ -124,7 +124,7 @@ where }; match get_gsm_decision(gsm) { - api_models::gsm::GsmDecision::Retry => { + storage_enums::GsmDecision::Retry => { retries = get_retries( state, retries, @@ -150,11 +150,13 @@ where .map(|pmd| pmd.is_network_token_payment_method_data()) .unwrap_or(false); + let clear_pan_possible = initial_gsm + .and_then(|data| data.feature_data.get_retry_feature_data()) + .map(|data| data.is_clear_pan_possible()) + .unwrap_or(false); + let should_retry_with_pan = is_network_token - && initial_gsm - .as_ref() - .map(|gsm| gsm.clear_pan_possible) - .unwrap_or(false) + && clear_pan_possible && business_profile.is_clear_pan_retries_enabled; let (connector, routing_decision) = if should_retry_with_pan { @@ -195,14 +197,7 @@ where retries = retries.map(|i| i - 1); } - api_models::gsm::GsmDecision::Requeue => { - Err(report!(errors::ApiErrorResponse::NotImplemented { - message: errors::NotImplementedMessage::Reason( - "Requeue not implemented".to_string(), - ), - }))? - } - api_models::gsm::GsmDecision::DoDefault => break, + storage_enums::GsmDecision::DoDefault => break, } initial_gsm = None; } @@ -278,7 +273,7 @@ pub async fn get_retries( pub async fn get_gsm<F, FData>( state: &app::SessionState, router_data: &types::RouterData<F, FData, types::PaymentsResponseData>, -) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> { +) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> { let error_response = router_data.response.as_ref().err(); let error_code = error_response.map(|err| err.code.to_owned()); let error_message = error_response.map(|err| err.message.to_owned()); @@ -292,19 +287,11 @@ pub async fn get_gsm<F, FData>( #[instrument(skip_all)] pub fn get_gsm_decision( - option_gsm: Option<storage::gsm::GatewayStatusMap>, -) -> api_models::gsm::GsmDecision { + option_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>, +) -> storage_enums::GsmDecision { let option_gsm_decision = option_gsm - .and_then(|gsm| { - api_models::gsm::GsmDecision::from_str(gsm.decision.as_str()) - .map_err(|err| { - let api_error = report!(err).change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("gsm decision parsing failed"); - logger::warn!(get_gsm_decision_parse_error=?api_error, "error fetching gsm decision"); - api_error - }) - .ok() - }); + .as_ref() + .map(|gsm| gsm.feature_data.get_decision()); if option_gsm_decision.is_some() { metrics::AUTO_RETRY_GSM_MATCH_COUNT.add(1, &[]); diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index f1f8dad3a05..8a7f87fa60d 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1060,7 +1060,7 @@ pub async fn get_gsm_record( error_message: Option<String>, connector_name: Option<String>, flow: &str, -) -> Option<storage::gsm::GatewayStatusMap> { +) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> { let connector_name = connector_name.unwrap_or_default(); let get_gsm = || async { state.store.find_gsm_rule( diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs index 30100a580d4..e4579613605 100644 --- a/crates/router/src/core/payouts/retry.rs +++ b/crates/router/src/core/payouts/retry.rs @@ -1,7 +1,7 @@ -use std::{cmp::Ordering, str::FromStr, vec::IntoIter}; +use std::vec::IntoIter; use common_enums::PayoutRetryType; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use router_env::{ logger, tracing::{self, instrument}, @@ -38,7 +38,7 @@ pub async fn do_gsm_multiple_connector_actions( let gsm = get_gsm(state, &connector, payout_data).await?; match get_gsm_decision(gsm) { - api_models::gsm::GsmDecision::Retry => { + common_enums::GsmDecision::Retry => { retries = get_retries( state, retries, @@ -71,14 +71,7 @@ pub async fn do_gsm_multiple_connector_actions( retries = retries.map(|i| i - 1); } - api_models::gsm::GsmDecision::Requeue => { - Err(report!(errors::ApiErrorResponse::NotImplemented { - message: errors::NotImplementedMessage::Reason( - "Requeue not implemented".to_string(), - ), - }))? - } - api_models::gsm::GsmDecision::DoDefault => break, + common_enums::GsmDecision::DoDefault => break, } } Ok(()) @@ -102,13 +95,13 @@ pub async fn do_gsm_single_connector_actions( let gsm = get_gsm(state, &original_connector_data, payout_data).await?; // if the error config is same as previous, we break out of the loop - if let Ordering::Equal = gsm.cmp(&previous_gsm) { + if gsm == previous_gsm { break; } previous_gsm.clone_from(&gsm); match get_gsm_decision(gsm) { - api_models::gsm::GsmDecision::Retry => { + common_enums::GsmDecision::Retry => { retries = get_retries( state, retries, @@ -133,14 +126,7 @@ pub async fn do_gsm_single_connector_actions( retries = retries.map(|i| i - 1); } - api_models::gsm::GsmDecision::Requeue => { - Err(report!(errors::ApiErrorResponse::NotImplemented { - message: errors::NotImplementedMessage::Reason( - "Requeue not implemented".to_string(), - ), - }))? - } - api_models::gsm::GsmDecision::DoDefault => break, + common_enums::GsmDecision::DoDefault => break, } } Ok(()) @@ -182,7 +168,7 @@ pub async fn get_gsm( state: &app::SessionState, original_connector_data: &api::ConnectorData, payout_data: &PayoutData, -) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> { +) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> { let error_code = payout_data.payout_attempt.error_code.to_owned(); let error_message = payout_data.payout_attempt.error_message.to_owned(); let connector_name = Some(original_connector_data.connector_name.to_string()); @@ -199,19 +185,9 @@ pub async fn get_gsm( #[instrument(skip_all)] pub fn get_gsm_decision( - option_gsm: Option<storage::gsm::GatewayStatusMap>, -) -> api_models::gsm::GsmDecision { - let option_gsm_decision = option_gsm - .and_then(|gsm| { - api_models::gsm::GsmDecision::from_str(gsm.decision.as_str()) - .map_err(|err| { - let api_error = report!(err).change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("gsm decision parsing failed"); - logger::warn!(get_gsm_decision_parse_error=?api_error, "error fetching gsm decision"); - api_error - }) - .ok() - }); + option_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>, +) -> common_enums::GsmDecision { + let option_gsm_decision = option_gsm.map(|gsm| gsm.feature_data.get_decision()); if option_gsm_decision.is_some() { metrics::AUTO_PAYOUT_RETRY_GSM_MATCH_COUNT.add(1, &[]); diff --git a/crates/router/src/db/gsm.rs b/crates/router/src/db/gsm.rs index 1aa96e14c18..eb88eecd4c4 100644 --- a/crates/router/src/db/gsm.rs +++ b/crates/router/src/db/gsm.rs @@ -1,5 +1,5 @@ use diesel_models::gsm as storage; -use error_stack::report; +use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::MockDb; @@ -13,8 +13,8 @@ use crate::{ pub trait GsmInterface { async fn add_gsm_rule( &self, - rule: storage::GatewayStatusMappingNew, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; + rule: hyperswitch_domain_models::gsm::GatewayStatusMap, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn find_gsm_decision( &self, connector: String, @@ -30,7 +30,7 @@ pub trait GsmInterface { sub_flow: String, code: String, message: String, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn update_gsm_rule( &self, connector: String, @@ -38,8 +38,8 @@ pub trait GsmInterface { sub_flow: String, code: String, message: String, - data: storage::GatewayStatusMappingUpdate, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; + data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn delete_gsm_rule( &self, @@ -56,12 +56,19 @@ impl GsmInterface for Store { #[instrument(skip_all)] async fn add_gsm_rule( &self, - rule: storage::GatewayStatusMappingNew, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + rule: hyperswitch_domain_models::gsm::GatewayStatusMap, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - rule.insert(&conn) + let gsm_db_record = diesel_models::gsm::GatewayStatusMappingNew::try_from(rule) + .change_context(errors::StorageError::SerializationFailed) + .attach_printable("Failed to convert gsm domain models to diesel models")? + .insert(&conn) .await - .map_err(|error| report!(errors::StorageError::from(error))) + .map_err(|error| report!(errors::StorageError::from(error)))?; + + hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] @@ -89,11 +96,16 @@ impl GsmInterface for Store { sub_flow: String, code: String, message: String, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::GatewayStatusMap::find(&conn, connector, flow, sub_flow, code, message) - .await - .map_err(|error| report!(errors::StorageError::from(error))) + let gsm_db_record = + storage::GatewayStatusMap::find(&conn, connector, flow, sub_flow, code, message) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + + hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] @@ -104,12 +116,26 @@ impl GsmInterface for Store { sub_flow: String, code: String, message: String, - data: storage::GatewayStatusMappingUpdate, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::GatewayStatusMap::update(&conn, connector, flow, sub_flow, code, message, data) - .await - .map_err(|error| report!(errors::StorageError::from(error))) + let gsm_update_data = diesel_models::gsm::GatewayStatusMappingUpdate::try_from(data) + .change_context(errors::StorageError::SerializationFailed)?; + let gsm_db_record = storage::GatewayStatusMap::update( + &conn, + connector, + flow, + sub_flow, + code, + message, + gsm_update_data, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + + hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] @@ -132,8 +158,8 @@ impl GsmInterface for Store { impl GsmInterface for MockDb { async fn add_gsm_rule( &self, - _rule: storage::GatewayStatusMappingNew, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + _rule: hyperswitch_domain_models::gsm::GatewayStatusMap, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } @@ -155,7 +181,7 @@ impl GsmInterface for MockDb { _sub_flow: String, _code: String, _message: String, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } @@ -166,8 +192,8 @@ impl GsmInterface for MockDb { _sub_flow: String, _code: String, _message: String, - _data: storage::GatewayStatusMappingUpdate, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + _data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index b81e5c1f71c..412cc0a4a10 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3185,8 +3185,8 @@ impl RoutingAlgorithmInterface for KafkaStore { impl GsmInterface for KafkaStore { async fn add_gsm_rule( &self, - rule: storage::GatewayStatusMappingNew, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + rule: hyperswitch_domain_models::gsm::GatewayStatusMap, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store.add_gsm_rule(rule).await } @@ -3210,7 +3210,7 @@ impl GsmInterface for KafkaStore { sub_flow: String, code: String, message: String, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store .find_gsm_rule(connector, flow, sub_flow, code, message) .await @@ -3223,8 +3223,8 @@ impl GsmInterface for KafkaStore { sub_flow: String, code: String, message: String, - data: storage::GatewayStatusMappingUpdate, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store .update_gsm_rule(connector, flow, sub_flow, code, message, data) .await diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 7b38342a743..90f2a423595 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1586,42 +1586,129 @@ impl ForeignFrom<api_models::organization::OrganizationCreateRequest> } } -impl ForeignFrom<gsm_api_types::GsmCreateRequest> for storage::GatewayStatusMappingNew { +impl ForeignFrom<gsm_api_types::GsmCreateRequest> + for hyperswitch_domain_models::gsm::GatewayStatusMap +{ fn foreign_from(value: gsm_api_types::GsmCreateRequest) -> Self { + let inferred_feature_data = common_types::domain::GsmFeatureData::foreign_from(&value); Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, - decision: value.decision.to_string(), status: value.status, router_error: value.router_error, - step_up_possible: value.step_up_possible, unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, - clear_pan_possible: value.clear_pan_possible, + feature_data: value.feature_data.unwrap_or(inferred_feature_data), + feature: value.feature.unwrap_or(api_enums::GsmFeature::Retry), + } + } +} + +impl ForeignFrom<&gsm_api_types::GsmCreateRequest> for common_types::domain::GsmFeatureData { + fn foreign_from(value: &gsm_api_types::GsmCreateRequest) -> Self { + // Defaulting alternate_network_possible to false as it is provided only in the Retry feature + // If the retry feature is not used, we assume alternate network as false + let alternate_network_possible = false; + + match value.feature { + Some(api_enums::GsmFeature::Retry) | None => { + Self::Retry(common_types::domain::RetryFeatureData { + step_up_possible: value.step_up_possible, + clear_pan_possible: value.clear_pan_possible, + alternate_network_possible, + decision: value.decision, + }) + } + } + } +} + +impl + ForeignFrom<( + &gsm_api_types::GsmUpdateRequest, + hyperswitch_domain_models::gsm::GatewayStatusMap, + )> for (api_enums::GsmFeature, common_types::domain::GsmFeatureData) +{ + fn foreign_from( + (gsm_update_request, gsm_db_record): ( + &gsm_api_types::GsmUpdateRequest, + hyperswitch_domain_models::gsm::GatewayStatusMap, + ), + ) -> Self { + let gsm_db_record_infered_feature = match gsm_db_record.feature_data.get_decision() { + api_enums::GsmDecision::Retry | api_enums::GsmDecision::DoDefault => { + api_enums::GsmFeature::Retry + } + }; + + let gsm_feature = gsm_update_request + .feature + .unwrap_or(gsm_db_record_infered_feature); + + match gsm_feature { + api_enums::GsmFeature::Retry => { + let gsm_db_record_retry_feature_data = + gsm_db_record.feature_data.get_retry_feature_data(); + + let retry_feature_data = common_types::domain::GsmFeatureData::Retry( + common_types::domain::RetryFeatureData { + step_up_possible: gsm_update_request + .step_up_possible + .or(gsm_db_record_retry_feature_data + .clone() + .map(|data| data.step_up_possible)) + .unwrap_or_default(), + clear_pan_possible: gsm_update_request + .clear_pan_possible + .or(gsm_db_record_retry_feature_data + .clone() + .map(|data| data.clear_pan_possible)) + .unwrap_or_default(), + alternate_network_possible: gsm_db_record_retry_feature_data + .map(|data| data.alternate_network_possible) + .unwrap_or_default(), + decision: gsm_update_request + .decision + .or(Some(gsm_db_record.feature_data.get_decision())) + .unwrap_or_default(), + }, + ); + (api_enums::GsmFeature::Retry, retry_feature_data) + } } } } -impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse { - fn foreign_from(value: storage::GatewayStatusMap) -> Self { +impl ForeignFrom<hyperswitch_domain_models::gsm::GatewayStatusMap> for gsm_api_types::GsmResponse { + fn foreign_from(value: hyperswitch_domain_models::gsm::GatewayStatusMap) -> Self { Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, - decision: value.decision.to_string(), + decision: value.feature_data.get_decision(), status: value.status, router_error: value.router_error, - step_up_possible: value.step_up_possible, + step_up_possible: value + .feature_data + .get_retry_feature_data() + .map(|data| data.is_step_up_possible()) + .unwrap_or(false), unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, - clear_pan_possible: value.clear_pan_possible, + clear_pan_possible: value + .feature_data + .get_retry_feature_data() + .map(|data| data.is_clear_pan_possible()) + .unwrap_or(false), + feature_data: Some(value.feature_data), + feature: value.feature, } } } diff --git a/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/down.sql b/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/down.sql new file mode 100644 index 00000000000..35bcb7d37f1 --- /dev/null +++ b/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE gateway_status_map DROP COLUMN IF EXISTS feature_data, + DROP COLUMN IF EXISTS feature; \ No newline at end of file diff --git a/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/up.sql b/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/up.sql new file mode 100644 index 00000000000..1e53a532e8b --- /dev/null +++ b/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/up.sql @@ -0,0 +1,4 @@ +-- Your SQL goes here +ALTER TABLE gateway_status_map +ADD COLUMN IF NOT EXISTS feature_data JSONB DEFAULT NULL, + ADD COLUMN IF NOT EXISTS feature VARCHAR(64) DEFAULT NULL; \ No newline at end of file
2025-04-09T05:17:41Z
## Description <!-- Describe your changes in detail --> This pull request includes a number of changes to the `gsm` module across multiple files to introduce new features and improve the existing code structure. The most important changes include the addition of new fields and enums, refactoring of existing enums, and introducing domain models for gsm. ### Changes to `gsm` module: * `crates/api_models/src/gsm.rs`: * Added new fields `alternate_network_possible` and `feature` to `GsmCreateRequest`, `GsmUpdateRequest`, and `GsmResponse` structs. * `step_up_possible` and `clear_pan_possible` are made as optional in api contract these are retry feature specific data and might not be present for other features. * `crates/common_enums/src/enums.rs`: * Added new enum`GsmFeature` to handle GSM decision and feature data. * Remove `Requeue` as feature us not yet implemented ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> # ### Create gsm rule without passing feature and feature data ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "adyenplatform", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "alternate_network_possible": false }' ``` ``` { "connector": "adyenplatform", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "retry" } } } ``` ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` Db entry <img width="2334" height="239" alt="image" src="https://github.com/user-attachments/assets/fd177675-dd2f-41d5-abf4-3b6c28411cda" /> ### Update rule `"clear_pan_possible": false` ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } } ``` ### Test case of existing records (manually create db entries like the existing ones and try to update it) db entry showing feature and feature_data to be null <img width="1310" height="312" alt="image" src="https://github.com/user-attachments/assets/8a1af508-2899-4c56-a112-af37363542c5" /> -> update call will `"clear_pan_possible": true` ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "novalnet", "flow": "Authorize", "sub_flow": "sub_flow", "code": "525002", "message": "Personal Identity Card Number not correct", "status": "Failure", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` ``` { "connector": "novalnet", "flow": "Authorize", "sub_flow": "sub_flow", "code": "525002", "message": "Personal Identity Card Number not correct", "status": "Failure", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "retry" } } } ``` DB entry after update <img width="1267" height="326" alt="image" src="https://github.com/user-attachments/assets/421c4fe9-eb73-409b-9810-e7101be63bba" /> ### Test case for the new change where in which we pass feature and feature data in the request ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": true, "clear_pan_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } } ``` <img width="1221" height="336" alt="image" src="https://github.com/user-attachments/assets/8bd9e48b-4f7b-492a-aacc-9d6d8fd969c4" /> We can see that step_up_possible and clear_pan_possible has been passed as true in the root level whereas it has been passed as false in the feature_data. And in the application response clear_pan_possible and step_up_possible is false in both the places as the values in the feature_data takes precedence. Note :- Same goes for db state and update gsm call -> Update call ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "clear_pan_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "do_default" } } }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "do_default" } } } ``` <img width="1359" height="333" alt="image" src="https://github.com/user-attachments/assets/9e3252ab-4905-4113-a963-999dd6157932" /> -> Test a retry payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: dev_NZClQhIklvWYnqEzfkfdzGOynCohMCTnkbYrPN0HPkQbm6rTnngnthX51kLWDIn2' \ --data-raw '{ "amount": 1000000, "amount_to_capture": 1000000, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1753886032", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_cLWcRqZDJcOaiN3oyxJh", "merchant_id": "merchant_1753885328", "status": "succeeded", "amount": 1000000, "net_amount": 1000000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000000, "connector": "cybersource", "client_secret": "pay_cLWcRqZDJcOaiN3oyxJh_secret_CCZupjoT0zDE6m4s1OCu", "created": "2025-07-30T14:32:41.449Z", "currency": "USD", "customer_id": "cu_1753885961", "customer": { "id": "cu_1753885961", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "X", "codeRaw": "I1" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_eWHrgeRsB1CJo79hTJVt", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1753885961", "created_at": 1753885961, "expires": 1753889561, "secret": "epk_fa14f011aa934fb29ae59ecdcf6cdd86" }, "manual_retry_allowed": false, "connector_transaction_id": "7538859630876495904805", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_cLWcRqZDJcOaiN3oyxJh_2", "payment_link": null, "profile_id": "pro_OMlZtENVSWshV7Mh9NPv", "surcharge_details": null, "attempt_count": 2, "merchant_decision": null, "merchant_connector_id": "mca_jAKVTh39vFjuD4LN7ZuX", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-30T14:47:41.449Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-30T14:32:43.450Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ```
794dce168e6b4d280c9c742a6e8a3b3283e09602
### Create gsm rule without passing feature and feature data ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "adyenplatform", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "alternate_network_possible": false }' ``` ``` { "connector": "adyenplatform", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "retry" } } } ``` ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` Db entry <img width="2334" height="239" alt="image" src="https://github.com/user-attachments/assets/fd177675-dd2f-41d5-abf4-3b6c28411cda" /> ### Update rule `"clear_pan_possible": false` ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } } ``` ### Test case of existing records (manually create db entries like the existing ones and try to update it) db entry showing feature and feature_data to be null <img width="1310" height="312" alt="image" src="https://github.com/user-attachments/assets/8a1af508-2899-4c56-a112-af37363542c5" /> -> update call will `"clear_pan_possible": true` ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "novalnet", "flow": "Authorize", "sub_flow": "sub_flow", "code": "525002", "message": "Personal Identity Card Number not correct", "status": "Failure", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` ``` { "connector": "novalnet", "flow": "Authorize", "sub_flow": "sub_flow", "code": "525002", "message": "Personal Identity Card Number not correct", "status": "Failure", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "retry" } } } ``` DB entry after update <img width="1267" height="326" alt="image" src="https://github.com/user-attachments/assets/421c4fe9-eb73-409b-9810-e7101be63bba" /> ### Test case for the new change where in which we pass feature and feature data in the request ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": true, "clear_pan_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } } ``` <img width="1221" height="336" alt="image" src="https://github.com/user-attachments/assets/8bd9e48b-4f7b-492a-aacc-9d6d8fd969c4" /> We can see that step_up_possible and clear_pan_possible has been passed as true in the root level whereas it has been passed as false in the feature_data. And in the application response clear_pan_possible and step_up_possible is false in both the places as the values in the feature_data takes precedence. Note :- Same goes for db state and update gsm call -> Update call ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "clear_pan_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "do_default" } } }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "do_default" } } } ``` <img width="1359" height="333" alt="image" src="https://github.com/user-attachments/assets/9e3252ab-4905-4113-a963-999dd6157932" /> -> Test a retry payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: dev_NZClQhIklvWYnqEzfkfdzGOynCohMCTnkbYrPN0HPkQbm6rTnngnthX51kLWDIn2' \ --data-raw '{ "amount": 1000000, "amount_to_capture": 1000000, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1753886032", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_cLWcRqZDJcOaiN3oyxJh", "merchant_id": "merchant_1753885328", "status": "succeeded", "amount": 1000000, "net_amount": 1000000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000000, "connector": "cybersource", "client_secret": "pay_cLWcRqZDJcOaiN3oyxJh_secret_CCZupjoT0zDE6m4s1OCu", "created": "2025-07-30T14:32:41.449Z", "currency": "USD", "customer_id": "cu_1753885961", "customer": { "id": "cu_1753885961", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "X", "codeRaw": "I1" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_eWHrgeRsB1CJo79hTJVt", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1753885961", "created_at": 1753885961, "expires": 1753889561, "secret": "epk_fa14f011aa934fb29ae59ecdcf6cdd86" }, "manual_retry_allowed": false, "connector_transaction_id": "7538859630876495904805", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_cLWcRqZDJcOaiN3oyxJh_2", "payment_link": null, "profile_id": "pro_OMlZtENVSWshV7Mh9NPv", "surcharge_details": null, "attempt_count": 2, "merchant_decision": null, "merchant_connector_id": "mca_jAKVTh39vFjuD4LN7ZuX", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-30T14:47:41.449Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-30T14:32:43.450Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ```
[ "crates/api_models/src/gsm.rs", "crates/common_enums/src/enums.rs", "crates/common_types/src/domain.rs", "crates/diesel_models/src/gsm.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/hyperswitch_domain_models/src/gsm.rs", "crates/hyperswitch_domain_models/src/lib.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/openapi_v2.rs", "crates/router/src/core/gsm.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/retry.rs", "crates/router/src/core/payouts/helpers.rs", "crates/router/src/core/payouts/retry.rs", "crates/router/src/db/gsm.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/types/transformers.rs", "migrations/2025-04-07-133030_add_feature_data_column_to_gsm/down.sql", "migrations/2025-04-07-133030_add_feature_data_column_to_gsm/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7769
Bug: feat(vsaas): add processor_merchant_id and created_by column in payment_intents and payments_attempts for v1 Tracking issue #1: https://github.com/juspay/hyperswitch-control-center/issues/2544 Tracking issue #2: https://github.com/juspay/hyperswitch-control-center/issues/2546
diff --git a/crates/common_utils/src/macros.rs b/crates/common_utils/src/macros.rs index 2ab0560cd41..8dcffbb6643 100644 --- a/crates/common_utils/src/macros.rs +++ b/crates/common_utils/src/macros.rs @@ -437,3 +437,387 @@ macro_rules! type_name { .unwrap_or_default(); }; } + +/// **Note** Creates an enum wrapper that implements `FromStr`, `Display`, `Serialize`, and `Deserialize` +/// based on a specific string representation format: `"VariantName<delimiter>FieldValue"`. +/// It handles parsing errors by returning a dedicated `Invalid` variant. +/// *Note*: The macro adds `Invalid,` automatically. +/// +/// # Use Case +/// +/// This macro is designed for scenarios where you need an enum, with each variant +/// holding a single piece of associated data, to be easily convertible to and from +/// a simple string format. This is useful for cases where enum is serialized to key value pairs +/// +/// It avoids more complex serialization structures (like JSON objects `{"VariantName": value}`) +/// in favor of a plain string representation. +/// +/// # Input Enum Format and Constraints +/// +/// To use this macro, the enum definition must adhere to the following structure: +/// +/// 1. **Public Enum:** The enum must be declared as `pub enum EnumName { ... }`. +/// 2. **Struct Variants Only:** All variants must be struct variants (using `{}`). +/// 3. **Exactly One Field:** Each struct variant must contain *exactly one* named field. +/// * **Valid:** `VariantA { value: i32 }` +/// * **Invalid:** `VariantA(i32)` (tuple variant) +/// * **Invalid:** `VariantA` or `VariantA {}` (no field) +/// * **Invalid:** `VariantA { value: i32, other: bool }` (multiple fields) +/// 4. **Tag Delimiter:** The macro invocation must specify a `tag_delimeter` literal, +/// which is the character used to separate the variant name from the field data in +/// the string representation (e.g., `tag_delimeter = ":",`). +/// 5. **Field Type Requirements:** The type of the single field in each variant (`$field_ty`) +/// must implement: +/// * `core::str::FromStr`: To parse the field's data from the string part. +/// The `Err` type should ideally be convertible to a meaningful error, though the +/// macro currently uses a generic error message upon failure. +/// * `core::fmt::Display`: To convert the field's data into the string part. +/// * `serde::Serialize` and `serde::Deserialize<'de>`: Although the macro implements +/// custom `Serialize`/`Deserialize` for the *enum* using the string format, the field +/// type itself must satisfy these bounds if required elsewhere or by generic contexts. +/// The macro's implementations rely solely on `Display` and `FromStr` for the conversion. +/// 6. **Error Type:** This macro uses `core::convert::Infallible` as it never fails but gives +/// `Self::Invalid` variant. +/// +/// # Serialization and Deserialization (`serde`) +/// +/// When `serde` features are enabled and the necessary traits are derived or implemented, +/// this macro implements `Serialize` and `Deserialize` for the enum: +/// +/// **Serialization:** An enum value like `MyEnum::VariantA { value: 123 }` (with `tag_delimeter = ":",`) +/// will be serialized into the string `"VariantA:123"`. If serializing to JSON, this results +/// in a JSON string: `"\"VariantA:123\""`. +/// **Deserialization:** The macro expects a string matching the format `"VariantName<delimiter>FieldValue"`. +/// It uses the enum's `FromStr` implementation internally. When deserializing from JSON, it +/// expects a JSON string containing the correctly formatted value (e.g., `"\"VariantA:123\""`). +/// +/// # `Display` and `FromStr` +/// +/// **`Display`:** Formats valid variants to `"VariantName<delimiter>FieldValue"` and catch-all cases to `"Invalid"`. +/// **`FromStr`:** Parses `"VariantName<delimiter>FieldValue"` to the variant, or returns `Self::Invalid` +/// if the input string is malformed or `"Invalid"`. +/// +/// # Example +/// +/// ```rust +/// use std::str::FromStr; +/// +/// crate::impl_enum_str!( +/// tag_delimeter = ":", +/// #[derive(Debug, PartialEq, Clone)] // Add other derives as needed +/// pub enum Setting { +/// Timeout { duration_ms: u32 }, +/// Username { name: String }, +/// } +/// ); +/// // Note: The macro adds `Invalid,` automatically. +/// +/// fn main() { +/// // Display +/// let setting1 = Setting::Timeout { duration_ms: 5000 }; +/// assert_eq!(setting1.to_string(), "Timeout:5000"); +/// assert_eq!(Setting::Invalid.to_string(), "Invalid"); +/// +/// // FromStr (returns Self, not Result) +/// let parsed_setting: Setting = "Username:admin".parse().expect("Valid parse"); // parse() itself doesn't panic +/// assert_eq!(parsed_setting, Setting::Username { name: "admin".to_string() }); +/// +/// let invalid_format: Setting = "Timeout".parse().expect("Parse always returns Self"); +/// assert_eq!(invalid_format, Setting::Invalid); // Malformed input yields Invalid +/// +/// let bad_data: Setting = "Timeout:fast".parse().expect("Parse always returns Self"); +/// assert_eq!(bad_data, Setting::Invalid); // Bad field data yields Invalid +/// +/// let unknown_tag: Setting = "Unknown:abc".parse().expect("Parse always returns Self"); +/// assert_eq!(unknown_tag, Setting::Invalid); // Unknown tag yields Invalid +/// +/// let explicit_invalid: Setting = "Invalid".parse().expect("Parse always returns Self"); +/// assert_eq!(explicit_invalid, Setting::Invalid); // "Invalid" string yields Invalid +/// +/// // Serde (requires derive Serialize/Deserialize on Setting) +/// // let json_output = serde_json::to_string(&setting1).unwrap(); +/// // assert_eq!(json_output, "\"Timeout:5000\""); +/// // let invalid_json_output = serde_json::to_string(&Setting::Invalid).unwrap(); +/// // assert_eq!(invalid_json_output, "\"Invalid\""); +/// +/// // let deserialized: Setting = serde_json::from_str("\"Username:guest\"").unwrap(); +/// // assert_eq!(deserialized, Setting::Username { name: "guest".to_string() }); +/// // let deserialized_invalid: Setting = serde_json::from_str("\"Invalid\"").unwrap(); +/// // assert_eq!(deserialized_invalid, Setting::Invalid); +/// // let deserialized_malformed: Setting = serde_json::from_str("\"TimeoutFast\"").unwrap(); +/// // assert_eq!(deserialized_malformed, Setting::Invalid); // Malformed -> Invalid +/// } +/// +/// # // Mock macro definition for doctest purposes +/// # #[macro_export] macro_rules! impl_enum_str { ($($tt:tt)*) => { $($tt)* } } +/// ``` +#[macro_export] +macro_rules! impl_enum_str { + ( + tag_delimeter = $tag_delim:literal, + $(#[$enum_attr:meta])* + pub enum $enum_name:ident { + $( + $(#[$variant_attr:meta])* + $variant:ident { + $(#[$field_attr:meta])* + $field:ident : $field_ty:ty $(,)? + } + ),* $(,)? + } + ) => { + $(#[$enum_attr])* + pub enum $enum_name { + $( + $(#[$variant_attr])* + $variant { + $(#[$field_attr])* + $field : $field_ty + }, + )* + /// Represents a parsing failure. + Invalid, // Automatically add the Invalid variant + } + + // Implement FromStr - now returns Self, not Result + impl core::str::FromStr for $enum_name { + // No associated error type needed + type Err = core::convert::Infallible; // FromStr requires an Err type, use Infallible + + fn from_str(s: &str) -> Result<Self, Self::Err> { + // Check for explicit "Invalid" string first + if s == "Invalid" { + return Ok(Self::Invalid); + } + + let Some((tag, associated_data)) = s.split_once($tag_delim) else { + // Missing delimiter -> Invalid + return Ok(Self::Invalid); + }; + + let result = match tag { + $( + stringify!($variant) => { + // Try to parse the field data + match associated_data.parse::<$field_ty>() { + Ok(parsed_field) => { + // Success -> construct the variant + Self::$variant { $field: parsed_field } + }, + Err(_) => { + // Field parse failure -> Invalid + Self::Invalid + } + } + } + ),* + // Unknown tag -> Invalid + _ => Self::Invalid, + }; + Ok(result) // Always Ok because failure modes return Self::Invalid + } + } + + // Implement Serialize + impl ::serde::Serialize for $enum_name { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: ::serde::Serializer, + { + match self { + $( + Self::$variant { $field } => { + let s = format!("{}{}{}", stringify!($variant), $tag_delim, $field); + serializer.serialize_str(&s) + } + )* + // Handle Invalid variant + Self::Invalid => serializer.serialize_str("Invalid"), + } + } + } + + // Implement Deserialize + impl<'de> ::serde::Deserialize<'de> for $enum_name { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: ::serde::Deserializer<'de>, + { + struct EnumVisitor; + + impl<'de> ::serde::de::Visitor<'de> for EnumVisitor { + type Value = $enum_name; + + fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + formatter.write_str(concat!("a string like VariantName", $tag_delim, "field_data or 'Invalid'")) + } + + // Leverage the FromStr implementation which now returns Self::Invalid on failure + fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> + where + E: ::serde::de::Error, + { + // parse() now returns Result<Self, Infallible> + // We unwrap() the Ok because it's infallible. + Ok(value.parse::<$enum_name>().unwrap()) + } + + fn visit_string<E>(self, value: String) -> Result<Self::Value, E> + where + E: ::serde::de::Error, + { + Ok(value.parse::<$enum_name>().unwrap()) + } + } + + deserializer.deserialize_str(EnumVisitor) + } + } + + // Implement Display + impl core::fmt::Display for $enum_name { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + $( + Self::$variant { $field } => { + write!(f, "{}{}{}", stringify!($variant), $tag_delim, $field) + } + )* + // Handle Invalid variant + Self::Invalid => write!(f, "Invalid"), + } + } + } + }; +} + +// --- Tests --- +#[cfg(test)] +mod tests { + #![allow(clippy::panic, clippy::expect_used)] + + use serde_json::{json, Value as JsonValue}; + + use crate::impl_enum_str; + + impl_enum_str!( + tag_delimeter = ":", + #[derive(Debug, PartialEq, Clone)] + pub enum TestEnum { + VariantA { value: i32 }, + VariantB { text: String }, + VariantC { id: u64 }, + VariantJson { data: JsonValue }, + } // Note: Invalid variant is added automatically by the macro + ); + + #[test] + fn test_enum_from_str_ok() { + // Success cases just parse directly + let parsed_a: TestEnum = "VariantA:42".parse().unwrap(); // Unwrapping Infallible is fine + assert_eq!(parsed_a, TestEnum::VariantA { value: 42 }); + + let parsed_b: TestEnum = "VariantB:hello world".parse().unwrap(); + assert_eq!( + parsed_b, + TestEnum::VariantB { + text: "hello world".to_string() + } + ); + + let parsed_c: TestEnum = "VariantC:123456789012345".parse().unwrap(); + assert_eq!( + parsed_c, + TestEnum::VariantC { + id: 123456789012345 + } + ); + + let parsed_json: TestEnum = r#"VariantJson:{"ok":true}"#.parse().unwrap(); + assert_eq!( + parsed_json, + TestEnum::VariantJson { + data: json!({"ok": true}) + } + ); + } + + #[test] + fn test_enum_from_str_failures_yield_invalid() { + // Missing delimiter + let parsed: TestEnum = "VariantA".parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Unknown tag + let parsed: TestEnum = "UnknownVariant:123".parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Bad field data for i32 + let parsed: TestEnum = "VariantA:not_a_number".parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Bad field data for JsonValue + let parsed: TestEnum = r#"VariantJson:{"bad_json"#.parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Empty field data for non-string (e.g., i32) + let parsed: TestEnum = "VariantA:".parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Empty field data for string IS valid for String type + let parsed_str: TestEnum = "VariantB:".parse().unwrap(); + assert_eq!( + parsed_str, + TestEnum::VariantB { + text: "".to_string() + } + ); + + // Parsing the literal "Invalid" string + let parsed_invalid_str: TestEnum = "Invalid".parse().unwrap(); + assert_eq!(parsed_invalid_str, TestEnum::Invalid); + } + + #[test] + fn test_enum_display_and_serialize() { + // Display valid + let value_a = TestEnum::VariantA { value: 99 }; + assert_eq!(value_a.to_string(), "VariantA:99"); + // Serialize valid + let json_a = serde_json::to_string(&value_a).expect("Serialize A failed"); + assert_eq!(json_a, "\"VariantA:99\""); // Serializes to JSON string + + // Display Invalid + let value_invalid = TestEnum::Invalid; + assert_eq!(value_invalid.to_string(), "Invalid"); + // Serialize Invalid + let json_invalid = serde_json::to_string(&value_invalid).expect("Serialize Invalid failed"); + assert_eq!(json_invalid, "\"Invalid\""); // Serializes to JSON string "Invalid" + } + + #[test] + fn test_enum_deserialize() { + // Deserialize valid + let input_a = "\"VariantA:123\""; + let deserialized_a: TestEnum = serde_json::from_str(input_a).expect("Deserialize A failed"); + assert_eq!(deserialized_a, TestEnum::VariantA { value: 123 }); + + // Deserialize explicit "Invalid" + let input_invalid = "\"Invalid\""; + let deserialized_invalid: TestEnum = + serde_json::from_str(input_invalid).expect("Deserialize Invalid failed"); + assert_eq!(deserialized_invalid, TestEnum::Invalid); + + // Deserialize malformed string (according to macro rules) -> Invalid + let input_malformed = "\"VariantA_no_delimiter\""; + let deserialized_malformed: TestEnum = + serde_json::from_str(input_malformed).expect("Deserialize malformed should succeed"); + assert_eq!(deserialized_malformed, TestEnum::Invalid); + + // Deserialize string with bad field data -> Invalid + let input_bad_data = "\"VariantA:not_a_number\""; + let deserialized_bad_data: TestEnum = + serde_json::from_str(input_bad_data).expect("Deserialize bad data should succeed"); + assert_eq!(deserialized_bad_data, TestEnum::Invalid); + } +} diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 4b24cf281cb..e2cc195fe05 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -49,6 +49,7 @@ use crate::{ }, errors::{CustomResult, ParsingError, PercentageError, ValidationError}, fp_utils::when, + impl_enum_str, }; /// Represents Percentage Value between 0 and 100 both inclusive @@ -1348,3 +1349,22 @@ where self.0.to_sql(out) } } + +impl_enum_str!( + tag_delimeter = ":", + /// CreatedBy conveys the information about the creator (identifier) as well as the origin or + /// trigger (Api, Jwt) of the record. + #[derive(Eq, PartialEq, Debug, Clone)] + pub enum CreatedBy { + /// Api variant + Api { + /// merchant id of creator. + merchant_id: String, + }, + /// Jwt variant + Jwt { + /// user id of creator. + user_id: String, + }, + } +); diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 63f039c32f9..0a3c44deee1 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -89,6 +89,8 @@ pub struct PaymentAttempt { pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub processor_merchant_id: Option<id_type::MerchantId>, + pub created_by: Option<String>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, pub payment_method_subtype: storage_enums::PaymentMethodType, @@ -197,6 +199,8 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, + pub processor_merchant_id: Option<id_type::MerchantId>, + pub created_by: Option<String>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, } @@ -334,6 +338,8 @@ pub struct PaymentAttemptNew { pub network_decline_code: Option<String>, pub network_advice_code: Option<String>, pub network_error_message: Option<String>, + pub processor_merchant_id: Option<id_type::MerchantId>, + pub created_by: Option<String>, } #[cfg(feature = "v1")] @@ -411,6 +417,8 @@ pub struct PaymentAttemptNew { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<storage_enums::CardDiscovery>, + pub processor_merchant_id: Option<id_type::MerchantId>, + pub created_by: Option<String>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, } diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 7476639a47d..840c8e085b9 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -60,6 +60,8 @@ pub struct PaymentIntent { pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, @@ -148,6 +150,8 @@ pub struct PaymentIntent { pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] @@ -337,6 +341,8 @@ pub struct PaymentIntentNew { pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, } #[cfg(feature = "v1")] @@ -408,6 +414,8 @@ pub struct PaymentIntentNew { pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, } #[cfg(feature = "v2")] diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 802aa698a82..374b341a47e 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -933,6 +933,10 @@ diesel::table! { #[max_length = 64] issuer_error_code -> Nullable<Varchar>, issuer_error_message -> Nullable<Text>, + #[max_length = 64] + processor_merchant_id -> Nullable<Varchar>, + #[max_length = 255] + created_by -> Nullable<Varchar>, setup_future_usage_applied -> Nullable<FutureUsage>, } } @@ -1021,6 +1025,10 @@ diesel::table! { platform_merchant_id -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, + #[max_length = 64] + processor_merchant_id -> Nullable<Varchar>, + #[max_length = 255] + created_by -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index b9ca1c5da46..9a72f663e4f 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -874,6 +874,10 @@ diesel::table! { capture_before -> Nullable<Timestamp>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, + #[max_length = 64] + processor_merchant_id -> Nullable<Varchar>, + #[max_length = 255] + created_by -> Nullable<Varchar>, payment_method_type_v2 -> Varchar, #[max_length = 128] connector_payment_id -> Nullable<Varchar>, @@ -954,6 +958,10 @@ diesel::table! { force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, #[max_length = 64] + processor_merchant_id -> Nullable<Varchar>, + #[max_length = 255] + created_by -> Nullable<Varchar>, + #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 9212d416cb7..3779877abcb 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -210,6 +210,8 @@ pub struct PaymentAttemptBatchNew { pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, } @@ -293,6 +295,8 @@ impl PaymentAttemptBatchNew { extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, + processor_merchant_id: self.processor_merchant_id, + created_by: self.created_by, setup_future_usage_applied: self.setup_future_usage_applied, } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 90ba708c109..35b9f4a4613 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -15,7 +15,7 @@ use common_utils::{ errors::CustomResult, ext_traits::ValueExt, id_type, pii, - types::{keymanager::ToEncryptable, MinorUnit}, + types::{keymanager::ToEncryptable, CreatedBy, MinorUnit}, }; use diesel_models::payment_intent::TaxDetails; #[cfg(feature = "v2")] @@ -115,7 +115,8 @@ pub struct PaymentIntent { pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, - pub platform_merchant_id: Option<id_type::MerchantId>, + pub processor_merchant_id: id_type::MerchantId, + pub created_by: Option<CreatedBy>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } @@ -493,13 +494,15 @@ pub struct PaymentIntent { pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>, /// The straight through routing algorithm id that is used for this payment. This overrides the default routing algorithm that is configured in business profile. pub routing_algorithm_id: Option<id_type::RoutingId>, - /// Identifier for the platform merchant. - pub platform_merchant_id: Option<id_type::MerchantId>, /// Split Payment Data pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + /// merchant who owns the credentials of the processor, i.e. processor owner + pub processor_merchant_id: id_type::MerchantId, + /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) + pub created_by: Option<CreatedBy>, } #[cfg(feature = "v2")] @@ -655,11 +658,11 @@ impl PaymentIntent { .payment_link_config .map(ApiModelToDieselModelConvertor::convert_from), routing_algorithm_id: request.routing_algorithm_id, - platform_merchant_id: platform_merchant_id - .map(|merchant_account| merchant_account.get_id().to_owned()), split_payments: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, + processor_merchant_id: merchant_account.get_id().clone(), + created_by: None, }) } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index a074cca9b5d..77183dcf0d7 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -15,7 +15,7 @@ use common_utils::{ id_type, pii, types::{ keymanager::{self, KeyManagerState}, - ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit, + ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy, MinorUnit, }, }; use diesel_models::{ @@ -454,6 +454,10 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, + /// merchant who owns the credentials of the processor, i.e. processor owner + pub processor_merchant_id: id_type::MerchantId, + /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) + pub created_by: Option<CreatedBy>, } impl PaymentAttempt { @@ -583,6 +587,8 @@ impl PaymentAttempt { id, card_discovery: None, feature_metadata: None, + processor_merchant_id: payment_intent.merchant_id.clone(), + created_by: None, }) } @@ -670,6 +676,8 @@ impl PaymentAttempt { feature_metadata: None, id, card_discovery: None, + processor_merchant_id: payment_intent.merchant_id.clone(), + created_by: None, }) } @@ -767,6 +775,8 @@ impl PaymentAttempt { }), card_discovery: None, charges: None, + processor_merchant_id: payment_intent.merchant_id.clone(), + created_by: None, }) } @@ -859,6 +869,10 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, + /// merchant who owns the credentials of the processor, i.e. processor owner + pub processor_merchant_id: id_type::MerchantId, + /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) + pub created_by: Option<CreatedBy>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, } @@ -1109,6 +1123,10 @@ pub struct PaymentAttemptNew { pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, + /// merchant who owns the credentials of the processor, i.e. processor owner + pub processor_merchant_id: id_type::MerchantId, + /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) + pub created_by: Option<CreatedBy>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, } @@ -1859,6 +1877,8 @@ impl behaviour::Conversion for PaymentAttempt { setup_future_usage_applied: self.setup_future_usage_applied, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), }) } @@ -1877,7 +1897,7 @@ impl behaviour::Conversion for PaymentAttempt { .cloned(); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, net_amount: NetAmount::new( @@ -1947,6 +1967,12 @@ impl behaviour::Conversion for PaymentAttempt { charges: storage_model.charges, issuer_error_code: storage_model.issuer_error_code, issuer_error_message: storage_model.issuer_error_message, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, }) } @@ -2033,6 +2059,8 @@ impl behaviour::Conversion for PaymentAttempt { extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), setup_future_usage_applied: self.setup_future_usage_applied, }) } @@ -2103,6 +2131,8 @@ impl behaviour::Conversion for PaymentAttempt { card_discovery, charges, feature_metadata, + processor_merchant_id, + created_by, } = self; let AttemptAmountDetails { @@ -2195,6 +2225,8 @@ impl behaviour::Conversion for PaymentAttempt { network_error_message: error .as_ref() .and_then(|details| details.network_error_message.clone()), + processor_merchant_id: Some(processor_merchant_id), + created_by: created_by.map(|cb| cb.to_string()), }) } @@ -2266,7 +2298,7 @@ impl behaviour::Conversion for PaymentAttempt { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), id: storage_model.id, status: storage_model.status, amount_details, @@ -2311,6 +2343,12 @@ impl behaviour::Conversion for PaymentAttempt { connector_token_details: storage_model.connector_token_details, card_discovery: storage_model.card_discovery, feature_metadata: storage_model.feature_metadata.map(From::from), + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), }) } .await @@ -2367,6 +2405,8 @@ impl behaviour::Conversion for PaymentAttempt { card_discovery, charges, feature_metadata, + processor_merchant_id, + created_by, } = self; let card_network = payment_method_data @@ -2456,6 +2496,8 @@ impl behaviour::Conversion for PaymentAttempt { network_error_message: error_details .as_ref() .and_then(|details| details.network_error_message.clone()), + processor_merchant_id: Some(processor_merchant_id), + created_by: created_by.map(|cb| cb.to_string()), }) } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index a55b1b62fab..de2e0dd46c9 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -14,7 +14,7 @@ use common_utils::{ type_name, types::{ keymanager::{self, KeyManagerState, ToEncryptable}, - MinorUnit, + CreatedBy, MinorUnit, }, }; #[cfg(feature = "v2")] @@ -1602,10 +1602,11 @@ impl behaviour::Conversion for PaymentIntent { customer_present, routing_algorithm_id, payment_link_config, - platform_merchant_id, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, + processor_merchant_id, + created_by, } = self; Ok(DieselPaymentIntent { skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()), @@ -1684,10 +1685,12 @@ impl behaviour::Conversion for PaymentIntent { routing_algorithm_id, psd2_sca_exemption_type: None, request_extended_authorization: None, - platform_merchant_id, + platform_merchant_id: None, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, + processor_merchant_id: Some(processor_merchant_id), + created_by: created_by.map(|cb| cb.to_string()), }) } async fn convert_back( @@ -1761,7 +1764,7 @@ impl behaviour::Conversion for PaymentIntent { .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed)?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), status: storage_model.status, amount_details, amount_captured: storage_model.amount_captured, @@ -1819,10 +1822,15 @@ impl behaviour::Conversion for PaymentIntent { customer_present: storage_model.customer_present.into(), payment_link_config: storage_model.payment_link_config, routing_algorithm_id: storage_model.routing_algorithm_id, - platform_merchant_id: storage_model.platform_merchant_id, split_payments: storage_model.split_payments, force_3ds_challenge: storage_model.force_3ds_challenge, force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), }) } .await @@ -1903,9 +1911,11 @@ impl behaviour::Conversion for PaymentIntent { tax_details: amount_details.tax_details, enable_payment_link: Some(self.enable_payment_link.as_bool()), apply_mit_exemption: Some(self.apply_mit_exemption.as_bool()), - platform_merchant_id: self.platform_merchant_id, + platform_merchant_id: None, force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), }) } } @@ -1973,7 +1983,9 @@ impl behaviour::Conversion for PaymentIntent { skip_external_tax_calculation: self.skip_external_tax_calculation, request_extended_authorization: self.request_extended_authorization, psd2_sca_exemption_type: self.psd2_sca_exemption_type, - platform_merchant_id: self.platform_merchant_id, + platform_merchant_id: None, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, }) @@ -2011,7 +2023,7 @@ impl behaviour::Conversion for PaymentIntent { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), status: storage_model.status, amount: storage_model.amount, currency: storage_model.currency, @@ -2065,7 +2077,12 @@ impl behaviour::Conversion for PaymentIntent { skip_external_tax_calculation: storage_model.skip_external_tax_calculation, request_extended_authorization: storage_model.request_extended_authorization, psd2_sca_exemption_type: storage_model.psd2_sca_exemption_type, - platform_merchant_id: storage_model.platform_merchant_id, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), force_3ds_challenge: storage_model.force_3ds_challenge, force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger, }) @@ -2133,7 +2150,9 @@ impl behaviour::Conversion for PaymentIntent { skip_external_tax_calculation: self.skip_external_tax_calculation, request_extended_authorization: self.request_extended_authorization, psd2_sca_exemption_type: self.psd2_sca_exemption_type, - platform_merchant_id: self.platform_merchant_id, + platform_merchant_id: None, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, }) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 6953d1837d1..9d29c9ffaa4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3816,7 +3816,8 @@ mod tests { skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, - platform_merchant_id: None, + processor_merchant_id: id_type::MerchantId::default(), + created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; @@ -3890,7 +3891,8 @@ mod tests { skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, - platform_merchant_id: None, + processor_merchant_id: id_type::MerchantId::default(), + created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; @@ -3962,7 +3964,8 @@ mod tests { skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, - platform_merchant_id: None, + processor_merchant_id: id_type::MerchantId::default(), + created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; @@ -4500,6 +4503,8 @@ impl AttemptType { extended_authorization_applied: None, capture_before: None, card_discovery: None, + processor_merchant_id: old_payment_attempt.processor_merchant_id, + created_by: old_payment_attempt.created_by, setup_future_usage_applied: None, } } diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index c5837d5435b..377b930a572 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -11,7 +11,6 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentData}, - utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, @@ -46,7 +45,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>, > { @@ -71,9 +70,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[IntentStatus::Failed, IntentStatus::Succeeded], diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 46ae753232f..9d4ff7a5579 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -12,7 +12,6 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentData}, - utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, @@ -47,7 +46,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>, > { @@ -71,9 +70,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 2bde0d54976..68100cb6ece 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -11,7 +11,6 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, types::MultipleCaptureData}, - utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, @@ -46,7 +45,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, @@ -77,9 +76,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_capture_v2.rs b/crates/router/src/core/payments/operations/payment_capture_v2.rs index f69dd8de62c..4f9f9d31224 100644 --- a/crates/router/src/core/payments/operations/payment_capture_v2.rs +++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs @@ -12,7 +12,6 @@ use crate::{ helpers, operations::{self, ValidateStatusForOperation}, }, - utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, types::{ @@ -158,9 +157,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentCaptureData<F>, PaymentsCaptureReques .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - self.validate_status_for_operation(payment_intent.status)?; let active_attempt_id = payment_intent diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index ef90a2f2bef..bc7d743e3f8 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1366,6 +1366,8 @@ impl PaymentCreate { extended_authorization_applied: None, capture_before: None, card_discovery: None, + processor_merchant_id: merchant_id.to_owned(), + created_by: None, setup_future_usage_applied: request.setup_future_usage, }, additional_pm_data, @@ -1388,7 +1390,7 @@ impl PaymentCreate { active_attempt_id: String, profile_id: common_utils::id_type::ProfileId, session_expiry: PrimitiveDateTime, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, business_profile: &domain::Profile, ) -> RouterResult<storage::PaymentIntent> { let created_at @ modified_at @ last_synced = common_utils::date_time::now(); @@ -1580,8 +1582,8 @@ impl PaymentCreate { skip_external_tax_calculation, request_extended_authorization: request.request_extended_authorization, psd2_sca_exemption_type: request.psd2_sca_exemption_type, - platform_merchant_id: platform_merchant_account - .map(|platform_merchant_account| platform_merchant_account.get_id().to_owned()), + processor_merchant_id: merchant_account.get_id().to_owned(), + created_by: None, force_3ds_challenge: request.force_3ds_challenge, force_3ds_challenge_trigger: Some(force_3ds_challenge_trigger), }) diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index f15990d67b9..7e23cf6f84d 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -13,7 +13,6 @@ use crate::{ helpers, operations::{self, ValidateStatusForOperation}, }, - utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, types::{ @@ -135,9 +134,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetriev .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - let payment_attempt = payment_intent .active_attempt_id .as_ref() diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs index 2e00b19c757..764fa937c23 100644 --- a/crates/router/src/core/payments/operations/payment_get_intent.rs +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -10,7 +10,6 @@ use crate::{ core::{ errors::{self, RouterResult}, payments::{self, helpers, operations}, - utils::ValidatePlatformMerchant, }, db::errors::StorageErrorExt, routes::{app::ReqState, SessionState}, @@ -100,9 +99,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 82f09fc2075..0a230c3d110 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -11,7 +11,6 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, - utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, @@ -44,7 +43,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; @@ -67,9 +66,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 5b5155bbe33..aab887b2c03 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -218,7 +218,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieve ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { - get_tracker_for_sync( + Box::pin(get_tracker_for_sync( payment_id, merchant_account, key_store, @@ -227,7 +227,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieve self, merchant_account.storage_scheme, platform_merchant_account, - ) + )) .await } } diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index 5a283409edf..711115292ac 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -27,7 +27,6 @@ use crate::{ self, helpers, operations::{self, ValidateStatusForOperation}, }, - utils::ValidatePlatformMerchant, }, db::errors::StorageErrorExt, routes::{app::ReqState, SessionState}, @@ -150,9 +149,6 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - self.validate_status_for_operation(payment_intent.status)?; let PaymentsUpdateIntentRequest { diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index dc87ca9140c..dfec91875a9 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -15,7 +15,6 @@ use crate::{ self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails, PaymentAddress, }, - utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, services, @@ -49,7 +48,7 @@ impl<F: Send + Clone + Sync> key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, @@ -78,9 +77,6 @@ impl<F: Send + Clone + Sync> .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[enums::IntentStatus::RequiresCapture], diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 9e179d55524..fb907a0f282 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -685,6 +685,8 @@ pub fn make_new_payment_attempt( extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: old_payment_attempt.card_discovery, + processor_merchant_id: old_payment_attempt.processor_merchant_id, + created_by: old_payment_attempt.created_by, setup_future_usage_applied: setup_futture_usage_intent, // setup future usage is picked from intent for new payment attempt } } diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 87dce4ade0b..36e7423da18 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1837,36 +1837,3 @@ pub(crate) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::De (None, None) | (None, Some(_)) => Ok(()), } } - -pub(crate) trait ValidatePlatformMerchant { - fn get_platform_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId>; - - fn validate_platform_merchant( - &self, - auth_platform_merchant_id: Option<&common_utils::id_type::MerchantId>, - ) -> CustomResult<(), errors::ApiErrorResponse> { - let data_platform_merchant_id = self.get_platform_merchant_id(); - match (data_platform_merchant_id, auth_platform_merchant_id) { - (Some(data_platform_merchant_id), Some(auth_platform_merchant_id)) => { - common_utils::fp_utils::when( - data_platform_merchant_id != auth_platform_merchant_id, - || { - Err(report!(errors::ApiErrorResponse::PaymentNotFound)).attach_printable(format!( - "Data platform merchant id: {data_platform_merchant_id:?} does not match with auth platform merchant id: {auth_platform_merchant_id:?}")) - }, - ) - } - (Some(_), None) | (None, Some(_)) => { - Err(report!(errors::ApiErrorResponse::InvalidPlatformOperation)) - .attach_printable("Platform merchant id is missing in either data or auth") - } - (None, None) => Ok(()), - } - } -} - -impl ValidatePlatformMerchant for storage::PaymentIntent { - fn get_platform_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId> { - self.platform_merchant_id.as_ref() - } -} diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index b2ef401abcf..3a942f70e32 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -222,6 +222,8 @@ mod tests { extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), + processor_merchant_id: Default::default(), + created_by: None, setup_future_usage_applied: Default::default(), }; @@ -310,6 +312,8 @@ mod tests { extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), + processor_merchant_id: Default::default(), + created_by: None, setup_future_usage_applied: Default::default(), }; let store = state @@ -411,6 +415,8 @@ mod tests { extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), + processor_merchant_id: Default::default(), + created_by: None, setup_future_usage_applied: Default::default(), }; let store = state diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 3ec06e4cd91..4dceb77d58d 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -276,7 +276,8 @@ pub async fn generate_sample_data( skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, - platform_merchant_id: None, + processor_merchant_id: merchant_id.clone(), + created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; @@ -368,6 +369,8 @@ pub async fn generate_sample_data( extended_authorization_applied: None, capture_before: None, card_discovery: None, + processor_merchant_id: Some(merchant_id.clone()), + created_by: None, setup_future_usage_applied: None, }; diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 1b97970bf16..5ce1c8b7b54 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -232,6 +232,8 @@ impl PaymentAttemptInterface for MockDb { charges: None, issuer_error_code: None, issuer_error_message: None, + processor_merchant_id: payment_attempt.processor_merchant_id, + created_by: payment_attempt.created_by, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; payment_attempts.push(payment_attempt.clone()); diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 25d89cbd6eb..98a7a62dc6b 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -3,7 +3,7 @@ use common_utils::types::keymanager::KeyManagerState; use common_utils::{ errors::CustomResult, fallback_reverse_lookup_not_found, - types::{ConnectorTransactionId, ConnectorTransactionIdTrait}, + types::{ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy}, }; use diesel_models::{ enums::{ @@ -650,6 +650,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { charges: None, issuer_error_code: None, issuer_error_message: None, + processor_merchant_id: payment_attempt.processor_merchant_id.clone(), + created_by: payment_attempt.created_by.clone(), setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; @@ -1657,6 +1659,8 @@ impl DataModelExt for PaymentAttempt { setup_future_usage_applied: self.setup_future_usage_applied, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|created_by| created_by.to_string()), } } @@ -1673,7 +1677,7 @@ impl DataModelExt for PaymentAttempt { storage_model.tax_amount, ), payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, currency: storage_model.currency, @@ -1740,6 +1744,12 @@ impl DataModelExt for PaymentAttempt { charges: storage_model.charges, issuer_error_code: storage_model.issuer_error_code, issuer_error_message: storage_model.issuer_error_message, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, } } @@ -1827,6 +1837,8 @@ impl DataModelExt for PaymentAttemptNew { extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|created_by| created_by.to_string()), setup_future_usage_applied: self.setup_future_usage_applied, } } @@ -1841,7 +1853,7 @@ impl DataModelExt for PaymentAttemptNew { storage_model.tax_amount, ), payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, currency: storage_model.currency, @@ -1903,6 +1915,12 @@ impl DataModelExt for PaymentAttemptNew { extended_authorization_applied: storage_model.extended_authorization_applied, capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, } } diff --git a/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/down.sql b/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/down.sql new file mode 100644 index 00000000000..f56ae9f5ef5 --- /dev/null +++ b/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/down.sql @@ -0,0 +1,5 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent DROP COLUMN IF EXISTS processor_merchant_id; +ALTER TABLE payment_intent DROP COLUMN IF EXISTS created_by; +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS processor_merchant_id; +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS created_by; diff --git a/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/up.sql b/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/up.sql new file mode 100644 index 00000000000..52932564b4b --- /dev/null +++ b/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/up.sql @@ -0,0 +1,8 @@ +-- Your SQL goes here +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS processor_merchant_id VARCHAR(64); +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS created_by VARCHAR(255); +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS processor_merchant_id VARCHAR(64); +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS created_by VARCHAR(255); +-- This backfill should be executed again after deployment. +UPDATE payment_intent SET processor_merchant_id = merchant_id where processor_merchant_id IS NULL; +UPDATE payment_attempt SET processor_merchant_id = merchant_id where processor_merchant_id IS NULL;
2025-04-08T14:40:56Z
## Description <!-- Describe your changes in detail --> - added `processor_merchant_id` and` created_by` column in `diesel_models` and `hyperswitch_domain_models` - added migrations - ~added backfilling `processor_merchant_id` column in migrations~ (Due to staggered release backfilling should be done at a later point after deployment is complete so it can't be done in the scope of this PR) - populating these fields with default scenario values as mentions in [Motivation and Context](#motivation-and-context) - removing `platform_merchant_id` column and population instances from `hyperswitch_domain_models`. - created a macro `impl_enum_str!` to implement serialization and deserialization for any enum with singleton associated data. - for e.g ```rust CreatedBy::Api { merchant_id: merchant_32423 } ``` will be serialized to `Api:merchant_32423` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #7769 #### Introducing two fields in payment_intent and payment_attempt table namely, - `processor_merchant_id` - `created_by` #### Terminology | column | description | | ----------| -------- | | **merchant_id**(already exists) | Who actually configures payment settings, or who has integrated with us, i.e **owner**. | | **processor_merchant_id** | Who owns the credentials of the processor, i.e. processor owner | | **created_by** | who invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) | #### Value combination matrix | Cases | merchant_id | processor_merchant_id | created_by(null) | | --------------------------------------------------- | ----------- | --------------------- | -----------| | Normal (non vsas) | 123 | 123 | 123 | | Platform performing for connected | pid1 | 123 | pid1 | | Platform performing for platform | pid1 | pid1 | pid1 | | Connected making some operation on top of a payment | pid1 | 123 | 123 | >created_by is an enum struct ```rust pub enum CreatedBy { Api { merchant_id: id_type::MerchantId }, Jwt { user_id: String }, } ``` #### **Important Note**: This PR is just a scaffold for the next changes to come that will include several logic like, determining what scenario it is mentioned in the above table and populating column fields accordingly. # ### Steps 1. Make a payment ```sh curl --location '{{baseurl}}/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ****redacted****' \ --data-raw '{ "amount": 104000, "currency": "GBP", "amount_to_capture": 104000, "confirm": true, "profile_id": "**redacted**", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "routing": { "type": "single", "data": "stripe" }, "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "re", "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "card_cvc": "257" } }, "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" }, "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": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 104000, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` response ```json { "payment_id": "pay_mzSYO8ZS6YgxJ8qhpk10", "merchant_id": "merchant_1744876813", "status": "processing", "amount": 104000, "net_amount": 104000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "checkout", "client_secret": "****redacted****", "created": "2025-04-17T08:11:05.286Z", "currency": "GBP", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0131", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453243", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 104000, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1744877465, "expires": 1744881065, "secret": "****redacted****" }, "manual_retry_allowed": false, "connector_transaction_id": "pay_smcaidph7qhefdvm653lrn6wda", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null }, "feature_metadata": null, "reference_id": "pay_mzSYO8ZS6YgxJ8qhpk10_1", "payment_link": null, "profile_id": "pro_RZojFbEiPLcW3fj9rK1W", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_J1wam8mC5wvSWgcWAoiz", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-17T08:26:05.286Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-17T08:11:06.465Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` 2. run the sql query in psql console ```sql select merchant_id, processor_merchant_id, created_by from payment_intent; ``` run the above query ### Result | merchant_id | processor_merchant_id | created_by| | --------------------- | ----------------------- | ------------------------- | | merchant_1 | merchant_1 | | | merchant_2 | merchant_2 | |
103a5c182b9744faf27d367efd58fac669d5c2ba
### Steps 1. Make a payment ```sh curl --location '{{baseurl}}/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ****redacted****' \ --data-raw '{ "amount": 104000, "currency": "GBP", "amount_to_capture": 104000, "confirm": true, "profile_id": "**redacted**", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "routing": { "type": "single", "data": "stripe" }, "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "re", "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "card_cvc": "257" } }, "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" }, "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": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 104000, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` response ```json { "payment_id": "pay_mzSYO8ZS6YgxJ8qhpk10", "merchant_id": "merchant_1744876813", "status": "processing", "amount": 104000, "net_amount": 104000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "checkout", "client_secret": "****redacted****", "created": "2025-04-17T08:11:05.286Z", "currency": "GBP", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0131", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453243", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 104000, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1744877465, "expires": 1744881065, "secret": "****redacted****" }, "manual_retry_allowed": false, "connector_transaction_id": "pay_smcaidph7qhefdvm653lrn6wda", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null }, "feature_metadata": null, "reference_id": "pay_mzSYO8ZS6YgxJ8qhpk10_1", "payment_link": null, "profile_id": "pro_RZojFbEiPLcW3fj9rK1W", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_J1wam8mC5wvSWgcWAoiz", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-17T08:26:05.286Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-17T08:11:06.465Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` 2. run the sql query in psql console ```sql select merchant_id, processor_merchant_id, created_by from payment_intent; ``` run the above query ### Result | merchant_id | processor_merchant_id | created_by| | --------------------- | ----------------------- | ------------------------- | | merchant_1 | merchant_1 | | | merchant_2 | merchant_2 | |
[ "crates/common_utils/src/macros.rs", "crates/common_utils/src/types.rs", "crates/diesel_models/src/payment_attempt.rs", "crates/diesel_models/src/payment_intent.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/diesel_models/src/user/sample_data.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs", "crates/hyperswitch_domain_models/src/payments/payment_intent.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_approve.rs", "crates/router/src/core/payments/operations/payment_cancel.rs", "crates/router/src/core/payments/operations/payment_capture.rs", "crates/router/src/core/payments/operations/payment_capture_v2.rs", "crates/router/src/core/payments/operations/payment_create.rs", "crates/router/src/core/payments/operations/payment_get.rs", "crates/router/src/core/payments/operations/payment_get_intent.rs", "crates/router/src/core/payments/operations/payment_reject.rs", "crates/router/src/core/payments/operations/payment_status.rs", "crates/router/src/core/payments/operations/payment_update_intent.rs", "crates/router/src/core/payments/operations/payments_incremental_authorization.rs", "crates/router/src/core/payments/retry.rs", "crates/router/src/core/utils.rs", "crates/router/src/types/storage/payment_attempt.rs", "crates/router/src/utils/user/sample_data.rs", "crates/storage_impl/src/mock_db/payment_attempt.rs", "crates/storage_impl/src/payments/payment_attempt.rs", "migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/down.sql", "migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7764
Bug: `nmi` tests shows different error messages for the same request Postman Tests for nmi behaves like the following while running `Flow Testcases/Variation Cases/Scenario9-Create a mandate payment` ## Creating a mandate payment for `nmi` ```curl curl --location '{{baseUrl}}/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{apiKey}}' \ --data-raw '{ "amount": 47074, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 47074, "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" } }' ``` ### Integ Response ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "credit mandate payment is not supported by nmi" } } ``` ### SBX Response ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "debit mandate payment is not supported by nmi" } } ``` It shows different error messages for two environments.
diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js index b07811aed26..656033c2caa 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js @@ -34,7 +34,7 @@ if (jsonData?.error?.type) { // Response body should have value "mandate payment is not supported by nmi" for "error reason" if (jsonData?.error?.message) { pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error.reason' matches ' mandate payment is not supported by nmi'" , + "[POST]::/payments/:id/confirm - Content check if value for 'error.reason' matches 'credit mandate payment is not supported by nmi'" , function () { pm.expect(jsonData.error.reason).to.eql("credit mandate payment is not supported by nmi"); }, diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json index 314752373cc..884b99e89f7 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json @@ -35,7 +35,7 @@ "payment_method": "card", "payment_method_data": { "card": { - "card_number": "4111111111111111", + "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "69", "card_holder_name": "joseph Doe",
2025-04-08T11:09:57Z
## Description <!-- Describe your changes in detail --> Postman Tests for `nmi` were failing on SBX (but not on Integ) because `Flow Testcases/Variation Cases/Scenario9-Create a mandate payment` responded an error message as `debit mandate payment is not supported by nmi` on SBX and `credit mandate payment is not supported by nmi` on Integ when we are using Card `4111111111111111`. So, I thought of two solutions. First, check whether the error message contains "mandate payment is not supported by nmi" or second, change the card number for which the error message in both the environments are same. I chose the second way finally. And, there is a slight change, which I missed in #7159. <!-- However, I made a change in #7159, which goes like the following ![image](https://github.com/user-attachments/assets/62b3ed2a-bbe2-426f-8a30-eb4f980b51ba) Because it was failing expecting the error message to be " mandate payment is not supported by nmi" but it should include the same instead of equal to. --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The `Flow Testcases/Variation Cases/Scenario9-Create a mandate payment` passing on Integ and failing on SBX. #7764 # ### Before | Integ | Sandbox | | -------- | ------- | | <img width="850" alt="image" src="https://github.com/user-attachments/assets/c66e4b3b-5cf3-49ee-998a-fe7ab388c0f9" /> | <img width="850" alt="image" src="https://github.com/user-attachments/assets/4a26f840-405b-41e8-86f2-3be32aa88056" /> | ### After | Integ | Sandbox | | -------- | ------- | | <img width="850" alt="image" src="https://github.com/user-attachments/assets/eb2b3d92-0431-4887-86a9-53f5db6be2eb" /> | <img width="850" alt="image" src="https://github.com/user-attachments/assets/e0334b87-9bf7-43ab-b20e-fdd87e5531c7" /> |
8738f190677c25e9023e2faa2be9aa9a60ce1097
### Before | Integ | Sandbox | | -------- | ------- | | <img width="850" alt="image" src="https://github.com/user-attachments/assets/c66e4b3b-5cf3-49ee-998a-fe7ab388c0f9" /> | <img width="850" alt="image" src="https://github.com/user-attachments/assets/4a26f840-405b-41e8-86f2-3be32aa88056" /> | ### After | Integ | Sandbox | | -------- | ------- | | <img width="850" alt="image" src="https://github.com/user-attachments/assets/eb2b3d92-0431-4887-86a9-53f5db6be2eb" /> | <img width="850" alt="image" src="https://github.com/user-attachments/assets/e0334b87-9bf7-43ab-b20e-fdd87e5531c7" /> |
[ "postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js", "postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json", "postman/collection-dir/nmi/Flow" ]
juspay/hyperswitch
juspay__hyperswitch-7761
Bug: One click docker setup A script is needed to ensure one click docker setup, to minimise issues faced by users. > Run the whole setup with simple command > Show output with localhost links for different setups
diff --git a/README.md b/README.md index 72ac7e0e3a7..7f15ac2b01c 100644 --- a/README.md +++ b/README.md @@ -78,36 +78,17 @@ Read more at [Hyperswitch docs](https://docs.hyperswitch.io/). ### 1. Local Setup You can run Hyperswitch on your system using Docker compose after cloning this repository. - +We recommend using Docker Desktop (Or Orbstack) for Windows and Mac OS. On Linux, you can install Docker Engine directly. ```shell git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch cd hyperswitch docker compose up -d +# This script verifies the setup and provides links to the individual components. +scripts/docker_output.sh ``` +The next step is to [configure a connector][configure-a-connector] with the Hyperswitch Control Center and [try a payment][try-a-payment]. -Check out the [local setup guide][local-setup-guide] for a more details on setting up the entire stack or component wise. This takes 15-mins and gives the following output -```shell -[+] Running 2/2 -✔ hyperswitch-control-center Pulled 2.9s -✔ hyperswitch-server Pulled 3.0s -[+] Running 6/0 - -✔ Container hyperswitch-pg-1 Created 0.0s -✔ Container hyperswitch-redis-standalone-1 Created 0.0s -✔ Container hyperswitch-migration_runner-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-server-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-web-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-control-center-1 Created 0.0s - -Attaching to hyperswitch-control-center-1, hyperswitch-server-1, hyperswitch-web-1, migration_runner-1, pg-1, redis-standalone-1 -``` -You've now setup Hyperswitch in your local machine. In order to verify that the server is up and running hit the health endpoint: -```shell -curl --head --request GET 'http://localhost:8080/health' -``` -The expected response here is a `200 OK` status code. This indicates that the server and all of its dependent services are functioning correctly. -Now, you can access the Control Center in your browser at `http://localhost:9000`. -The next step is to configure a connector with the Hyperswitch Control Center and try a payment. +Check out the [local setup guide][local-setup-guide] for more details on setting up the entire stack or component wise. ### 2. Deployment on cloud @@ -144,7 +125,8 @@ You can experience the product by signing up for our [hosted sandbox](https://ap [learning-resources]: https://docs.hyperswitch.io/learn-more/payment-flows [local-setup-guide]: /docs/try_local_system.md [docker-compose-scheduler-monitoring]: /docs/try_local_system.md#running-additional-services - +[configure-a-connector]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/using-hyperswitch-control-center#add-a-payment-processor +[try-a-payment]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/test-a-payment <a href="support-feature-requests"> <h2 id="support-feature-requests">Support, Feature requests & Bugs</h2> diff --git a/scripts/docker_output.sh b/scripts/docker_output.sh new file mode 100755 index 00000000000..80d178ca75b --- /dev/null +++ b/scripts/docker_output.sh @@ -0,0 +1,33 @@ +#! /usr/bin/env bash +set -euo pipefail + +# Define the URL to check service availability (adjust HOST and PORT if needed) +HOST="localhost" +PORT="8080" +SERVICE_URL="http://${HOST}:${PORT}/health" + +MAX_RETRIES=70 +RETRY_COUNT=0 + +# Wait until the service is available or retries are exhausted +while ! curl --silent --fail "${SERVICE_URL}" > /dev/null; do + if (( RETRY_COUNT >= MAX_RETRIES )); then + echo "" + echo "Service failed to start. Kindly check the logs." + echo "You can view the logs using the command: docker-compose logs -f <service name>" + exit 1 + fi + printf "." + sleep 2 + ((RETRY_COUNT++)) +done + +# Define ANSI 24-bit (true color) escape sequences for Light Sky Blue +LIGHT_SKY_BLUE="\033[38;2;135;206;250m" +RESET="\033[0m" + +# Print the service URLs with only the links colored +echo -e "Control Centre running at ${LIGHT_SKY_BLUE}http://localhost:9000${RESET}" +echo -e "App server running at ${LIGHT_SKY_BLUE}http://localhost:8080${RESET}" +echo -e "Web-SDK running at ${LIGHT_SKY_BLUE}http://localhost:5252/HyperLoader.js${RESET}" +echo -e "Mailhog running at ${LIGHT_SKY_BLUE}http://localhost:8025${RESET}" \ No newline at end of file
2025-04-08T08:30:51Z
## Description <!-- Describe your changes in detail --> Script for one click docker setup, to minimise issues faced by users. >Run the whole setup with simple command >Show output with localhost links for different setups ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Script for one click docker setup, to minimise issues faced by users. Closes #7761 #
d6c26c5d75652a2ba2ecfbc0df7d33172df1705b
Attaching ss of test on local. <img width="466" alt="Screenshot 2025-04-08 at 4 12 13 PM" src="https://github.com/user-attachments/assets/003ce4e1-aadc-4ad2-abde-763728f51ad1" />
[ "README.md", "scripts/docker_output.sh" ]
juspay/hyperswitch
juspay__hyperswitch-7759
Bug: Create authentications to fallback to ApiKeyAuth if AdminApiAuth fails hotfix Create two new authentication mechanisms that enhance the existing AdminApiAuth and AdminApiAuthWithMerchantIdFromRoute by allowing fallback to regular API key-based authentication when the admin key check fails.
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index c59b8471344..7cd4ce2d4bd 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -480,6 +480,7 @@ pub(crate) async fn fetch_raw_secrets( #[cfg(feature = "olap")] replica_database, secrets, + fallback_merchant_ids_api_key_auth: conf.fallback_merchant_ids_api_key_auth, locker: conf.locker, connectors: conf.connectors, forex_api, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a4c454ec196..83591b15e36 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -66,6 +66,7 @@ pub struct Settings<S: SecretState> { pub redis: RedisSettings, pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, + pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>, pub locker: Locker, pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, @@ -676,6 +677,13 @@ pub struct Secrets { pub master_enc_key: Secret<String>, } +#[derive(Debug, Default, Deserialize, Clone)] +#[serde(default)] +pub struct FallbackMerchantIds { + #[serde(deserialize_with = "deserialize_merchant_ids")] + pub merchant_ids: HashSet<id_type::MerchantId>, +} + #[derive(Debug, Clone, Default, Deserialize)] pub struct UserSettings { pub password_validity_in_days: u16, @@ -1271,6 +1279,53 @@ where })? } +fn deserialize_merchant_ids_inner( + value: impl AsRef<str>, +) -> Result<HashSet<id_type::MerchantId>, String> { + let (values, errors) = value + .as_ref() + .trim() + .split(',') + .map(|s| { + let trimmed = s.trim(); + id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| { + format!( + "Unable to deserialize `{}` as `MerchantId`: {error}", + trimmed + ) + }) + }) + .fold( + (HashSet::new(), Vec::new()), + |(mut values, mut errors), result| match result { + Ok(t) => { + values.insert(t); + (values, errors) + } + Err(error) => { + errors.push(error); + (values, errors) + } + }, + ); + + if !errors.is_empty() { + Err(format!("Some errors occurred:\n{}", errors.join("\n"))) + } else { + Ok(values) + } +} + +fn deserialize_merchant_ids<'de, D>( + deserializer: D, +) -> Result<HashSet<id_type::MerchantId>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let s = String::deserialize(deserializer)?; + deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom) +} + impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 1c494542228..2be9058e906 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -186,7 +186,7 @@ pub async fn merchant_account_create( &req, json_payload.into_inner(), |state, _, req, _| create_merchant_account(state, req), - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallback, api_locking::LockAction::NotApplicable, )) .await @@ -249,7 +249,7 @@ pub async fn retrieve_merchant_account( payload, |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be MerchantAccountRead, but since FE is calling this API for @@ -350,7 +350,7 @@ pub async fn merchant_account_list( query_params.into_inner(), |state, _, request, _| list_merchant_account(state, request), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallback, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, @@ -409,7 +409,7 @@ pub async fn update_merchant_account( json_payload.into_inner(), |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 911617753d4..087e295dc8e 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -29,7 +29,7 @@ pub async fn api_key_create( api_keys::create_api_key(state, payload, auth_data.key_store).await }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyWrite, @@ -130,7 +130,7 @@ pub async fn api_key_retrieve( (merchant_id.clone(), key_id.clone()), |state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyRead, @@ -166,7 +166,7 @@ pub async fn api_key_update( payload, |state, _, payload, _| api_keys::update_api_key(state, payload), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyWrite, @@ -303,7 +303,7 @@ pub async fn api_key_list( api_keys::list_api_keys(state, merchant_id, limit, offset).await }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7e3d6802b88..3b9fcfc0d8e 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -654,113 +654,20 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { - let merchant_id_from_route = self.0.clone(); - 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 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 (auth_data, auth_type) = ApiKeyAuth + .authenticate_and_fetch(request_headers, state) + .await?; - let profile_id = - get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? - .map(id_type::ProfileId::from_str) - .transpose() - .change_context(errors::ValidationError::IncorrectValueProvided { - field_name: "X-Profile-Id", - }) - .change_context(errors::ApiErrorResponse::Unauthorized)?; + let merchant_id_from_route = self.0.clone(); + let merchant_id_from_api_key = auth_data.merchant_account.get_id(); - if merchant_id_from_route != stored_api_key.merchant_id { + if merchant_id_from_route != *merchant_id_from_api_key { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Merchant ID from route and Merchant ID from api-key in header do not match", ); } - 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 auth = AuthenticationData { - merchant_account: merchant, - platform_merchant_account, - key_store, - profile_id, - }; - Ok(( - auth.clone(), - AuthenticationType::ApiKey { - merchant_id: auth.merchant_account.get_id().clone(), - key_id: stored_api_key.key_id, - }, - )) + Ok((auth_data, auth_type)) } } @@ -1398,6 +1305,198 @@ where } } +#[derive(Debug, Default)] +pub struct AdminApiAuthWithApiKeyFallback; + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for AdminApiAuthWithApiKeyFallback +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let request_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + + let conf = state.conf(); + + let admin_api_key = &conf.secrets.get_inner().admin_api_key; + + if request_api_key == admin_api_key.peek() { + return Ok(((), AuthenticationType::AdminApiKey)); + } + let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Api Key Authentication Failure: fallback merchant set not configured", + ); + }; + + let api_key = api_keys::PlaintextApiKey::from(request_api_key); + let hash_key = conf.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) + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) + .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"); + } + + if fallback_merchant_ids + .merchant_ids + .contains(&stored_api_key.merchant_id) + { + return Ok(( + (), + AuthenticationType::ApiKey { + merchant_id: stored_api_key.merchant_id, + key_id: stored_api_key.key_id, + }, + )); + } + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure")) + } +} + +#[derive(Debug, Default)] +pub struct AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(pub id_type::MerchantId); + +#[cfg(feature = "v1")] +impl AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute { + async fn fetch_merchant_key_store_and_account<A: SessionStateInfo + Sync>( + merchant_id: &id_type::MerchantId, + state: &A, + ) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> { + let key_manager_state = &(&state.session_state()).into(); + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + Ok((key_store, merchant)) + } +} + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> + for AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let merchant_id_from_route: id_type::MerchantId = self.0.clone(); + let request_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + let conf = state.conf(); + + let admin_api_key: &masking::Secret<String> = &conf.secrets.get_inner().admin_api_key; + + if request_api_key == admin_api_key.peek() { + let (key_store, merchant) = + Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; + let auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account: None, + key_store, + profile_id: None, + }; + return Ok(( + auth, + AuthenticationType::AdminApiAuthWithMerchantId { + merchant_id: merchant_id_from_route.clone(), + }, + )); + } + let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Api Key Authentication Failure: fallback merchant set not configured", + ); + }; + + let api_key = api_keys::PlaintextApiKey::from(request_api_key); + let hash_key = conf.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) + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) + .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"); + } + + if fallback_merchant_ids + .merchant_ids + .contains(&stored_api_key.merchant_id) + { + let (_, api_key_merchant) = + Self::fetch_merchant_key_store_and_account(&stored_api_key.merchant_id, state) + .await?; + let (route_key_store, route_merchant) = + Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; + if api_key_merchant.get_org_id() == route_merchant.get_org_id() { + let auth = AuthenticationData { + merchant_account: route_merchant, + platform_merchant_account: None, + key_store: route_key_store, + profile_id: None, + }; + return Ok(( + auth.clone(), + AuthenticationType::MerchantId { + merchant_id: auth.merchant_account.get_id().clone(), + }, + )); + } + } + + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure")) + } +} + /// A helper struct to extract headers from the request pub(crate) struct HeaderMapStruct<'a> { headers: &'a HeaderMap,
2025-04-08T08:09:47Z
## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7744](https://github.com/juspay/hyperswitch/pull/7744) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
2fdeb8580baffbf3fa3e5b49325a36ee02e4b176
[ "crates/router/src/configs/secrets_transformers.rs", "crates/router/src/configs/settings.rs", "crates/router/src/routes/admin.rs", "crates/router/src/routes/api_keys.rs", "crates/router/src/services/authentication.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7755
Bug: [CI] cypress checks for wise failing wise is returning status as `forbidden`. it is better to replace that with adyen payouts
2025-04-08T07:04:59Z
## Description <!-- Describe your changes in detail --> this pr updates the `adyen` payouts credentials and it also replaces wise from running in github ci ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ci checks are failing across all prs. closes #7755 #
de86066402fab0d7725f7ee71085862b3b8c74e9
ci checks should pass.
[]
juspay/hyperswitch
juspay__hyperswitch-7748
Bug: Add checks around Cypress mandates payments Just verifying the payment method status isn't enough. We also need to verify the existence of connector mandate id. this can be done by updating the `mitusingpmid` command.
2025-04-07T17:27:49Z
## Description <!-- Describe your changes in detail --> This PR adds a check to verify if the `payment_status` is not any of `succeeded`, `partially_captured` or `requires_capture` and if so, then the `connector_mandate_id` should be `null`. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Verifying PM status isn't enough. We also need to check the existence of connector mandate id. Closes #7748 #
5730ddfc8893017f40a5f5a8c1b7f099cc0d22a9
CI should pass. Also: CIT confirm, we should get `connector_mandate_id` <img width="510" alt="image" src="https://github.com/user-attachments/assets/41f74780-5b6e-404f-a9ec-2cf7619d9adf" /> MIT confirm, in NTID flow, `connector_mandate_id` will be `null` <img width="509" alt="image" src="https://github.com/user-attachments/assets/82c21ce9-261e-4457-9efc-c3e68398e555" />
[]
juspay/hyperswitch
juspay__hyperswitch-7745
Bug: Create authentications to fallback to ApiKeyAuth if AdminApiAuth fails Create two new authentication mechanisms that enhance the existing `AdminApiAuth` and `AdminApiAuthWithMerchantIdFromRoute` by allowing fallback to regular API key-based authentication when the admin key check fails. This will be used by Merchant Account and API Key routes.
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index c59b8471344..7cd4ce2d4bd 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -480,6 +480,7 @@ pub(crate) async fn fetch_raw_secrets( #[cfg(feature = "olap")] replica_database, secrets, + fallback_merchant_ids_api_key_auth: conf.fallback_merchant_ids_api_key_auth, locker: conf.locker, connectors: conf.connectors, forex_api, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a4c454ec196..83591b15e36 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -66,6 +66,7 @@ pub struct Settings<S: SecretState> { pub redis: RedisSettings, pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, + pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>, pub locker: Locker, pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, @@ -676,6 +677,13 @@ pub struct Secrets { pub master_enc_key: Secret<String>, } +#[derive(Debug, Default, Deserialize, Clone)] +#[serde(default)] +pub struct FallbackMerchantIds { + #[serde(deserialize_with = "deserialize_merchant_ids")] + pub merchant_ids: HashSet<id_type::MerchantId>, +} + #[derive(Debug, Clone, Default, Deserialize)] pub struct UserSettings { pub password_validity_in_days: u16, @@ -1271,6 +1279,53 @@ where })? } +fn deserialize_merchant_ids_inner( + value: impl AsRef<str>, +) -> Result<HashSet<id_type::MerchantId>, String> { + let (values, errors) = value + .as_ref() + .trim() + .split(',') + .map(|s| { + let trimmed = s.trim(); + id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| { + format!( + "Unable to deserialize `{}` as `MerchantId`: {error}", + trimmed + ) + }) + }) + .fold( + (HashSet::new(), Vec::new()), + |(mut values, mut errors), result| match result { + Ok(t) => { + values.insert(t); + (values, errors) + } + Err(error) => { + errors.push(error); + (values, errors) + } + }, + ); + + if !errors.is_empty() { + Err(format!("Some errors occurred:\n{}", errors.join("\n"))) + } else { + Ok(values) + } +} + +fn deserialize_merchant_ids<'de, D>( + deserializer: D, +) -> Result<HashSet<id_type::MerchantId>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let s = String::deserialize(deserializer)?; + deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom) +} + impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 1c494542228..2be9058e906 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -186,7 +186,7 @@ pub async fn merchant_account_create( &req, json_payload.into_inner(), |state, _, req, _| create_merchant_account(state, req), - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallback, api_locking::LockAction::NotApplicable, )) .await @@ -249,7 +249,7 @@ pub async fn retrieve_merchant_account( payload, |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be MerchantAccountRead, but since FE is calling this API for @@ -350,7 +350,7 @@ pub async fn merchant_account_list( query_params.into_inner(), |state, _, request, _| list_merchant_account(state, request), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallback, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, @@ -409,7 +409,7 @@ pub async fn update_merchant_account( json_payload.into_inner(), |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 911617753d4..087e295dc8e 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -29,7 +29,7 @@ pub async fn api_key_create( api_keys::create_api_key(state, payload, auth_data.key_store).await }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyWrite, @@ -130,7 +130,7 @@ pub async fn api_key_retrieve( (merchant_id.clone(), key_id.clone()), |state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyRead, @@ -166,7 +166,7 @@ pub async fn api_key_update( payload, |state, _, payload, _| api_keys::update_api_key(state, payload), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyWrite, @@ -303,7 +303,7 @@ pub async fn api_key_list( api_keys::list_api_keys(state, merchant_id, limit, offset).await }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7e3d6802b88..3b9fcfc0d8e 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -654,113 +654,20 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { - let merchant_id_from_route = self.0.clone(); - 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 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 (auth_data, auth_type) = ApiKeyAuth + .authenticate_and_fetch(request_headers, state) + .await?; - let profile_id = - get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? - .map(id_type::ProfileId::from_str) - .transpose() - .change_context(errors::ValidationError::IncorrectValueProvided { - field_name: "X-Profile-Id", - }) - .change_context(errors::ApiErrorResponse::Unauthorized)?; + let merchant_id_from_route = self.0.clone(); + let merchant_id_from_api_key = auth_data.merchant_account.get_id(); - if merchant_id_from_route != stored_api_key.merchant_id { + if merchant_id_from_route != *merchant_id_from_api_key { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Merchant ID from route and Merchant ID from api-key in header do not match", ); } - 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 auth = AuthenticationData { - merchant_account: merchant, - platform_merchant_account, - key_store, - profile_id, - }; - Ok(( - auth.clone(), - AuthenticationType::ApiKey { - merchant_id: auth.merchant_account.get_id().clone(), - key_id: stored_api_key.key_id, - }, - )) + Ok((auth_data, auth_type)) } } @@ -1398,6 +1305,198 @@ where } } +#[derive(Debug, Default)] +pub struct AdminApiAuthWithApiKeyFallback; + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for AdminApiAuthWithApiKeyFallback +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let request_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + + let conf = state.conf(); + + let admin_api_key = &conf.secrets.get_inner().admin_api_key; + + if request_api_key == admin_api_key.peek() { + return Ok(((), AuthenticationType::AdminApiKey)); + } + let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Api Key Authentication Failure: fallback merchant set not configured", + ); + }; + + let api_key = api_keys::PlaintextApiKey::from(request_api_key); + let hash_key = conf.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) + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) + .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"); + } + + if fallback_merchant_ids + .merchant_ids + .contains(&stored_api_key.merchant_id) + { + return Ok(( + (), + AuthenticationType::ApiKey { + merchant_id: stored_api_key.merchant_id, + key_id: stored_api_key.key_id, + }, + )); + } + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure")) + } +} + +#[derive(Debug, Default)] +pub struct AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(pub id_type::MerchantId); + +#[cfg(feature = "v1")] +impl AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute { + async fn fetch_merchant_key_store_and_account<A: SessionStateInfo + Sync>( + merchant_id: &id_type::MerchantId, + state: &A, + ) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> { + let key_manager_state = &(&state.session_state()).into(); + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + Ok((key_store, merchant)) + } +} + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> + for AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let merchant_id_from_route: id_type::MerchantId = self.0.clone(); + let request_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + let conf = state.conf(); + + let admin_api_key: &masking::Secret<String> = &conf.secrets.get_inner().admin_api_key; + + if request_api_key == admin_api_key.peek() { + let (key_store, merchant) = + Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; + let auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account: None, + key_store, + profile_id: None, + }; + return Ok(( + auth, + AuthenticationType::AdminApiAuthWithMerchantId { + merchant_id: merchant_id_from_route.clone(), + }, + )); + } + let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Api Key Authentication Failure: fallback merchant set not configured", + ); + }; + + let api_key = api_keys::PlaintextApiKey::from(request_api_key); + let hash_key = conf.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) + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) + .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"); + } + + if fallback_merchant_ids + .merchant_ids + .contains(&stored_api_key.merchant_id) + { + let (_, api_key_merchant) = + Self::fetch_merchant_key_store_and_account(&stored_api_key.merchant_id, state) + .await?; + let (route_key_store, route_merchant) = + Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; + if api_key_merchant.get_org_id() == route_merchant.get_org_id() { + let auth = AuthenticationData { + merchant_account: route_merchant, + platform_merchant_account: None, + key_store: route_key_store, + profile_id: None, + }; + return Ok(( + auth.clone(), + AuthenticationType::MerchantId { + merchant_id: auth.merchant_account.get_id().clone(), + }, + )); + } + } + + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure")) + } +} + /// A helper struct to extract headers from the request pub(crate) struct HeaderMapStruct<'a> { headers: &'a HeaderMap,
2025-04-07T13:20:20Z
## Description <!-- Describe your changes in detail --> This PR introduces two new authentication mechanisms that enhance the existing `AdminApiAuth` and `AdminApiAuthWithMerchantIdFromRoute` by allowing fallback to regular API key-based authentication when the admin key check fails. ### 1. `AdminApiAuthWithApiKeyFallback` - Used in routes where **no merchant context** is required. - Authenticates using: 1. `admin_api_key` 2. If that fails, falls back to: - Validating the provided `api-key` - Ensuring its associated `merchant_id` matches the configured `fallback_merchant_id` from the merchant_ids set. ### 2. `AdminApiAuthWithApiKeyFallbackWithMerchant` - Used in routes that require **full merchant context** (`AuthenticationData`) - Authenticates using: 1. `admin_api_key` — on success, loads `AuthenticationData` 2. If that fails: - Validates the provided `api-key` - Ensures: - The `merchant_id` from `api-key` also matches the configured `fallback_merchant_id` from the merchant_ids set. - If all conditions pass, loads and returns `AuthenticationData` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Some internal routes currently rely on `AdminApiAuth` using a shared `admin_api_key`. However, there are scenarios where we want to allow scoped access using an `api-key` associated with a specific merchant — **only if it matches a configured fallback merchant** from the merchant_ids set. # #### Merchant Account - Create ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' \ --data-raw '{ "merchant_id": "merchant_1744040286", "locker_id": "m0010", "merchant_name": "Nike", "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": "https://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", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ], "organization_id": "org_aDQVlxlUjkkgfFO9rlwr" }' ``` #### Merchant Account - Retrieve ```bash curl --location 'http://localhost:8080/accounts/merchant_1744037289' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' ``` #### Merchant Account - Update ```bash curl --location 'http://localhost:8080/accounts/merchant_1744037289' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' \ --data-raw '{ "merchant_id": "merchant_1744037289", "locker_id": "m0010", "merchant_name": "Nike New", "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": "https://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", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` #### API Key - Create ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2038-01-19T03:14:08.000Z" }' ``` #### API Key - Retrieve ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289/dev_Uyyi5bbsKgcsvwgtC4EJ' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` #### API Key - Update ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289/dev_Uyyi5bbsKgcsvwgtC4EJ' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "Test API Key", "description": "My very awesome API key", "expiration": null }' ``` #### API Key - List ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744036688/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` #### Merchant Account - List
c245ece19fb1b3988c61e12c0faa37c527cabd71
The following APIs need to be validated with - AdminAPIKey - the API Key associated with the configured merchant_id in the ENVs. Tested by setting the ENV through ```bash ROUTER__FALLBACK_MERCHANT_IDS_API_KEY_AUTH__MERCHANT_IDS="merchant_1744036688, merchant_1744037289" cargo run ``` And also tested by specifying the values in the TOML file. #### Merchant Account - Create ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' \ --data-raw '{ "merchant_id": "merchant_1744040286", "locker_id": "m0010", "merchant_name": "Nike", "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": "https://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", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ], "organization_id": "org_aDQVlxlUjkkgfFO9rlwr" }' ``` #### Merchant Account - Retrieve ```bash curl --location 'http://localhost:8080/accounts/merchant_1744037289' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' ``` #### Merchant Account - Update ```bash curl --location 'http://localhost:8080/accounts/merchant_1744037289' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' \ --data-raw '{ "merchant_id": "merchant_1744037289", "locker_id": "m0010", "merchant_name": "Nike New", "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": "https://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", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` #### API Key - Create ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2038-01-19T03:14:08.000Z" }' ``` #### API Key - Retrieve ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289/dev_Uyyi5bbsKgcsvwgtC4EJ' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` #### API Key - Update ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289/dev_Uyyi5bbsKgcsvwgtC4EJ' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "Test API Key", "description": "My very awesome API key", "expiration": null }' ``` #### API Key - List ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744036688/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` #### Merchant Account - List
[ "crates/router/src/configs/secrets_transformers.rs", "crates/router/src/configs/settings.rs", "crates/router/src/routes/admin.rs", "crates/router/src/routes/api_keys.rs", "crates/router/src/services/authentication.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7737
Bug: [ENHANCEMENT] expose configurations from payment links SDK has below functionalities which needs to be exposed as payment link configs 1. `labels`, possible values - floating, above, never 2. `paymentMethodsHeaderText` - for an optional text to be displayed above the payment form 3. `terms.cards`, possible values - auto, always, never
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 61cf7b26ac3..12e5308cbd4 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -14798,6 +14798,27 @@ "enable_button_only_on_form_ready": { "type": "boolean", "description": "Flag to enable the button only when the payment form is ready for submission" + }, + "payment_form_header_text": { + "type": "string", + "description": "Optional header for the SDK's payment form", + "nullable": true + }, + "payment_form_label_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkSdkLabelType" + } + ], + "nullable": true + }, + "show_card_terms": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkShowSdkTerms" + } + ], + "nullable": true } } }, @@ -14940,6 +14961,27 @@ "type": "boolean", "description": "Flag to enable the button only when the payment form is ready for submission", "nullable": true + }, + "payment_form_header_text": { + "type": "string", + "description": "Optional header for the SDK's payment form", + "nullable": true + }, + "payment_form_label_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkSdkLabelType" + } + ], + "nullable": true + }, + "show_card_terms": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkShowSdkTerms" + } + ], + "nullable": true } } }, @@ -14987,6 +15029,22 @@ } } }, + "PaymentLinkSdkLabelType": { + "type": "string", + "enum": [ + "above", + "floating", + "never" + ] + }, + "PaymentLinkShowSdkTerms": { + "type": "string", + "enum": [ + "always", + "auto", + "never" + ] + }, "PaymentLinkStatus": { "type": "string", "description": "Status Of the Payment Link", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 5d3f7c5dc8f..a9a8525f65b 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2892,6 +2892,14 @@ pub struct PaymentLinkConfigRequest { pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, + /// Optional header for the SDK's payment form + pub payment_form_header_text: Option<String>, + /// Label type in the SDK's payment form + #[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")] + pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, + /// Boolean for controlling whether or not to show the explicit consent for storing cards + #[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")] + pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] @@ -2979,6 +2987,14 @@ pub struct PaymentLinkConfig { pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: bool, + /// Optional header for the SDK's payment form + pub payment_form_header_text: Option<String>, + /// Label type in the SDK's payment form + #[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")] + pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, + /// Boolean for controlling whether or not to show the explicit consent for storing cards + #[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")] + pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 859dba9b59a..61efe59c66b 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -8023,6 +8023,9 @@ pub struct PaymentLinkDetails { pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, + pub payment_form_header_text: Option<String>, + pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, + pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, } #[derive(Debug, serde::Serialize, Clone)] @@ -8041,6 +8044,9 @@ pub struct SecurePaymentLinkDetails { pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, + pub payment_form_header_text: Option<String>, + pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, + pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/common_enums/src/enums/ui.rs b/crates/common_enums/src/enums/ui.rs index aec6c7ed64a..eaa63e89e39 100644 --- a/crates/common_enums/src/enums/ui.rs +++ b/crates/common_enums/src/enums/ui.rs @@ -90,6 +90,54 @@ pub enum PaymentLinkDetailsLayout { Layout2, } +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + Serialize, + Deserialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "lowercase")] +#[strum(serialize_all = "lowercase")] +pub enum PaymentLinkSdkLabelType { + #[default] + Above, + Floating, + Never, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + Serialize, + Deserialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "lowercase")] +#[strum(serialize_all = "lowercase")] +pub enum PaymentLinkShowSdkTerms { + Always, + #[default] + Auto, + Never, +} + impl<'de> Deserialize<'de> for ElementSize { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 94da0f0438b..07ca6cb46dc 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -681,6 +681,9 @@ pub struct PaymentLinkConfigRequest { pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: Option<bool>, + pub payment_form_header_text: Option<String>, + pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, + pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 445cc6eab3c..634626a4b1f 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -196,6 +196,12 @@ pub struct PaymentLinkConfigRequestForPayments { Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, + /// Optional header for the SDK's payment form + pub payment_form_header_text: Option<String>, + /// Label type in the SDK's payment form + pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, + /// Boolean for controlling whether or not to show the explicit consent for storing cards + pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index a488c5aaa53..73f42dbd153 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -422,6 +422,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, + payment_form_header_text: item.payment_form_header_text, + payment_form_label_type: item.payment_form_label_type, + show_card_terms: item.show_card_terms, } } fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest { @@ -446,6 +449,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, + payment_form_header_text, + payment_form_label_type, + show_card_terms, } = self; api_models::admin::PaymentLinkConfigRequest { theme, @@ -474,6 +480,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, + payment_form_header_text, + payment_form_label_type, + show_card_terms, } } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 47a5ad25f76..40cedb1e402 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -329,6 +329,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::FeatureStatus, api_models::enums::MerchantProductType, api_models::enums::CtpServiceProvider, + api_models::enums::PaymentLinkSdkLabelType, + api_models::enums::PaymentLinkShowSdkTerms, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, api_models::admin::ConnectorWalletDetails, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index efc9dc9076b..ead503d1bb9 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -295,6 +295,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::UIWidgetFormLayout, api_models::enums::MerchantProductType, api_models::enums::CtpServiceProvider, + api_models::enums::PaymentLinkSdkLabelType, + api_models::enums::PaymentLinkShowSdkTerms, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, api_models::admin::CardTestingGuardConfig, diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 48004dd740b..c2945335b52 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -139,6 +139,9 @@ pub async fn form_payment_link_data( sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, + payment_form_header_text: None, + payment_form_label_type: None, + show_card_terms: None, } }; @@ -296,6 +299,9 @@ pub async fn form_payment_link_data( payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, + payment_form_header_text: payment_link_config.payment_form_header_text.clone(), + payment_form_label_type: payment_link_config.payment_form_label_type, + show_card_terms: payment_link_config.show_card_terms, }; Ok(( @@ -356,6 +362,9 @@ pub async fn initiate_secure_payment_link_flow( payment_link_ui_rules: payment_link_config.payment_link_ui_rules, enable_button_only_on_form_ready: payment_link_config .enable_button_only_on_form_ready, + payment_form_header_text: payment_link_config.payment_form_header_text, + payment_form_label_type: payment_link_config.payment_form_label_type, + show_card_terms: payment_link_config.show_card_terms, }; let js_script = format!( "window.__PAYMENT_DETAILS = {}", @@ -674,6 +683,9 @@ pub fn get_payment_link_config_based_on_priority( payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, + payment_form_header_text, + payment_form_label_type, + show_card_terms, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, @@ -688,6 +700,9 @@ pub fn get_payment_link_config_based_on_priority( (payment_button_text_colour), (sdk_ui_rules), (payment_link_ui_rules), + (payment_form_header_text), + (payment_form_label_type), + (show_card_terms), ); let payment_link_config = @@ -716,6 +731,9 @@ pub fn get_payment_link_config_based_on_priority( sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, + payment_form_header_text, + payment_form_label_type, + show_card_terms, }; Ok((payment_link_config, domain_name)) @@ -827,6 +845,9 @@ pub async fn get_payment_link_status( sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, + payment_form_header_text: None, + payment_form_label_type: None, + show_card_terms: None, } }; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js index f9b0fe892cf..effd27cc64a 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -12,6 +12,7 @@ function initializeSDK() { var paymentDetails = window.__PAYMENT_DETAILS; var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; + var labelType = paymentDetails.payment_form_label_type; var appearance = { variables: { colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", @@ -25,9 +26,12 @@ function initializeSDK() { colorBackground: "rgb(255, 255, 255)", }, }; - if (sdkUiRules !== null && typeof sdkUiRules === "object" && Object.getPrototypeOf(sdkUiRules) === Object.prototype) { + if (isObject(sdkUiRules)) { appearance.rules = sdkUiRules; } + if (labelType !== null && typeof labelType === "string") { + appearance.labels = labelType; + } // @ts-ignore hyper = window.Hyper(pub_key, { isPreloadEnabled: false, @@ -70,11 +74,18 @@ function initializeSDK() { hideCardNicknameField: hideCardNicknameField, customMessageForCardTerms: paymentDetails.custom_message_for_card_terms, }; - // @ts-ignore + var showCardTerms = paymentDetails.show_card_terms; + if (showCardTerms !== null && typeof showCardTerms === "string") { + unifiedCheckoutOptions.terms = { + card: showCardTerms + }; + } + var paymentMethodsHeaderText = paymentDetails.payment_form_header_text; + if (paymentMethodsHeaderText !== null && typeof paymentMethodsHeaderText === "string") { + unifiedCheckoutOptions.paymentMethodsHeaderText = paymentMethodsHeaderText; + } unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions); - // @ts-ignore mountUnifiedCheckout("#unified-checkout"); - // @ts-ignore showSDK(paymentDetails.display_sdk_only, paymentDetails.enable_button_only_on_form_ready); let shimmer = document.getElementById("payment-details-shimmer"); diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index 12ae76a2085..446428e6ff3 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -33,6 +33,7 @@ if (!isFramed) { var paymentDetails = window.__PAYMENT_DETAILS; var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; + var labelType = paymentDetails.payment_form_label_type; var appearance = { variables: { colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", @@ -46,9 +47,12 @@ if (!isFramed) { colorBackground: "rgb(255, 255, 255)", }, }; - if (sdkUiRules !== null && typeof sdkUiRules === "object" && Object.getPrototypeOf(sdkUiRules) === Object.prototype) { + if (isObject(sdkUiRules)) { appearance.rules = sdkUiRules; } + if (labelType !== null && typeof labelType === "string") { + appearance.labels = labelType; + } // @ts-ignore hyper = window.Hyper(pub_key, { isPreloadEnabled: false, @@ -93,11 +97,19 @@ if (!isFramed) { showCardFormByDefault: paymentDetails.show_card_form_by_default, customMessageForCardTerms: paymentDetails.custom_message_for_card_terms, }; - // @ts-ignore + var showCardTerms = paymentDetails.show_card_terms; + if (showCardTerms !== null && typeof showCardTerms === "string") { + unifiedCheckoutOptions.terms = { + card: showCardTerms + }; + } + var paymentMethodsHeaderText = paymentDetails.payment_form_header_text; + if (paymentMethodsHeaderText !== null && typeof paymentMethodsHeaderText === "string") { + unifiedCheckoutOptions.paymentMethodsHeaderText = paymentMethodsHeaderText; + } + unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions); - // @ts-ignore mountUnifiedCheckout("#unified-checkout"); - // @ts-ignore showSDK(paymentDetails.display_sdk_only, paymentDetails.enable_button_only_on_form_ready); let shimmer = document.getElementById("payment-details-shimmer"); diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5b6b014aca4..d8014768719 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4529,6 +4529,9 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, + payment_form_header_text: config.payment_form_header_text, + payment_form_label_type: config.payment_form_label_type, + show_card_terms: config.show_card_terms, } } } @@ -4600,6 +4603,9 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, + payment_form_header_text: config.payment_form_header_text, + payment_form_label_type: config.payment_form_label_type, + show_card_terms: config.show_card_terms, } } } diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index c9ff466af00..b889c41e7bc 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -152,7 +152,7 @@ pub async fn customers_list( let flow = Flow::CustomersList; let payload = query.into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -174,7 +174,7 @@ pub async fn customers_list( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 6d529b12809..04690465466 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -2188,6 +2188,9 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, + payment_form_header_text: item.payment_form_header_text, + payment_form_label_type: item.payment_form_label_type, + show_card_terms: item.show_card_terms, } } } @@ -2219,6 +2222,9 @@ impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest> sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, + payment_form_header_text: item.payment_form_header_text, + payment_form_label_type: item.payment_form_label_type, + show_card_terms: item.show_card_terms, } } }
2025-04-07T11:51:22Z
## Description This PR exposes three configurations for payment links 1. `payment_form_header_text` - for rendering a header text for payment links 2. `payment_form_label_type` - for specifying the type of payment form labels (floating / above / never) 3. `show_card_terms` - for controlling visibility of the terms for cards (auto / always / never) ## Motivation and Context Helps in exposing UI functionalities through some configs for SDK. #
68e22eefe81980666737e34336210dbea57ff40d
Tested locally <details> <summary>Create payment link with new configs</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ML2p8kRGcMvi4oQ3cPnIfz5R2rO31efjWKXzgMnbRCnj5pUpjiki8K2HONlmMAb4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_9SCrW9x19m2WbGYHprJS","profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#2167AE","enable_button_only_on_form_ready":true,"display_sdk_only":true,"show_card_terms":"never","payment_form_label_type":"floating","payment_form_header_text":"Detalles de tu tarjeta","payment_link_ui_rules":{"#submit":{"height":"max-content","borderRadius":"50px","padding":"14px 20px","marginTop":"48px","fontSize":"20px"},"#submit.not-ready":{"backgroundColor":"#A6ADAF !important"},"#submit.processing":{"paddingLeft":"50px !important","paddingRight":"50px !important"}},"sdk_ui_rules":{".Input, .Input:focus, .Input--invalid, .Input--empty":{"border":"none","boxShadow":"none","borderRadius":"28px","paddingLeft":"22px !important","paddingBottom":"2px !important","backgroundColor":"rgb(231, 234, 235) !important","height":"56px","fontSize":"20px"},".Input, .Input:focus, .Input--empty":{"color":"#23366F"},".Input--invalid":{"border":"2px solid #CB4B40 !important"},".Label":{"marginLeft":"22px","color":"#2167AE","opacity":"1 !important","bottom":"5px"},".Label--invalid, .Input--invalid, .Error":{"color":"#CB4B40 !important","opacity":"1 !important"},".Label--floating":{"opacity":"1 !important"},".InputLogo--empty":{"color":"#979797"},".InputLogo":{"color":"#23366F"},".InputLogo--invalid":{"color":"#CB4B40"},".PaymentLabel":{"color":"#23366F !important","fontSize":"24px"}}}}' Response {"payment_id":"pay_McmUUZfc21SHM7Hpc9Sr","merchant_id":"merchant_1743758708","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_McmUUZfc21SHM7Hpc9Sr_secret_ohEWaukkfjWDkoB2U7pc","created":"2025-04-07T11:49:19.273Z","currency":"EUR","customer_id":"cus_9SCrW9x19m2WbGYHprJS","customer":{"id":"cus_9SCrW9x19m2WbGYHprJS","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_9SCrW9x19m2WbGYHprJS","created_at":1744026559,"expires":1744030159,"secret":"epk_74f58545483841e7a27ef0bddca9b8b5"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1743758708/pay_McmUUZfc21SHM7Hpc9Sr?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1743758708/pay_McmUUZfc21SHM7Hpc9Sr?locale=en","payment_link_id":"plink_1VJHoVm7E71veuUAJhI8"},"profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-07T12:04:19.254Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-07T11:49:19.358Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} Verify below things 1. Label is floating when 2. Payment form has a header text 3. Card terms are missing for off_session payment type <img width="627" alt="Screenshot 2025-04-07 at 5 21 04 PM" src="https://github.com/user-attachments/assets/5e395ab6-44e7-44ab-9660-57603f79c4c2" /> </details>
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/admin.rs", "crates/api_models/src/payments.rs", "crates/common_enums/src/enums/ui.rs", "crates/diesel_models/src/business_profile.rs", "crates/diesel_models/src/payment_intent.rs", "crates/hyperswitch_domain_models/src/lib.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/openapi_v2.rs", "crates/router/src/core/payment_link.rs", "crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js", "crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js", "crates/router/src/core/payments/transformers.rs", "crates/router/src/routes/customers.rs", "crates/router/src/types/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7680
Bug: [BUG] Improper use of innerHTML in payment links Payment links make use of innerHTML property for rendering a bunch a user's text based inputs. This is considered unsafe since innerHTML evaluates the input as HTML and can lead to cross side scripting. Update this to use textContent rather than using innerHTML for rendering text based user inputs.
diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs index 571371dc63c..f6d93497627 100644 --- a/crates/hyperswitch_domain_models/src/api.rs +++ b/crates/hyperswitch_domain_models/src/api.rs @@ -72,7 +72,7 @@ pub enum PaymentLinkAction { pub struct PaymentLinkFormData { pub js_script: String, pub css_script: String, - pub sdk_url: String, + pub sdk_url: url::Url, pub html_meta_tags: String, } @@ -127,7 +127,7 @@ pub struct GenericExpiredLinkData { pub struct GenericLinkFormData { pub js_data: String, pub css_data: String, - pub sdk_url: String, + pub sdk_url: url::Url, pub html_meta_tags: String, } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index fb40451888f..8e1fb35ddce 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -444,9 +444,19 @@ impl Default for GenericLinkEnvUiConfig { } } -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Deserialize, Clone)] pub struct PaymentLink { - pub sdk_url: String, + pub sdk_url: url::Url, +} + +impl Default for PaymentLink { + fn default() -> Self { + Self { + #[allow(clippy::expect_used)] + sdk_url: url::Url::parse("https://beta.hyperswitch.io/v0/HyperLoader.js") + .expect("Failed to parse default SDK URL"), + } + } } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index adcfe8046de..545966968bd 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -387,12 +387,11 @@ pub async fn initiate_secure_payment_link_flow( payment_form_label_type: payment_link_config.payment_form_label_type, show_card_terms: payment_link_config.show_card_terms, }; - let js_script = format!( - "window.__PAYMENT_DETAILS = {}", - serde_json::to_string(&secure_payment_link_details) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to serialize PaymentLinkData")? - ); + let payment_details_str = serde_json::to_string(&secure_payment_link_details) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize PaymentLinkData")?; + let url_encoded_str = urlencoding::encode(&payment_details_str); + let js_script = format!("window.__PAYMENT_DETAILS = '{}';", url_encoded_str); let html_meta_tags = get_meta_tags_html(&link_details); let payment_link_data = services::PaymentLinkFormData { js_script, @@ -491,7 +490,8 @@ fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> { let payment_details_str = serde_json::to_string(payment_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; - Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};")) + let url_encoded_str = urlencoding::encode(&payment_details_str); + Ok(format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';")) } fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String { diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index bdfdfa8a8bf..1e96731402f 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -1,9 +1,19 @@ -// @ts-nocheck +// @ts-check /** * UTIL FUNCTIONS */ +function decodeUri(uri) { + try { + var uriStr = decodeURIComponent(uri); + return JSON.parse(uriStr); + } catch (e) { + console.error("Error decoding and parsing string URI:", e); + return uri; + } +} + function adjustLightness(hexColor, factor) { // Convert hex to RGB var r = parseInt(hexColor.slice(1, 3), 16); @@ -176,10 +186,13 @@ window.state = { var widgets = null; var unifiedCheckout = null; // @ts-ignore -var pub_key = window.__PAYMENT_DETAILS.pub_key; +var encodedPaymentDetails = window.__PAYMENT_DETAILS; +var paymentDetails = decodeUri(encodedPaymentDetails); +var pub_key = paymentDetails.pub_key; var hyper = null; -const translations = getTranslations(window.__PAYMENT_DETAILS.locale); +// @ts-ignore +const translations = getTranslations(paymentDetails.locale); var isFramed = false; try { @@ -215,10 +228,6 @@ function emitPaymentStatus(paymentDetails) { * - Initialize SDK **/ function boot() { - - // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; - // Emit latest payment status if (isFramed) { emitPaymentStatus(paymentDetails); @@ -435,7 +444,7 @@ function initializeEventListeners(paymentDetails) { if (paymentForm instanceof HTMLFormElement) { paymentForm.addEventListener("submit", function (event) { event.preventDefault(); - handleSubmit(event); + handleSubmit(event, paymentDetails); }) } @@ -447,18 +456,20 @@ function initializeEventListeners(paymentDetails) { function handleFormReadyForSubmission() { window.addEventListener("message", function (event) { // Event listener for updating the button rules - if (isObject(event.data) && event.data["isFormReadyForSubmission"] !== null) { - let isFormReadyForSubmission = event.data["isFormReadyForSubmission"]; - var submitButtonNode = document.getElementById("submit"); - if (submitButtonNode instanceof HTMLButtonElement) { - if (isFormReadyForSubmission === false) { - submitButtonNode.disabled = true; - addClass("#submit", "not-ready"); - addClass("#submit", "disabled"); - } else if (isFormReadyForSubmission === true) { - submitButtonNode.disabled = false; - removeClass("#submit", "not-ready"); - removeClass("#submit", "disabled"); + if (event.origin == "{{sdk_origin}}") { + if (isObject(event.data) && event.data["isFormReadyForSubmission"] !== null) { + let isFormReadyForSubmission = event.data["isFormReadyForSubmission"]; + var submitButtonNode = document.getElementById("submit"); + if (submitButtonNode instanceof HTMLButtonElement) { + if (isFormReadyForSubmission === false) { + submitButtonNode.disabled = true; + addClass("#submit", "not-ready"); + addClass("#submit", "disabled"); + } else if (isFormReadyForSubmission === true) { + submitButtonNode.disabled = false; + removeClass("#submit", "not-ready"); + removeClass("#submit", "disabled"); + } } } } @@ -504,12 +515,10 @@ function mountUnifiedCheckout(id) { * - Toggle UI loaders appropriately * - Handle errors and redirect to status page * @param {Event} e + * @param {PaymentDetails} paymentDetails */ // @ts-ignore -function handleSubmit(e) { - // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; - +function handleSubmit(e, paymentDetails) { // Update button loader hide("#submit-button-text"); show("#submit-spinner"); @@ -553,7 +562,7 @@ function handleSubmit(e) { url.search = params.toString(); window.top.location.href = url.toString(); } else { - redirectToStatus(); + redirectToStatus(paymentDetails); } }) .catch(function (error) { @@ -772,25 +781,33 @@ function appendMerchantDetails(paymentDetails, merchantDynamicDetails) { ); var horizontalLine = document.createElement("hr"); horizontalLine.className = "hyper-checkout-payment-horizontal-line"; - horizontalLineContainer.append(horizontalLine); + if (horizontalLineContainer instanceof HTMLDivElement) { + horizontalLineContainer.append(horizontalLine); + } // max number of items to show in the merchant details let maxItemsInDetails = 50; for (var item of merchantDetailsObject) { var merchantData = document.createElement("div"); merchantData.className = "hyper-checkout-payment-merchant-dynamic-data"; + var keyNode = document.createElement("span"); + keyNode.textContent = item.key; + var valueNode = document.createElement("span"); + valueNode.textContent = item.value; // make the key and value bold if specified in the ui_configuration - var key = item.ui_configuration - ? item.ui_configuration.is_key_bold - ? item.key.bold() - : item.key - : item.key; - var value = item.ui_configuration - ? item.ui_configuration.is_value_bold - ? item.value.bold() - : item.value - : item.value; - merchantData.innerHTML = key + " : " + value; + if (isObject(item.ui_configuration)) { + if (item.ui_configuration.is_key_bold) { + keyNode.style.fontWeight = "bold"; + } + if (item.ui_configuration.is_value_bold) { + valueNode.style.fontWeight = "bold"; + } + } + var separatorNode = document.createElement("span"); + separatorNode.textContent = " : "; + merchantData.appendChild(keyNode); + merchantData.appendChild(separatorNode); + merchantData.appendChild(valueNode); merchantDynamicDetails.append(merchantData); if (--maxItemsInDetails === 0) { diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js index effd27cc64a..33758131aa2 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -9,7 +9,8 @@ **/ function initializeSDK() { // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; + var encodedPaymentDetails = window.__PAYMENT_DETAILS; + var paymentDetails = decodeUri(encodedPaymentDetails); var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; var labelType = paymentDetails.payment_form_label_type; @@ -99,8 +100,7 @@ function initializeSDK() { /** * Use - redirect to /payment_link/status */ -function redirectToStatus() { - var paymentDetails = window.__PAYMENT_DETAILS; +function redirectToStatus(paymentDetails) { var arr = window.location.pathname.split("/"); // NOTE - This code preserves '/api' in url for integ and sbx diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index 446428e6ff3..3db5eb94de2 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -123,8 +123,7 @@ if (!isFramed) { /** * Use - redirect to /payment_link/status */ - function redirectToStatus() { - var paymentDetails = window.__PAYMENT_DETAILS; + function redirectToStatus(paymentDetails) { var arr = window.location.pathname.split("/"); // NOTE - This code preserves '/api' in url for integ and sbx envs diff --git a/crates/router/src/core/payment_link/payment_link_status/status.js b/crates/router/src/core/payment_link/payment_link_status/status.js index 16949d546a6..371fdf1d2df 100644 --- a/crates/router/src/core/payment_link/payment_link_status/status.js +++ b/crates/router/src/core/payment_link/payment_link_status/status.js @@ -4,6 +4,16 @@ * UTIL FUNCTIONS */ +function decodeUri(uri) { + try { + var uriStr = decodeURIComponent(uri); + return JSON.parse(uriStr); + } catch (e) { + console.error("Error decoding and parsing string URI:", e); + return uri; + } +} + /** * Ref - https://github.com/onury/invert-color/blob/master/lib/cjs/invert.js */ @@ -86,7 +96,12 @@ window.state = { isMobileView: window.innerWidth <= 1400, }; -const translations = getTranslations(window.__PAYMENT_DETAILS.locale); +// @ts-ignore +var encodedPaymentDetails = window.__PAYMENT_DETAILS; +var paymentDetails = decodeUri(encodedPaymentDetails); + +// @ts-ignore +const translations = getTranslations(paymentDetails.locale); var isFramed = false; try { @@ -122,9 +137,6 @@ function emitPaymentStatus(paymentDetails) { * - Initialize SDK **/ function boot() { - // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; - // Emit latest payment status if (isFramed) { emitPaymentStatus(paymentDetails); @@ -272,7 +284,7 @@ function renderStatusDetails(paymentDetails) { var merchantLogoNode = document.createElement("img"); merchantLogoNode.className = "hyper-checkout-status-merchant-logo"; // @ts-ignore - merchantLogoNode.src = window.__PAYMENT_DETAILS.merchant_logo; + merchantLogoNode.src = paymentDetails.merchant_logo; merchantLogoNode.alt = ""; // Form content items diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 4a2b3d75204..7e13dbbed16 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -400,7 +400,7 @@ pub async fn render_pm_collect_link( let generic_form_data = services::GenericLinkFormData { js_data: serialized_js_content, css_data: serialized_css_content, - sdk_url: default_config.sdk_url.to_string(), + sdk_url: default_config.sdk_url.clone(), html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 063529e21fe..06edca897dc 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -260,7 +260,7 @@ pub async fn initiate_payout_link( let generic_form_data = services::GenericLinkFormData { js_data: serialized_js_content, css_data: serialized_css_content, - sdk_url: default_config.sdk_url.to_string(), + sdk_url: default_config.sdk_url.clone(), html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 76a2b9e50e6..2ae0c68ccef 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1877,6 +1877,30 @@ fn build_payment_link_template( let _ = tera.add_raw_template("payment_link_js", &js_template); context.insert("payment_details_js_script", &payment_link_data.js_script); + let sdk_origin = payment_link_data + .sdk_url + .host_str() + .ok_or_else(|| { + logger::error!("Host missing for payment link SDK URL"); + report!(errors::ApiErrorResponse::InternalServerError) + }) + .and_then(|host| { + if host == "localhost" { + let port = payment_link_data.sdk_url.port().ok_or_else(|| { + logger::error!("Port missing for localhost in SDK URL"); + report!(errors::ApiErrorResponse::InternalServerError) + })?; + Ok(format!( + "{}://{}:{}", + payment_link_data.sdk_url.scheme(), + host, + port + )) + } else { + Ok(format!("{}://{}", payment_link_data.sdk_url.scheme(), host)) + } + })?; + context.insert("sdk_origin", &sdk_origin); let rendered_js = match tera.render("payment_link_js", &context) { Ok(rendered_js) => rendered_js, @@ -1954,11 +1978,11 @@ pub fn build_secure_payment_link_html( .attach_printable("Error while rendering secure payment link's HTML template") } -fn get_hyper_loader_sdk(sdk_url: &str) -> String { +fn get_hyper_loader_sdk(sdk_url: &url::Url) -> String { format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>") } -fn get_preload_link_html_template(sdk_url: &str) -> String { +fn get_preload_link_html_template(sdk_url: &url::Url) -> String { format!( r#"<link rel="preload" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" as="style"> <link rel="preload" href="{sdk_url}" as="script">"#,
2025-04-07T10:15:29Z
## Description This PR addresses below issues specifically for payment links - improper use of innerHTML for API inputs - for rendering transaction details - improper use of receiving event (isFormReadyForSubmission) from HS SDK Overall, this PR sanitizes API text based inputs which are rendered in the payment link UI using URI encoding before rendering the payment link HTML response. The URI encoded data is decoded in JS runtime (browser) and consumed whenever required. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
4ad0492a88ec2c53b9c70af9a999fc3127c19345
Tested locally <details> <summary>1. Create payment links and process redirection based txns (3DS)</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ML2p8kRGcMvi4oQ3cPnIfz5R2rO31efjWKXzgMnbRCnj5pUpjiki8K2HONlmMAb4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_9SCrW9x19m2WbGYHprJS","profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#003264","skip_status_screen":true,"transaction_details":[{"key":"a","value":"<script href=\"https://www.somesite.com\"></script>","ui_configuration":{"is_key_bold":true,"is_value_bold":true}}],"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response {"payment_id":"pay_DrqIRGsc6hs4BP3GVe56","merchant_id":"merchant_1743758708","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_DrqIRGsc6hs4BP3GVe56_secret_5g2zaDCBZlK5ebBSQnF7","created":"2025-04-07T10:11:02.890Z","currency":"EUR","customer_id":"cus_9SCrW9x19m2WbGYHprJS","customer":{"id":"cus_9SCrW9x19m2WbGYHprJS","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_9SCrW9x19m2WbGYHprJS","created_at":1744020662,"expires":1744024262,"secret":"epk_e9bec308a59f4550adf8dd6b7b57506f"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1743758708/pay_DrqIRGsc6hs4BP3GVe56?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1743758708/pay_DrqIRGsc6hs4BP3GVe56?locale=en","payment_link_id":"plink_qOUNfvUvtkTK7K8sXBoU"},"profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-07T10:26:02.875Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-07T10:11:02.944Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"issuer_error_code":null,"issuer_error_message":null} Verify below things 1. Redirection works as expected 2. Payment journey is as expected </details> <details> <summary>2. Create payment links and process redirection based txns (3DS)</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ML2p8kRGcMvi4oQ3cPnIfz5R2rO31efjWKXzgMnbRCnj5pUpjiki8K2HONlmMAb4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_9SCrW9x19m2WbGYHprJS","profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#003264","skip_status_screen":true,"transaction_details":[{"key":"a","value":"<script href=\"https://www.somesite.com\"></script>","ui_configuration":{"is_key_bold":true,"is_value_bold":true}}],"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response {"payment_id":"pay_Gw2avLXsTOJUSvESS1ig","merchant_id":"merchant_1743758708","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_Gw2avLXsTOJUSvESS1ig_secret_XthFTGPAmHOvIG4wf0lf","created":"2025-04-07T10:12:36.809Z","currency":"EUR","customer_id":"cus_9SCrW9x19m2WbGYHprJS","customer":{"id":"cus_9SCrW9x19m2WbGYHprJS","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_9SCrW9x19m2WbGYHprJS","created_at":1744020756,"expires":1744024356,"secret":"epk_4baa462e06a34161875cda39626e0612"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1743758708/pay_Gw2avLXsTOJUSvESS1ig?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1743758708/pay_Gw2avLXsTOJUSvESS1ig?locale=en","payment_link_id":"plink_kN6v8N8kffrl3cdX3sf7"},"profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-07T10:27:36.806Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-07T10:12:36.831Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"issuer_error_code":null,"issuer_error_message":null} Verify below things 1. Payment journey is as expected </details> <details> <summary>3. Give improper data for the text fields to be rendered in transaction_details</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ML2p8kRGcMvi4oQ3cPnIfz5R2rO31efjWKXzgMnbRCnj5pUpjiki8K2HONlmMAb4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_9SCrW9x19m2WbGYHprJS","profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#003264","skip_status_screen":true,"transaction_details":[{"key":"a","value":"<script href=\"https://www.somesite.com\"></script>","ui_configuration":{"is_key_bold":true,"is_value_bold":true}}],"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response {"payment_id":"pay_U31G1jOtO9PLlEAhaCnh","merchant_id":"merchant_1743758708","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_U31G1jOtO9PLlEAhaCnh_secret_pdVAtxEgm8M2EXyvQekZ","created":"2025-04-07T10:13:54.256Z","currency":"EUR","customer_id":"cus_9SCrW9x19m2WbGYHprJS","customer":{"id":"cus_9SCrW9x19m2WbGYHprJS","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_9SCrW9x19m2WbGYHprJS","created_at":1744020834,"expires":1744024434,"secret":"epk_4e5e8c040ef24d22841731b62003d0cb"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1743758708/pay_U31G1jOtO9PLlEAhaCnh?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1743758708/pay_U31G1jOtO9PLlEAhaCnh?locale=en","payment_link_id":"plink_PH1XXvtv2yl3N9Kh9It8"},"profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-07T10:28:54.250Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-07T10:13:54.276Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"issuer_error_code":null,"issuer_error_message":null} Verify below things 1. Giving any malformed script or any other tags in `transaction_details` renders it as a text <img width="658" alt="Screenshot 2025-04-07 at 3 44 37 PM" src="https://github.com/user-attachments/assets/973c69d4-c429-45af-9d06-9559faffca26" /> </details>
[ "crates/hyperswitch_domain_models/src/api.rs", "crates/router/src/configs/settings.rs", "crates/router/src/core/payment_link.rs", "crates/router/src/core/payment_link/payment_link_initiate/payment_link.js", "crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js", "crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js", "crates/router/src/core/payment_link/payment_link_status/status.js", "crates/router/src/core/payment_methods.rs", "crates/router/src/core/payout_link.rs", "crates/router/src/services/api.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7734
Bug: chore: address Rust 1.86.0 clippy lints Address the clippy lints occurring due to new rust version 1.86.0 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 11c9b17fae6..c96fdd3ca57 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -125,7 +125,7 @@ impl<const PRECISION: u8> Percentage<PRECISION> { fn is_valid_precision_length(value: &str) -> bool { if value.contains('.') { // if string has '.' then take the decimal part and verify precision length - match value.split('.').last() { + match value.split('.').next_back() { Some(decimal_part) => { decimal_part.trim_end_matches('0').len() <= <u8 as Into<usize>>::into(PRECISION) } diff --git a/crates/common_utils/src/validation.rs b/crates/common_utils/src/validation.rs index 9403e6720a9..007674a0db1 100644 --- a/crates/common_utils/src/validation.rs +++ b/crates/common_utils/src/validation.rs @@ -26,6 +26,8 @@ pub fn validate_phone_number(phone_number: &str) -> Result<(), ValidationError> pub fn validate_email(email: &str) -> CustomResult<(), ValidationError> { #[deny(clippy::invalid_regex)] static EMAIL_REGEX: Lazy<Option<Regex>> = Lazy::new(|| { + #[allow(unknown_lints)] + #[allow(clippy::manual_ok_err)] match Regex::new( r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$", ) { diff --git a/crates/euclid/src/backend/vir_interpreter.rs b/crates/euclid/src/backend/vir_interpreter.rs index 7fde8721be0..50420ecd1c4 100644 --- a/crates/euclid/src/backend/vir_interpreter.rs +++ b/crates/euclid/src/backend/vir_interpreter.rs @@ -40,13 +40,15 @@ where } fn eval_statement(stmt: &vir::ValuedIfStatement, ctx: &types::Context) -> bool { - Self::eval_condition(&stmt.condition, ctx) - .then(|| { + if Self::eval_condition(&stmt.condition, ctx) { + { stmt.nested.as_ref().map_or(true, |nested_stmts| { nested_stmts.iter().any(|s| Self::eval_statement(s, ctx)) }) - }) - .unwrap_or(false) + } + } else { + false + } } fn eval_rule(rule: &vir::ValuedRule<O>, ctx: &types::Context) -> bool { diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs index b42e3b7f1fc..165fde6476b 100644 --- a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs +++ b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs @@ -747,7 +747,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .change_context(errors::ConnectorError::ResponseHandlingFailed)?; // If location headers are not present connector will return 4XX so this error will never be propagated let payment_fields_token = location .split('/') - .last() + .next_back() .ok_or(errors::ConnectorError::ResponseHandlingFailed)? .to_string(); diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs index 7c49cfe93dc..b8ebe76e5d1 100644 --- a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs @@ -308,7 +308,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues let apple_pay_payment_data = payment_method_data.get_applepay_decoded_payment_data()?; let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data - .expose()[..] + .expose() .as_bytes() .parse_struct("ApplePayEncodedPaymentData") .change_context(errors::ConnectorError::InvalidWalletToken { diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 101a9b753ad..11e6de3ac6b 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -402,7 +402,7 @@ impl ChargebeeCustomer { .ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)? .to_string(); let mandate_id = parts - .last() + .next_back() .ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)? .to_string(); Ok(ChargebeeMandateDetails { diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs index 57caa65ba8c..57e207c9c78 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs @@ -1373,7 +1373,7 @@ pub fn construct_file_upload_request( .file_type .as_ref() .split('/') - .last() + .next_back() .unwrap_or_default() )) .mime_str(request.file_type.as_ref()) diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index 086763635b6..59c76c64be5 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -78,8 +78,8 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) - | PaymentMethodData::MandatePayment {} - | PaymentMethodData::Reward {} + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::MobilePayment(_) diff --git a/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs index 31265162ca0..03e7d9bd298 100644 --- a/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs @@ -137,8 +137,8 @@ impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePay | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) - | PaymentMethodData::MandatePayment {} - | PaymentMethodData::Reward {} + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) diff --git a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs index 400125e2cdc..ee658d8a0fa 100644 --- a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs @@ -353,8 +353,8 @@ impl TryFrom<&NoonRouterData<&PaymentsAuthorizeRouterData>> for NoonPaymentsRequ | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) - | PaymentMethodData::MandatePayment {} - | PaymentMethodData::Reward {} + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs index 5d2d6db91fb..02d2b0e7aef 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs @@ -148,7 +148,7 @@ impl Paypal { if let Some(field) = error .field .as_ref() - .and_then(|field| field.split('/').last()) + .and_then(|field| field.split('/').next_back()) { reason.push_str(&format!(", field - {field}")); } diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index 95f9979762a..b843b4d0c38 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -331,8 +331,8 @@ impl TryFrom<&ConnectorAuthType> for SquareAuthType { | ConnectorAuthType::SignatureKey { .. } | ConnectorAuthType::MultiAuthKey { .. } | ConnectorAuthType::CurrencyAuthKey { .. } - | ConnectorAuthType::TemporaryAuth { .. } - | ConnectorAuthType::NoKey { .. } + | ConnectorAuthType::TemporaryAuth + | ConnectorAuthType::NoKey | ConnectorAuthType::CertificateAuth { .. } => { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } diff --git a/crates/hyperswitch_connectors/src/connectors/volt.rs b/crates/hyperswitch_connectors/src/connectors/volt.rs index 5bd6065d57f..a8c5a5298d6 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt.rs @@ -663,7 +663,7 @@ impl webhooks::IncomingWebhook for Volt { let user_agent = utils::get_header_key_value(webhook_headers::USER_AGENT, request.headers)?; let version = user_agent .split('/') - .last() + .next_back() .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(format!( "{}|{}|{}", diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index a42bffa3bc0..4628eaf116e 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -1099,13 +1099,14 @@ impl IncomingWebhook for Worldpay { request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let event_signature = get_header_key_value("Event-Signature", request.headers)?.split(','); + let mut event_signature = + get_header_key_value("Event-Signature", request.headers)?.split(','); let sign_header = event_signature - .last() + .next_back() .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; let signature = sign_header .split('/') - .last() + .next_back() .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; hex::decode(signature).change_context(errors::ConnectorError::WebhookResponseEncodingFailed) } diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index ba3065c752b..d5ebe6d6957 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -282,7 +282,7 @@ impl VoucherData::PagoEfectivo => ZenPaymentChannels::PclBoacompraPagoefectivo, VoucherData::RedCompra => ZenPaymentChannels::PclBoacompraRedcompra, VoucherData::RedPagos => ZenPaymentChannels::PclBoacompraRedpagos, - VoucherData::Oxxo { .. } + VoucherData::Oxxo | VoucherData::Alfamart { .. } | VoucherData::Indomaret { .. } | VoucherData::SevenEleven { .. } diff --git a/crates/router/src/connector/netcetera/netcetera_types.rs b/crates/router/src/connector/netcetera/netcetera_types.rs index 4869c228b41..b79eab200e5 100644 --- a/crates/router/src/connector/netcetera/netcetera_types.rs +++ b/crates/router/src/connector/netcetera/netcetera_types.rs @@ -1113,8 +1113,8 @@ pub struct MerchantRiskIndicator { /// New field introduced: /// - transChar -> Indicates to the ACS specific transactions identified by the Merchant. /// - Size: Variable, 1-2 elements. JSON Data Type: Array of String. Accepted values: - /// - 01 -> Cryptocurrency transaction - /// - 02 -> NFT transaction + /// - 01 -> Cryptocurrency transaction + /// - 02 -> NFT transaction trans_char: Option<String>, } @@ -1558,19 +1558,19 @@ pub struct Sdk { /// Creates a JSON object of the following data as the JWS payload to be signed: /// /// - SDK Reference Number -> Identifies the vendor and version of the 3DS SDK that is utilised for a specific - /// transaction. The value is assigned by EMVCo when the Letter of Approval of the - /// specific 3DS SDK is issued. The field is limited to 32 characters. + /// transaction. The value is assigned by EMVCo when the Letter of Approval of the + /// specific 3DS SDK is issued. The field is limited to 32 characters. /// - SDK Signature Timestamp -> Date and time indicating when the 3DS SDK generated the Split-SDK Server Signed - /// Content converted into UTC. The value is limited to 14 characters. Accepted - /// format: YYYYMMDDHHMMSS. + /// Content converted into UTC. The value is limited to 14 characters. Accepted + /// format: YYYYMMDDHHMMSS. /// - SDK Transaction ID -> Universally unique transaction identifier assigned by the 3DS SDK to identify a - /// single transaction. The field is limited to 36 characters and it shall be in a - /// canonical format as defined in IETF RFC 4122. This may utilize any of the specified - /// versions as long as the output meets specific requirements. + /// single transaction. The field is limited to 36 characters and it shall be in a + /// canonical format as defined in IETF RFC 4122. This may utilize any of the specified + /// versions as long as the output meets specific requirements. /// - Split-SDK Server ID -> DS assigned Split-SDK Server identifier. Each DS can provide a unique ID to each - /// Split-SDK Server on an individual basis. The field is limited to 32 characters. - /// Any individual DS may impose specific formatting and character requirements on the - /// contents of this field. + /// Split-SDK Server on an individual basis. The field is limited to 32 characters. + /// Any individual DS may impose specific formatting and character requirements on the + /// contents of this field. /// /// Generates a digital signature of the full JSON object according to JWS (RFC 7515) using JWS Compact /// Serialization. The parameter values for this version of the specification and to be included in the JWS @@ -1705,7 +1705,7 @@ pub struct SplitSdkType { /// Limited Split-SDK Indicator: If the Split-SDK client has limited capabilities /// - Length: 1 character /// - Value accepted: - /// • Y = Limited + /// • Y = Limited /// - Only present if value = Y limited_ind: Option<String>, } diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs index 1751c70fe97..8e3fb560ceb 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/router/src/connector/netcetera/transformers.rs @@ -700,9 +700,9 @@ pub struct ResultsResponseData { /// - `U`: Authentication / Account verification could not be performed; technical or other problem. /// - `C`: A challenge is required to complete the authentication. /// - `R`: Authentication / Account verification Rejected. Issuer is rejecting authentication/verification - /// and request that authorization not be attempted. + /// and request that authorization not be attempted. /// - `A`: Attempts processing performed; Not authenticated / verified, but a proof of attempt - /// authentication / verification is provided. + /// authentication / verification is provided. /// - `D`: A challenge is required to complete the authentication. Decoupled Authentication confirmed. /// - `I`: Informational Only; 3DS Requestor challenge preference acknowledged. pub trans_status: Option<common_enums::TransactionStatus>, diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index 093e0a72d10..ee299403b69 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -178,7 +178,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::RequestTimeoutReceived | errors::ConnectorError::CurrencyNotSupported { .. } | errors::ConnectorError::InvalidConnectorConfig { .. } - | errors::ConnectorError::AmountConversionFailed { .. } + | errors::ConnectorError::AmountConversionFailed | errors::ConnectorError::GenericError { .. } => { err.change_context(errors::ApiErrorResponse::RefundFailed { data: None }) } @@ -369,7 +369,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::RequestTimeoutReceived | errors::ConnectorError::CurrencyNotSupported { .. } | errors::ConnectorError::ProcessingStepFailed(None) - | errors::ConnectorError::AmountConversionFailed { .. } + | errors::ConnectorError::AmountConversionFailed | errors::ConnectorError::GenericError { .. } => { logger::error!(%error,"Setup Mandate flow failed"); errors::ApiErrorResponse::PaymentAuthorizationFailed { data: None } diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index a0f651b93c3..e8b1e83b250 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -78,9 +78,9 @@ impl Event for AuditEvent { AuditEventType::RefundFail => "refund_fail", AuditEventType::PaymentCancelled { .. } => "payment_cancelled", AuditEventType::PaymentUpdate { .. } => "payment_update", - AuditEventType::PaymentApprove { .. } => "payment_approve", - AuditEventType::PaymentCreate { .. } => "payment_create", - AuditEventType::PaymentStatus { .. } => "payment_status", + AuditEventType::PaymentApprove => "payment_approve", + AuditEventType::PaymentCreate => "payment_create", + AuditEventType::PaymentStatus => "payment_status", AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize", AuditEventType::PaymentReject { .. } => "payment_rejected", }; diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 84caf9ad765..d06f4a604c9 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -68,7 +68,7 @@ impl CashtocodeTest { router_return_url: Some(String::from("https://google.com")), webhook_url: None, complete_authorize_url: None, - customer_id: if let Ok(id) = cust_id { Some(id) } else { None }, + customer_id: cust_id.ok(), surcharge_details: None, request_incremental_authorization: false, metadata: None,
2025-04-07T08:57:34Z
## Description <!-- Describe your changes in detail --> This PR addresses the clippy lints occurring due to new rust version 1.86.0 https://rust-lang.github.io/rust-clippy/master/index.html #
0a5d2495435ff737dd952c97e5dcd0fc52839258
CI checks should pass as this PR addresses clippy lints. 1. ran `rustc --version` ![image](https://github.com/user-attachments/assets/b154032b-dff4-4582-b525-9b97ce83ce55) 3. ran `just clippy` with new rust version (1.86.0) <img width="1004" alt="Screenshot 2025-04-07 at 5 46 05 PM" src="https://github.com/user-attachments/assets/5951c74e-8f3d-44e2-8172-e376c01c2e9d" /> 4. ran `just clippy_v2` with new rust version (1.86.0) <img width="1019" alt="Screenshot 2025-04-07 at 5 46 38 PM" src="https://github.com/user-attachments/assets/ecdf5c2a-dc31-45b4-be01-cedc041cf59d" />
[ "crates/common_utils/src/types.rs", "crates/common_utils/src/validation.rs", "crates/euclid/src/backend/vir_interpreter.rs", "crates/hyperswitch_connectors/src/connectors/bluesnap.rs", "crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs", "crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs", "crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs", "crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/forte/transformers.rs", "crates/hyperswitch_connectors/src/connectors/noon/transformers.rs", "crates/hyperswitch_connectors/src/connectors/paypal.rs", "crates/hyperswitch_connectors/src/connectors/square/transformers.rs", "crates/hyperswitch_connectors/src/connectors/volt.rs", "crates/hyperswitch_connectors/src/connectors/worldpay.rs", "crates/hyperswitch_connectors/src/connectors/zen/transformers.rs", "crates/router/src/connector/netcetera/netcetera_types.rs", "crates/router/src/connector/netcetera/transformers.rs", "crates/router/src/core/errors/utils.rs", "crates/router/src/events/audit_events.rs", "crates/router/tests/connectors/cashtocode.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7729
Bug: refactor(postman): update `Stripe` response `status`, `error_code`, and `error_message` for deprecated `Sofort` Map `status`, `error_code`, and `error_message` for `Stripe` Payment Processor `Sofort` Bank Transfer Payment Method as `Sofort` has been deprecated by `Stripe`.
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js index aa8d32b0cf2..c2e29faee5a 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js @@ -63,21 +63,21 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "requires_customer_action" for "status" +// Response body should have value "failed" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'", + "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'failed'", function () { - pm.expect(jsonData.status).to.eql("requires_customer_action"); + pm.expect(jsonData.status).to.eql("failed"); }, ); } -// Response body should have "next_action.redirect_to_url" +// Response body should have "next_action" pm.test( - "[POST]::/payments - Content check if 'next_action.redirect_to_url' exists", + "[POST]::/payments - Content check if 'next_action' exists", function () { - pm.expect(typeof jsonData.next_action.redirect_to_url !== "undefined").to.be + pm.expect(typeof jsonData.next_action !== "undefined").to.be .true; }, ); @@ -92,6 +92,26 @@ if (jsonData?.payment_method_type) { ); } +// Response body should have value "payment_method_not_available" for "error_code" +if (jsonData?.error_code) { + pm.test( + "[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'payment_method_not_available'", + function () { + pm.expect(jsonData.error_code).to.eql("payment_method_not_available"); + }, + ); +} + +// Response body should have value "Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort" for "error_message" +if (jsonData?.error_message) { + pm.test( + "[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort'", + function () { + pm.expect(jsonData.error_message).to.eql("Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort"); + }, + ); +} + // Response body should have value "stripe" for "connector" if (jsonData?.connector) { pm.test( diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js index 9053ddab13b..e99ef624bf2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js @@ -60,12 +60,32 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "requires_customer_action" for "status" +// Response body should have value "failed" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'", + "[POST]::/payments:id - Content check if value for 'status' matches 'failed'", function () { - pm.expect(jsonData.status).to.eql("requires_customer_action"); + pm.expect(jsonData.status).to.eql("failed"); }, ); } + +// Response body should have value "payment_method_not_available" for "error_code" +if (jsonData?.error_code) { + pm.test( + "[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'payment_method_not_available'", + function () { + pm.expect(jsonData.error_code).to.eql("payment_method_not_available"); + }, + ); +} + +// Response body should have value "Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort" for "error_message" +if (jsonData?.error_message) { + pm.test( + "[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort'", + function () { + pm.expect(jsonData.error_message).to.eql("Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort"); + }, + ); +} \ No newline at end of file
2025-04-04T15:28:17Z
## Description <!-- Describe your changes in detail --> Mapping `status`, `error_code`, and `error_message` for `Stripe` Payment Processor `Sofort` Bank Transfer Payment Method as `Sofort` has been deprecated by `Stripe`. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> `Stripe` Payment Processor has deprecated `Sofort` Bank Transfer Payment Method. #
961c875ecc225c924160448f01bf38a8e5a4ca03
_Before_ <img width="1728" alt="image" src="https://github.com/user-attachments/assets/96c27305-04fb-4839-a91b-84ed69bc4ced" /> _After_ <img width="1727" alt="image" src="https://github.com/user-attachments/assets/50881bf2-8fb0-4b7f-8a96-2742e55d6c76" />
[ "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js", "postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js", "postman/collection-dir/stripe/Flow" ]
juspay/hyperswitch
juspay__hyperswitch-7728
Bug: [DOCS] Intelligent router open api ### Feature Description Open API spec for intelligent router ### Possible Implementation Open API spec for intelligent router ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
2025-04-04T13:25:55Z
## Description <!-- Describe your changes in detail --> Open API reference for Intelligent router ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
961c875ecc225c924160448f01bf38a8e5a4ca03
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/7df6c90a-a125-4dfb-aa36-6072881ecc23" />
[]
juspay/hyperswitch
juspay__hyperswitch-7723
Bug: Add invoice number and email in AuthorizeDotNet connector Add invoice number and email in AuthorizeDotNet connector
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index bb93d9279de..9bd809c124f 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -5,6 +5,7 @@ use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::{Encode, OptionExt, ValueExt}, + pii::Email, request::Method, }; use error_stack::ResultExt; @@ -36,6 +37,12 @@ use crate::{ }, }; +const MAX_ID_LENGTH: usize = 20; + +fn get_random_string() -> String { + Alphanumeric.sample_string(&mut rand::thread_rng(), MAX_ID_LENGTH) +} + #[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "authCaptureTransaction")] @@ -207,6 +214,7 @@ struct PaymentProfileDetails { #[serde(rename_all = "camelCase")] pub struct CustomerDetails { id: String, + email: Option<Email>, } #[derive(Debug, Serialize)] @@ -230,6 +238,7 @@ pub struct BillTo { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Order { + invoice_number: String, description: String, } @@ -611,7 +620,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>> let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; - let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 { + let ref_id = if item.router_data.connector_request_reference_id.len() <= MAX_ID_LENGTH { Some(item.router_data.connector_request_reference_id.clone()) } else { None @@ -727,9 +736,17 @@ impl }), profile: None, order: Order { + invoice_number: get_random_string(), description: item.router_data.connector_request_reference_id.clone(), }, - customer: None, + customer: Some(CustomerDetails { + id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { + item.router_data.payment_id.clone() + } else { + get_random_string() + }, + email: item.router_data.request.get_optional_email(), + }), bill_to: item .router_data .get_optional_billing() @@ -798,9 +815,17 @@ impl }) }), order: Order { + invoice_number: get_random_string(), description: item.router_data.connector_request_reference_id.clone(), }, - customer: None, + customer: Some(CustomerDetails { + id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { + item.router_data.payment_id.clone() + } else { + get_random_string() + }, + email: item.router_data.request.get_optional_email(), + }), bill_to: None, user_fields: match item.router_data.request.metadata.clone() { Some(metadata) => Some(UserFields { @@ -835,24 +860,21 @@ impl &Card, ), ) -> Result<Self, Self::Error> { - let (profile, customer) = if item.router_data.request.is_mandate_payment() { - ( - Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { - create_profile: true, - })), - Some(CustomerDetails { - //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate. - //If the length exceeds 20 characters, a random alphanumeric string is used instead. - id: if item.router_data.payment_id.len() <= 20 { - item.router_data.payment_id.clone() - } else { - Alphanumeric.sample_string(&mut rand::thread_rng(), 20) - }, - }), - ) - } else { - (None, None) - }; + let (profile, customer) = ( + Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { + create_profile: true, + })), + Some(CustomerDetails { + //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate. + //If the length exceeds 20 characters, a random alphanumeric string is used instead. + id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { + item.router_data.payment_id.clone() + } else { + get_random_string() + }, + email: item.router_data.request.get_optional_email(), + }), + ); Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, @@ -864,6 +886,7 @@ impl })), profile, order: Order { + invoice_number: get_random_string(), description: item.router_data.connector_request_reference_id.clone(), }, customer, @@ -911,23 +934,19 @@ impl &WalletData, ), ) -> Result<Self, Self::Error> { - let (profile, customer) = if item.router_data.request.is_mandate_payment() { - ( - Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { - create_profile: true, - })), - Some(CustomerDetails { - id: if item.router_data.payment_id.len() <= 20 { - item.router_data.payment_id.clone() - } else { - Alphanumeric.sample_string(&mut rand::thread_rng(), 20) - }, - }), - ) - } else { - (None, None) - }; - + let (profile, customer) = ( + Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { + create_profile: true, + })), + Some(CustomerDetails { + id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { + item.router_data.payment_id.clone() + } else { + get_random_string() + }, + email: item.router_data.request.get_optional_email(), + }), + ); Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, @@ -938,6 +957,7 @@ impl )?), profile, order: Order { + invoice_number: get_random_string(), description: item.router_data.connector_request_reference_id.clone(), }, customer,
2025-04-04T13:24:23Z
## Description <!-- Describe your changes in detail --> Added invoice number and email in AuthorizeDotNet connector ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This feature is a merchant ask. They need it to claim chargebacks. #
e88672c97cc02001fb656e550cd670eda424d9c9
Postman Tests 1. Connector Create - AuthorizeDotNet Request: ``` curl --location 'http://localhost:8080/account/merchant_1744026981/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Y3QfvvJdv4BhlHCTUDfWpwTPLyZnFw3nSkJ3pDAOL1ZJvW7foEdck5LuqNh5N1Nj' \ --data '{ "connector_type": "payment_processor", "connector_name": "authorizedotnet", "connector_account_details": { "auth_type": "BodyKey", "api_key": "API KEY", "key1": "KEY1" }, "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": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "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 } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default", }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "authorizedotnet", "connector_label": "authorizedotnet_US_default", "merchant_connector_id": "mca_z9HhKBpL6GKf6kLyTqzO", "profile_id": "pro_APc2BIFDjU2pAlUnqbD0", "connector_account_details": { "auth_type": "BodyKey", "api_key": "29*****G3", "key1": "34************nv" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "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": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, } ``` 2. Payments - Create Request: ``` { "amount": 35308, "currency": "USD", "confirm": false, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country":"US", "first_name": "PiX" } } } ``` Response: ``` { "payment_id": "pay_AhwRHSRSeXE0HUgmIDh4", "merchant_id": "merchant_1744026981", "status": "requires_payment_method", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_AhwRHSRSeXE0HUgmIDh4_secret_rlGIHoYt8wloO4iCKQmq", "created": "2025-04-07T11:56:35.755Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1744026995, "expires": 1744030595, "secret": "epk_0d1d33b9a9964dd08fda3c8894ea808a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_APc2BIFDjU2pAlUnqbD0", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-07T12:11:35.755Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-07T11:56:35.794Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "issuer_error_code": null, "issuer_error_message": null } ``` 3. Payments - Confirm Request: ``` { "connector": ["authorizedotnet"], "capture_method": "automatic", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "370000000000002", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` Response: ``` { "payment_id": "pay_AhwRHSRSeXE0HUgmIDh4", "merchant_id": "merchant_1744026981", "status": "succeeded", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": 35308, "connector": "authorizedotnet", "client_secret": "pay_AhwRHSRSeXE0HUgmIDh4_secret_rlGIHoYt8wloO4iCKQmq", "created": "2025-04-07T11:56:35.755Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0002", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "370000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "120060815605", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "120060815605", "payment_link": null, "profile_id": "pro_APc2BIFDjU2pAlUnqbD0", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_z9HhKBpL6GKf6kLyTqzO", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-07T12:11:35.755Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-07T11:56:41.667Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } ``` Screenshot of the AuthorizeDotNet Sandbox dashboard: <img width="1286" alt="Screenshot 2025-04-04 at 6 56 52 PM" src="https://github.com/user-attachments/assets/2ca2bc0f-4f01-4aac-b97b-cdecc57646c6" />
[ "crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7725
Bug: [FEATURE] Add refunds update flow in v2 apis Add refunds update flow in v2 apis
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index c6b6f01fb0a..12c30cc61f0 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3265,6 +3265,64 @@ ] } }, + "/v2/refunds/{id}/update_metadata": { + "put": { + "tags": [ + "Refunds" + ], + "summary": "Refunds - Metadata Update", + "description": "Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields", + "operationId": "Update Refund Metadata and Reason", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The identifier for refund", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RefundMetadataUpdateRequest" + }, + "examples": { + "Update refund reason": { + "value": { + "reason": "Paid by mistake" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Refund updated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RefundResponse" + } + } + } + }, + "400": { + "description": "Missing Mandatory fields" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/v2/refunds/{id}": { "get": { "tags": [ @@ -20629,6 +20687,24 @@ } } }, + "RefundMetadataUpdateRequest": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive", + "example": "Customer returned the product", + "nullable": true, + "maxLength": 255 + }, + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true + } + }, + "additionalProperties": false + }, "RefundResponse": { "type": "object", "required": [ @@ -20737,24 +20813,6 @@ "instant" ] }, - "RefundUpdateRequest": { - "type": "object", - "properties": { - "reason": { - "type": "string", - "description": "An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive", - "example": "Customer returned the product", - "nullable": true, - "maxLength": 255 - }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true - } - }, - "additionalProperties": false - }, "RefundsCreateRequest": { "type": "object", "required": [ diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index bb20978e0d2..e556c7eccce 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -166,6 +166,19 @@ pub struct RefundUpdateRequest { pub metadata: Option<pii::SecretSerdeValue>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct RefundMetadataUpdateRequest { + /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive + #[schema(max_length = 255, example = "Customer returned the product")] + pub reason: Option<String>, + + /// 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. + #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, +} + #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundManualUpdateRequest { diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 95b6c3d7df9..6057797e200 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -148,6 +148,7 @@ Never share your secret api keys. Keep them guarded and secure. //Routes for refunds routes::refunds::refunds_create, + routes::refunds::refunds_metadata_update, routes::refunds::refunds_retrieve, routes::refunds::refunds_list, @@ -193,7 +194,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::refunds::RefundType, api_models::refunds::RefundResponse, api_models::refunds::RefundStatus, - api_models::refunds::RefundUpdateRequest, + api_models::refunds::RefundMetadataUpdateRequest, api_models::organization::OrganizationCreateRequest, api_models::organization::OrganizationUpdateRequest, api_models::organization::OrganizationResponse, diff --git a/crates/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs index 8fb6d4f1835..6628d432203 100644 --- a/crates/openapi/src/routes/refunds.rs +++ b/crates/openapi/src/routes/refunds.rs @@ -112,6 +112,7 @@ pub async fn refunds_retrieve_with_body() {} operation_id = "Update a Refund", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub async fn refunds_update() {} /// Refunds - List @@ -215,6 +216,38 @@ pub async fn refunds_filter_list() {} #[cfg(feature = "v2")] pub async fn refunds_create() {} +/// Refunds - Metadata Update +/// +/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields +#[utoipa::path( + put, + path = "/v2/refunds/{id}/update_metadata", + params( + ("id" = String, Path, description = "The identifier for refund") + ), + request_body( + content = RefundMetadataUpdateRequest, + examples( + ( + "Update refund reason" = ( + value = json!({ + "reason": "Paid by mistake" + }) + ) + ) + ) + ), + responses( + (status = 200, description = "Refund updated", body = RefundResponse), + (status = 400, description = "Missing Mandatory fields") + ), + tag = "Refunds", + operation_id = "Update Refund Metadata and Reason", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn refunds_metadata_update() {} + /// Refunds - Retrieve /// /// Retrieves a Refund. This may be used to get the status of a previously initiated refund diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs index 8d113d5a329..ee10e1b3081 100644 --- a/crates/router/src/core/refunds_v2.rs +++ b/crates/router/src/core/refunds_v2.rs @@ -465,6 +465,42 @@ where request.check_integrity(request, connector_refund_id.to_owned()) } +// ********************************************** REFUND UPDATE ********************************************** + +pub async fn refund_metadata_update_core( + state: SessionState, + merchant_account: domain::MerchantAccount, + req: refunds::RefundMetadataUpdateRequest, + global_refund_id: id_type::GlobalRefundId, +) -> errors::RouterResponse<refunds::RefundResponse> { + let db = state.store.as_ref(); + let refund = db + .find_refund_by_id(&global_refund_id, merchant_account.storage_scheme) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; + + let response = db + .update_refund( + refund, + storage::RefundUpdate::MetadataAndReasonUpdate { + metadata: req.metadata, + reason: req.reason, + updated_by: merchant_account.storage_scheme.to_string(), + }, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Unable to update refund with refund_id: {}", + global_refund_id.get_string_repr() + ) + })?; + + refunds::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json) +} + // ********************************************** REFUND SYNC ********************************************** #[instrument(skip_all)] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index db65dff64b5..9cb83192f6f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1187,7 +1187,11 @@ impl Refunds { { route = route .service(web::resource("").route(web::post().to(refunds::refunds_create))) - .service(web::resource("/{id}").route(web::get().to(refunds::refunds_retrieve))); + .service(web::resource("/{id}").route(web::get().to(refunds::refunds_retrieve))) + .service( + web::resource("/{id}/update_metadata") + .route(web::put().to(refunds::refunds_metadata_update)), + ); } route diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index dc92545841e..1ae4412807c 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -12,6 +12,39 @@ use crate::{ services::{api, authentication as auth, authorization::permissions::Permission}, types::{api::refunds, domain}, }; + +#[cfg(feature = "v2")] +/// A private module to hold internal types to be used in route handlers. +/// This is because we will need to implement certain traits on these types which will have the resource id +/// But the api payload will not contain the resource id +/// So these types can hold the resource id along with actual api payload, on which api event and locking action traits can be implemented +mod internal_payload_types { + use super::*; + + // Serialize is implemented because of api events + #[derive(Debug, serde::Serialize)] + pub struct RefundsGenericRequestWithResourceId<T: serde::Serialize> { + pub global_refund_id: common_utils::id_type::GlobalRefundId, + pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, + #[serde(flatten)] + pub payload: T, + } + + impl<T: serde::Serialize> common_utils::events::ApiEventMetric + for RefundsGenericRequestWithResourceId<T> + { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + let refund_id = self.global_refund_id.clone(); + self.payment_id + .clone() + .map(|payment_id| common_utils::events::ApiEventsType::Refund { + payment_id, + refund_id, + }) + } + } +} + /// Refunds - Create /// /// To create a refund against an already processed payment @@ -323,6 +356,45 @@ pub async fn refunds_update( .await } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))] +pub async fn refunds_metadata_update( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<refunds::RefundMetadataUpdateRequest>, + path: web::Path<common_utils::id_type::GlobalRefundId>, +) -> HttpResponse { + let flow = Flow::RefundsUpdate; + + let global_refund_id = path.into_inner(); + let internal_payload = internal_payload_types::RefundsGenericRequestWithResourceId { + global_refund_id: global_refund_id.clone(), + payment_id: None, + payload: json_payload.into_inner(), + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + internal_payload, + |state, auth: auth::AuthenticationData, req, _| { + refund_metadata_update_core( + state, + auth.merchant_account, + req.payload, + global_refund_id.clone(), + ) + }, + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index 935cb14c1f7..908d8cddaf4 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -1,11 +1,11 @@ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] pub use api_models::refunds::RefundRequest; -#[cfg(all(feature = "v2", feature = "refunds_v2"))] -pub use api_models::refunds::RefundsCreateRequest; pub use api_models::refunds::{ RefundListRequest, RefundListResponse, RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveBody, RefundsRetrieveRequest, }; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +pub use api_models::refunds::{RefundMetadataUpdateRequest, RefundsCreateRequest}; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync};
2025-04-04T13:18:14Z
## Description <!-- Describe your changes in detail --> This PR contains refunds update flow for v2 apis. It is a part of v2 implementation of refunds. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Merging this pr will add refunds update flow to the hyperswitch v2 apis, merchants can update refunds with v2 apis. #
c6c57c1c52ad3ec08e8d443e49227950e390965e
- Create Refund API Call ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_AL59Mhfn1eDbm5FtUXao' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_t3GJeRLga4fvpMYfeA26gnjD5jwPWUFA9gbGdUfRwujMbWd54GDi5YjhcbmL5WiQ' \ --data '{ "payment_id":"12345_pay_01966ca5ba0f781394e31ca377c045c1", "merchant_reference_id":"1745579609", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ``` { "id": "12345_ref_01966ca5cdd87781af1426c620531fb5", "payment_id": "12345_pay_01966ca5ba0f781394e31ca377c045c1", "merchant_reference_id": "1745579528", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-25T11:12:07.651Z", "updated_at": "2025-04-25T11:12:08.717Z", "connector": "stripe", "profile_id": "pro_AL59Mhfn1eDbm5FtUXao", "merchant_connector_id": "mca_rAbIwlE7su9DkFILFzSO", "connector_refund_reference_id": null } ``` - Update Refund API Call ``` curl --location --request PUT 'http://localhost:8080/v2/refunds/12345_ref_01966ca5cdd87781af1426c620531fb5/update_metadata' \ --header 'x-profile-id: pro_AL59Mhfn1eDbm5FtUXao' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_t3GJeRLga4fvpMYfeA26gnjD5jwPWUFA9gbGdUfRwujMbWd54GDi5YjhcbmL5WiQ' \ --data '{ "reason":"Customer asked for refund", "metadata": { "customer": "Mr bean from IIT Dholakpur" } }' ``` - Response from the above call ``` { "id": "12345_ref_01966ca5cdd87781af1426c620531fb5", "payment_id": "12345_pay_01966ca5ba0f781394e31ca377c045c1", "merchant_reference_id": "1745579528", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Customer asked for refund", "metadata": { "customer": "Mr bean from IIT Dholakpur" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-25T11:12:07.651Z", "updated_at": "2025-04-25T11:12:10.581Z", "connector": "stripe", "profile_id": "pro_AL59Mhfn1eDbm5FtUXao", "merchant_connector_id": "mca_rAbIwlE7su9DkFILFzSO", "connector_refund_reference_id": null } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/refunds.rs", "crates/openapi/src/openapi_v2.rs", "crates/openapi/src/routes/refunds.rs", "crates/router/src/core/refunds_v2.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/refunds.rs", "crates/router/src/types/api/refunds.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7676
Bug: [BUG] Novalnet connector integration ### Bug Description Novalnet's connector response for refunds expects below format ``` pub struct NovalnetRefundResponse { pub customer: Option<NovalnetResponseCustomer>, pub merchant: Option<NovalnetResponseMerchant>, pub result: ResultData, pub transaction: Option<NovalnetRefundsTransactionData>, } pub struct NovalnetRefundsTransactionData { pub amount: Option<u64>, pub date: Option<String>, pub currency: Option<common_enums::Currency>, pub order_no: Option<String>, pub payment_type: String, pub refund: RefundData, pub refunded_amount: u64, pub status: NovalnetTransactionStatus, pub status_code: u64, pub test_mode: u8, pub tid: Option<Secret<i64>>, } pub struct RefundData { amount: u64, currency: common_enums::Currency, payment_type: String, tid: Option<Secret<i64>>, } ``` Which fails at deserialization for a specific case. ``` { "result": { "status": "FAILURE", "status_code": 300079, "status_text": "Refund limit exceeded. Please contact our support department at [email protected]" }, "transaction": { "amount": 123, "currency": "EUR", "order_no": "pay_be68heac90b_1", "payment_type": "CREDITCARD", "refund": { "amount": 123, "currency": "EUR" }, "status": "CONFIRMED", "status_code": 100, "test_mode": 0, "tid": 2187482476274382 } } ``` Under `RefundData` object, `payment_type` is made as a required parameter which is missing in the response for certain scenarios leading to keeping the refund in a PENDING state. ### Expected Behavior Deserialization should not fail and mark the refund status as PENDING ### Actual Behavior Deserialization should succeed and mark the refund status to FAILURE in such scenarios. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index e35384659d1..2a8b0911dca 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -902,7 +902,7 @@ pub struct NovalnetRefundsTransactionData { pub order_no: Option<String>, pub payment_type: String, pub refund: RefundData, - pub refunded_amount: u64, + pub refunded_amount: Option<u64>, pub status: NovalnetTransactionStatus, pub status_code: u64, pub test_mode: u8, @@ -913,7 +913,7 @@ pub struct NovalnetRefundsTransactionData { pub struct RefundData { amount: u64, currency: common_enums::Currency, - payment_type: String, + payment_type: Option<String>, tid: Option<Secret<i64>>, }
2025-04-04T11:02:09Z
## Description <!-- Describe your changes in detail --> Need to make unused fields in novalnet refund response as optional. This will prevent the deserialization errors. It's a configuration done on Novalnet side, only available in prod. Cannot test this specific case in sandbox. cc: @kashif-m ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Few fields which are not mandatory in response were made mandatory in the types defined which were causing deserialization when parsing connector refund response. #
bd32dd4f0f259336f004a2358a7771652a3c6689
Curl to test: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LGJYQwEIgppbYvbIuwmQYyHGtMLquJJUujSrP34trbI4k1nnTs1ZyqkG1aI6Nx5N' \ --data '{ "payment_id": "pay_ahzKGIpLrLjWUsalTs0D", "amount": 10000, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ```
[ "crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7710
Bug: [Nexixpay]: handle error_code and error_message in failure responses of nexixpay Nexixpay does not send error_code and error_message in case of failure responses. We will send NO_ERROR_CODE and nexixpay operation result as error_message in this case.
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 68f3b4bb695..32e630a2be7 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -8,7 +8,7 @@ use common_utils::{ use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ refunds::{Execute, RSync}, SetupMandate, @@ -25,9 +25,10 @@ use hyperswitch_domain_models::{ PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, }, }; -use hyperswitch_interfaces::errors; +use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors}; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; +use strum::Display; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, @@ -305,6 +306,23 @@ fn update_nexi_meta_data( })) } +pub fn get_error_response( + operation_result: NexixpayPaymentStatus, + status_code: u16, +) -> ErrorResponse { + ErrorResponse { + status_code, + code: NO_ERROR_CODE.to_string(), + message: operation_result.to_string(), + reason: Some(operation_result.to_string()), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDSAuthData { @@ -425,22 +443,35 @@ impl<F> is_auto_capture, })?); - Ok(Self { - status: AttemptStatus::from(item.response.operation.operation_result), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - item.response.operation.order_id.clone(), - ), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata, - network_txn_id: None, - connector_response_reference_id: Some(item.response.operation.order_id), - incremental_authorization_allowed: None, - charges: None, + let status = AttemptStatus::from(item.response.operation.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + item.response.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.operation.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some(item.response.operation.order_id), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } } } @@ -632,7 +663,7 @@ impl TryFrom<&ConnectorAuthType> for NexixpayAuthType { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Display, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NexixpayPaymentStatus { Authorized, @@ -821,51 +852,80 @@ impl<F> }, psync_flow: NexixpayPaymentIntent::Authorize })); - Ok(Self { - status: AttemptStatus::from(response_body.operation.operation_result.clone()), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - response_body.operation.order_id.clone(), - ), - redirection_data: Box::new(Some(redirection_form.clone())), - mandate_reference: Box::new(Some(MandateReference { - connector_mandate_id: item - .data - .connector_mandate_request_reference_id - .clone(), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - })), - connector_metadata, - network_txn_id: None, - connector_response_reference_id: Some( - response_body.operation.order_id.clone(), - ), - incremental_authorization_allowed: None, - charges: None, + let status = AttemptStatus::from(response_body.operation.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + response_body.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + response_body.operation.order_id.clone(), + ), + redirection_data: Box::new(Some(redirection_form.clone())), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item + .data + .connector_mandate_request_reference_id + .clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some( + response_body.operation.order_id.clone(), + ), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } + } + NexixpayPaymentsResponse::MandateResponse(ref mandate_response) => { + let status = + AttemptStatus::from(mandate_response.operation.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + mandate_response.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + mandate_response.operation.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + mandate_response.operation.order_id.clone(), + ), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }), + } } - NexixpayPaymentsResponse::MandateResponse(ref mandate_response) => Ok(Self { - status: AttemptStatus::from(mandate_response.operation.operation_result.clone()), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - mandate_response.operation.order_id.clone(), - ), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: Some( - mandate_response.operation.order_id.clone(), - ), - incremental_authorization_allowed: None, - charges: None, - }), - ..item.data - }), } } } @@ -975,27 +1035,42 @@ impl<F> } else { AttemptStatus::from(item.response.operation.operation_result.clone()) }; - Ok(Self { - status, - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - item.response.operation.order_id.clone(), - ), - redirection_data: Box::new(None), - mandate_reference: Box::new(Some(MandateReference { - connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - })), - connector_metadata, - network_txn_id: None, - connector_response_reference_id: Some(item.response.operation.order_id), - incremental_authorization_allowed: None, - charges: None, + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + item.response.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.operation.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item + .data + .connector_mandate_request_reference_id + .clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some(item.response.operation.order_id), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } } } @@ -1122,25 +1197,32 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>> .into()) } }; - let contract_id = Secret::new( - item.router_data - .connector_mandate_request_reference_id - .clone() - .ok_or_else(|| errors::ConnectorError::MissingRequiredField { - field_name: "connector_mandate_request_reference_id", - })?, - ); + + let recurrence_request_obj = if item.router_data.request.is_mandate_payment() { + let contract_id = Secret::new( + item.router_data + .connector_mandate_request_reference_id + .clone() + .ok_or_else(|| errors::ConnectorError::MissingRequiredField { + field_name: "connector_mandate_request_reference_id", + })?, + ); + Some(RecurrenceRequest { + action: NexixpayRecurringAction::ContractCreation, + contract_id, + contract_type: ContractType::MitUnscheduled, + }) + } else { + None + }; + Ok(Self { order: order_data, card: card?, operation_id, capture_type, three_d_s_auth_data, - recurrence: Some(RecurrenceRequest { - action: NexixpayRecurringAction::ContractCreation, - contract_id, - contract_type: ContractType::MitUnscheduled, - }), + recurrence: recurrence_request_obj, }) } } @@ -1159,25 +1241,41 @@ impl<F> PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - Ok(Self { - status: AttemptStatus::from(item.response.operation_result), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), - redirection_data: Box::new(None), - mandate_reference: Box::new(Some(MandateReference { - connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - })), - connector_metadata: item.data.request.connector_meta.clone(), - network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), - incremental_authorization_allowed: None, - charges: None, + let status = AttemptStatus::from(item.response.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + item.response.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), + redirection_data: Box::new(None), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item + .data + .connector_mandate_request_reference_id + .clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata: item.data.request.connector_meta.clone(), + network_txn_id: None, + connector_response_reference_id: Some(item.response.order_id.clone()), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } } } @@ -1349,26 +1447,43 @@ impl }, psync_flow: NexixpayPaymentIntent::Authorize })); - Ok(Self { - status: AttemptStatus::from(item.response.operation.operation_result.clone()), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - item.response.operation.order_id.clone(), - ), - redirection_data: Box::new(Some(redirection_form.clone())), - mandate_reference: Box::new(Some(MandateReference { - connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - })), - connector_metadata, - network_txn_id: None, - connector_response_reference_id: Some(item.response.operation.order_id.clone()), - incremental_authorization_allowed: None, - charges: None, + + let status = AttemptStatus::from(item.response.operation.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + item.response.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.operation.order_id.clone(), + ), + redirection_data: Box::new(Some(redirection_form.clone())), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item + .data + .connector_mandate_request_reference_id + .clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some(item.response.operation.order_id.clone()), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } } }
2025-04-03T07:43:12Z
## Description <!-- Describe your changes in detail --> Nexixpay does not send error_code and error_message in case of failure responses. We will store NO_ERROR_CODE and nexixpay operation result as error_message in this case in our DB. This is sent in outgoing webhooks to the merchants. Possible values of error messages: 1. Declined 2. DeniedByRisk 3. ThreedsFailed 4. Failed ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Currently error_code and error_message goes null in case of webhooks to merchants for nexixpay. We need to pass NO_ERROR_CODE and nexixpay operation result as error_message as connector doesn't sends us any message or code. #
bd32dd4f0f259336f004a2358a7771652a3c6689
Curls to test: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nRAnqXGtbt60CdOO7rfovzh4MdEAIiaqnWc78AdQIx4yWnDXIKetpkjGFOvwFPcb' \ --data-raw '{ "amount": 3596, "currency": "EUR", "amount_to_capture": 3596, "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4742158750987704", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "861" } }, "confirm": true, "profile_id": "pro_PBNVTjuDfM7y2MyljTkG", "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "setup_future_usage": "off_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "description": "Its my first payment request", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IT", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IT", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 3545, "account_name": "transaction_processing" } ], "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "online", "accepted_at":"1963-05-03T04:07:52.723Z", "online": { "ip_address":"127.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` Webhook for failed payment via nexixpay: ``` { "merchant_id": "merchant_1743678217", "event_id": "evt_0195fbf468957b539666947e6762e0af", "event_type": "payment_failed", "content": { "type": "payment_details", "object": { "payment_id": "pay_LOrSTDvs2fs1rntR8Bv7", "merchant_id": "merchant_1743678217", "status": "failed", "amount": 3596, "net_amount": 3596, "shipping_cost": null, "amount_capturable": 3596, "amount_received": null, "connector": "nexixpay", "client_secret": "pay_LOrSTDvs2fs1rntR8Bv7_secret_ZAC52wYDhKokuUvZjKws", "created": "2025-04-03T14:00:35.887Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "7704", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "474215", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_r5dkurdxxncdiAxecZp2", "shipping": { "address": { "city": "San Fransico", "country": "IT", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "billing": { "address": { "city": "San Fransico", "country": "IT", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 3545, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "No error code", "error_message": "ThreedsFailed", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "pay_LOrSTDvs2fs1rntR8Bv7_1", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null }, "feature_metadata": null, "reference_id": "pay_LOrSTDvs2fs1rntR8Bv7_1", "payment_link": null, "profile_id": "pro_9rN5ntPWxQFSDMxRHEZ5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bB3eKYzBDOgKte0bcmKl", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-03T14:15:35.887Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_stzSPzwuoRaFMpPpYb9r", "payment_method_status": "inactive", "updated": "2025-04-03T14:00:53.638Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": "6Hj8lx8blnGI3EMXRX", "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } }, "timestamp": "2025-04-03T14:00:53.654Z" } ```
[ "crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-8200
Bug: [FEATURE] Introduce routing in V2 - Implement rule based profile level activation , straight through routing and default fallback in V2 apis.
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index d200d352fa4..ae2710c50e9 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -346,6 +346,7 @@ pub struct PaymentIntentNew { pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 44b75e6e647..5b1201027b7 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1344,6 +1344,8 @@ diesel::table! { created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, + #[max_length = 64] + decision_engine_routing_id -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 8e5de204fba..992bd58784f 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -1892,20 +1892,19 @@ impl super::behaviour::Conversion for Profile { authentication_product_ids: item.authentication_product_ids, three_ds_decision_manager_config: item.three_ds_decision_manager_config, card_testing_guard_config: item.card_testing_guard_config, - card_testing_secret_key: item - .card_testing_secret_key - .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?, + card_testing_secret_key: match item.card_testing_secret_key { + Some(encrypted_value) => crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::DecryptOptional(Some(encrypted_value)), + key_manager_identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_optionaloperation()) + .unwrap_or_default(), + None => None, + }, is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, is_debit_routing_enabled: item.is_debit_routing_enabled, merchant_business_country: item.merchant_business_country, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 0abc626bd19..2240df7241f 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -1,3 +1,6 @@ +#[cfg(feature = "v2")] +use std::str::FromStr; + use api_models::{ mandates, payment_methods::{self}, @@ -1904,6 +1907,7 @@ pub enum PaymentMethodsData { } impl PaymentMethodsData { + #[cfg(feature = "v1")] pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { if let Self::Card(card) = self { card.co_badged_card_data.clone() @@ -1911,6 +1915,10 @@ impl PaymentMethodsData { None } } + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] + pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { + todo!() + } } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -1933,6 +1941,10 @@ fn saved_in_locker_default() -> bool { true } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CardDetailsPaymentMethod { pub last4_digits: Option<String>, @@ -1950,6 +1962,54 @@ pub struct CardDetailsPaymentMethod { pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct CardDetailsPaymentMethod { + pub last4_digits: Option<String>, + pub issuer_country: Option<String>, + pub expiry_month: Option<Secret<String>>, + pub expiry_year: Option<Secret<String>>, + pub nick_name: Option<Secret<String>>, + pub card_holder_name: Option<Secret<String>>, + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_network: Option<api_enums::CardNetwork>, + pub card_type: Option<String>, + #[serde(default = "saved_in_locker_default")] + pub saved_to_locker: bool, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl CardDetailsPaymentMethod { + pub fn to_card_details_from_locker(self) -> payment_methods::CardDetailFromLocker { + payment_methods::CardDetailFromLocker { + card_number: None, + card_holder_name: self.card_holder_name.clone(), + card_issuer: self.card_issuer.clone(), + card_network: self.card_network.clone(), + card_type: self.card_type.clone(), + issuer_country: self.clone().get_issuer_country_alpha2(), + last4_digits: self.last4_digits, + expiry_month: self.expiry_month, + expiry_year: self.expiry_year, + card_fingerprint: None, + nick_name: self.nick_name, + card_isin: self.card_isin, + saved_to_locker: self.saved_to_locker, + } + } + + pub fn get_issuer_country_alpha2(self) -> Option<common_enums::CountryAlpha2> { + self.issuer_country + .as_ref() + .map(|c| api_enums::CountryAlpha2::from_str(c)) + .transpose() + .ok() + .flatten() + } +} + +#[cfg(feature = "v1")] impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { fn from(item: payment_methods::CardDetail) -> Self { Self { @@ -1969,6 +2029,25 @@ impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { + fn from(item: payment_methods::CardDetail) -> Self { + Self { + issuer_country: item.card_issuing_country.map(|c| c.to_string()), + last4_digits: Some(item.card_number.get_last4()), + expiry_month: Some(item.card_exp_month), + expiry_year: Some(item.card_exp_year), + card_holder_name: item.card_holder_name, + nick_name: item.nick_name, + card_isin: None, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type.map(|card| card.to_string()), + saved_to_locker: true, + } + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod { fn from(item: NetworkTokenDetails) -> Self { diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 8df0ff705e7..c08a8130266 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1936,6 +1936,7 @@ impl behaviour::Conversion for PaymentIntent { processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|cb| cb.to_string()), is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, + routing_algorithm_id: self.routing_algorithm_id, }) } } diff --git a/crates/hyperswitch_domain_models/src/routing.rs b/crates/hyperswitch_domain_models/src/routing.rs index 4a802250630..baa2d45ab4e 100644 --- a/crates/hyperswitch_domain_models/src/routing.rs +++ b/crates/hyperswitch_domain_models/src/routing.rs @@ -1,18 +1,32 @@ use std::collections::HashMap; use api_models::{enums as api_enums, routing}; +use common_utils::id_type; use serde; +#[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingData { pub routed_through: Option<String>, - pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: PaymentRoutingInfo, pub algorithm: Option<routing::StraightThroughAlgorithm>, } +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RoutingData { + // TODO: change this to RoutableConnectors enum + pub routed_through: Option<String>, + pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + + pub pre_routing_connector_choice: Option<PreRoutingConnectorChoice>, + + pub algorithm_requested: Option<id_type::RoutingId>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] #[serde(from = "PaymentRoutingInfoSerde", into = "PaymentRoutingInfoSerde")] pub struct PaymentRoutingInfo { diff --git a/crates/payment_methods/Cargo.toml b/crates/payment_methods/Cargo.toml index 26572c9e32f..73f3fe8ef96 100644 --- a/crates/payment_methods/Cargo.toml +++ b/crates/payment_methods/Cargo.toml @@ -35,7 +35,7 @@ workspace = true [features] customer_v2 = ["api_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] -default = ["dummy_connector", "payouts", "v1"] +default = ["dummy_connector", "payouts"] v1 = ["hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1", "scheduler/v1", "common_types/v1"] v2 = ["customer_v2", "payment_methods_v2", "common_utils/v2", "scheduler/v2", "common_types/v2"] payment_methods_v2 = [ "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 7e13dbbed16..96ac030f57f 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1889,7 +1889,8 @@ pub async fn vault_payment_method_external( let connector_name = merchant_connector_account .get_connector_name() - .unwrap_or_default(); // always get the connector name from this call + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index c545bcac503..911b4ece00e 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1409,7 +1409,8 @@ pub async fn retrieve_payment_method_from_vault_external( let connector_name = merchant_connector_account .get_connector_name() - .unwrap_or_default(); // always get the connector name from this call + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, @@ -1569,7 +1570,8 @@ pub async fn delete_payment_method_data_from_vault_external( let connector_name = merchant_connector_account .get_connector_name() - .unwrap_or_default(); // always get the connector name from this call + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0993a6eee3f..38a53d9b2d1 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -241,7 +241,55 @@ where ) .await? } - ConnectorCallType::Retryable(vec) => todo!(), + ConnectorCallType::Retryable(connectors) => { + let mut connectors = connectors.clone().into_iter(); + let connector_data = get_connector_data(&mut connectors)?; + let router_data = call_connector_service( + state, + req_state.clone(), + &merchant_context, + connector_data.connector_data.clone(), + &operation, + &mut payment_data, + &customer, + call_connector_action.clone(), + None, + header_payload.clone(), + #[cfg(feature = "frm")] + None, + #[cfg(not(feature = "frm"))] + None, + profile, + false, + false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType + req.get_all_keys_required(), + ) + .await?; + + let payments_response_operation = Box::new(PaymentResponse); + + payments_response_operation + .to_post_update_tracker()? + .save_pm_and_mandate( + state, + &router_data, + &merchant_context, + &mut payment_data, + profile, + ) + .await?; + + payments_response_operation + .to_post_update_tracker()? + .update_tracker( + state, + payment_data, + router_data, + merchant_context.get_merchant_key_store(), + merchant_context.get_merchant_account().storage_scheme, + ) + .await? + } ConnectorCallType::SessionMultiple(vec) => todo!(), ConnectorCallType::Skip => payment_data, }; @@ -6574,23 +6622,167 @@ where Ok(decided_connector) } -#[allow(clippy::too_many_arguments)] #[cfg(feature = "v2")] -pub async fn decide_connector<F, D>( - state: SessionState, +#[allow(clippy::too_many_arguments)] +pub async fn connector_selection<F, D>( + state: &SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_data: &mut D, - request_straight_through: Option<api::routing::StraightThroughAlgorithm>, - routing_data: &mut storage::RoutingData, - eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { - todo!() + let mut routing_data = storage::RoutingData { + routed_through: payment_data.get_payment_attempt().connector.clone(), + + merchant_connector_id: payment_data + .get_payment_attempt() + .merchant_connector_id + .clone(), + pre_routing_connector_choice: payment_data.get_pre_routing_result().and_then( + |pre_routing_results| { + pre_routing_results + .get(&payment_data.get_payment_attempt().payment_method_subtype) + .cloned() + }, + ), + + algorithm_requested: payment_data + .get_payment_intent() + .routing_algorithm_id + .clone(), + }; + + let payment_dsl_input = core_routing::PaymentsDslInput::new( + None, + payment_data.get_payment_attempt(), + payment_data.get_payment_intent(), + payment_data.get_payment_method_data(), + payment_data.get_address(), + None, + payment_data.get_currency(), + ); + + let decided_connector = decide_connector( + state.clone(), + merchant_context, + business_profile, + &mut routing_data, + payment_dsl_input, + mandate_type, + ) + .await?; + + payment_data.set_connector_in_payment_attempt(routing_data.routed_through); + + payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id); + + Ok(decided_connector) +} + +#[allow(clippy::too_many_arguments)] +#[cfg(feature = "v2")] +pub async fn decide_connector( + state: SessionState, + merchant_context: &domain::MerchantContext, + business_profile: &domain::Profile, + routing_data: &mut storage::RoutingData, + payment_dsl_input: core_routing::PaymentsDslInput<'_>, + mandate_type: Option<api::MandateTransactionType>, +) -> RouterResult<ConnectorCallType> { + // If the connector was already decided previously, use the same connector + // This is in case of flows like payments_sync, payments_cancel where the successive operations + // with the connector have to be made using the same connector account. + + let predetermined_info_cloned = routing_data + .routed_through + .as_ref() + .zip(routing_data.merchant_connector_id.as_ref()) + .map(|(cn_ref, mci_ref)| (cn_ref.clone(), mci_ref.clone())); + + match ( + predetermined_info_cloned, + routing_data.pre_routing_connector_choice.as_ref(), + ) { + // Condition 1: Connector was already decided previously + (Some((owned_connector_name, owned_merchant_connector_id)), _) => { + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &owned_connector_name, + api::GetToken::Connector, + Some(owned_merchant_connector_id.clone()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received in 'routed_through'") + .map(|connector_data| { + routing_data.routed_through = Some(owned_connector_name); + ConnectorCallType::PreDetermined(connector_data.into()) + }) + } + // Condition 2: Pre-routing connector choice + (None, Some(routable_connector_choice)) => { + let routable_connector_list = match routable_connector_choice { + storage::PreRoutingConnectorChoice::Single(routable_connector) => { + vec![routable_connector.clone()] + } + storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + routable_connector_list.clone() + } + }; + + routable_connector_list + .first() + .ok_or_else(|| { + report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("No first routable connector in pre_routing_connector_choice") + }) + .and_then(|first_routable_connector| { + routing_data.routed_through = Some(first_routable_connector.connector.to_string()); + routing_data + .merchant_connector_id + .clone_from(&first_routable_connector.merchant_connector_id); + + let pre_routing_connector_data_list_result: RouterResult<Vec<api::ConnectorData>> = routable_connector_list + .iter() + .map(|connector_choice| { + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_choice.connector.to_string(), + api::GetToken::Connector, + connector_choice.merchant_connector_id.clone(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received while processing pre_routing_connector_choice") + }) + .collect::<Result<Vec<_>, _>>(); // Collects into RouterResult<Vec<ConnectorData>> + + pre_routing_connector_data_list_result + .and_then(|list| { + list.first() + .cloned() + .ok_or_else(|| { + report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("Empty pre_routing_connector_data_list after mapping") + }) + .map(|first_data| ConnectorCallType::PreDetermined(first_data.into())) + }) + }) + } + (None, None) => { + route_connector_v2_for_payments( + &state, + merchant_context, + business_profile, + payment_dsl_input, + routing_data, + mandate_type, + ) + .await + } + } } #[allow(clippy::too_many_arguments)] @@ -6837,21 +7029,6 @@ where .await } -#[cfg(feature = "v2")] -pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>( - state: &SessionState, - payment_data: &mut D, - routing_data: &mut storage::RoutingData, - connectors: Vec<api::ConnectorData>, - mandate_type: Option<api::MandateTransactionType>, - is_connector_agnostic_mit_enabled: Option<bool>, -) -> RouterResult<ConnectorCallType> -where - D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, -{ - todo!() -} - #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>( @@ -7005,7 +7182,6 @@ where Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into()) } } - _ => { helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?; @@ -7025,22 +7201,6 @@ where } } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[allow(clippy::too_many_arguments)] -pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>( - state: &SessionState, - payment_data: &mut D, - routing_data: &mut storage::RoutingData, - connectors: Vec<api::ConnectorData>, - is_connector_agnostic_mit_enabled: Option<bool>, - payment_method_info: &domain::PaymentMethod, -) -> RouterResult<ConnectorCallType> -where - D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, -{ - todo!() -} - #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") @@ -7400,6 +7560,60 @@ where }) } +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments)] +pub async fn route_connector_v2_for_payments( + state: &SessionState, + merchant_context: &domain::MerchantContext, + business_profile: &domain::Profile, + transaction_data: core_routing::PaymentsDslInput<'_>, + routing_data: &mut storage::RoutingData, + _mandate_type: Option<api::MandateTransactionType>, +) -> RouterResult<ConnectorCallType> { + let routing_algorithm_id = routing_data + .algorithm_requested + .as_ref() + .or(business_profile.routing_algorithm_id.as_ref()); + + let connectors = routing::perform_static_routing_v1( + state, + merchant_context.get_merchant_account().get_id(), + routing_algorithm_id, + business_profile, + &TransactionData::Payment(transaction_data.clone()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + let connectors = routing::perform_eligibility_analysis_with_fallback( + &state.clone(), + merchant_context.get_merchant_key_store(), + connectors, + &TransactionData::Payment(transaction_data), + None, + business_profile, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed eligibility analysis and fallback")?; + + connectors + .first() + .map(|conn| { + routing_data.routed_through = Some(conn.connector.to_string()); + routing_data.merchant_connector_id = conn.merchant_connector_id.clone(); + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &conn.connector.to_string(), + api::GetToken::Connector, + conn.merchant_connector_id.clone(), + ) + }) + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")? + .map(|connector_data| ConnectorCallType::PreDetermined(connector_data.into())) +} + #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn route_connector_v1_for_payments<F, D>( @@ -8259,6 +8473,11 @@ pub trait OperationSessionGetters<F> { #[cfg(feature = "v2")] fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>; + + #[cfg(feature = "v2")] + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>>; } pub trait OperationSessionSetters<F> { @@ -8307,6 +8526,13 @@ pub trait OperationSessionSetters<F> { &mut self, straight_through_algorithm: serde_json::Value, ); + + #[cfg(feature = "v2")] + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ); + fn set_connector_in_payment_attempt(&mut self, connector: Option<String>); #[cfg(feature = "v1")] @@ -8758,10 +8984,22 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { fn get_whole_connector_response(&self) -> Option<String> { todo!(); } + + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + None + } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm); + } // Setters Implementation fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; @@ -9001,10 +9239,26 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_whole_connector_response(&self) -> Option<String> { todo!() } + + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + self.get_payment_intent() + .prerouting_algorithm + .clone() + .and_then(|pre_routing_algorithm| pre_routing_algorithm.pre_routing_results) + } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { + #[cfg(feature = "v2")] + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm); + } // Setters Implementation fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; @@ -9245,10 +9499,23 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { fn get_whole_connector_response(&self) -> Option<String> { todo!() } + + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + None + } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { + #[cfg(feature = "v2")] + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm); + } fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } @@ -9490,10 +9757,22 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { fn get_whole_connector_response(&self) -> Option<String> { todo!(); } + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + None + } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { + #[cfg(feature = "v2")] + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm); + } fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 220a48cd1e1..a166c54139d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3949,6 +3949,7 @@ impl MerchantConnectorAccountType { } } + #[cfg(feature = "v1")] pub fn get_connector_name(&self) -> Option<String> { match self { Self::DbVal(db_val) => Some(db_val.connector_name.to_string()), @@ -3956,6 +3957,14 @@ impl MerchantConnectorAccountType { } } + #[cfg(feature = "v2")] + pub fn get_connector_name(&self) -> Option<api_enums::Connector> { + match self { + Self::DbVal(db_val) => Some(db_val.connector_name), + Self::CacheVal(_) => None, + } + } + pub fn get_additional_merchant_data( &self, ) -> Option<Encryptable<masking::Secret<serde_json::Value>>> { @@ -5289,12 +5298,6 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get merchant default fallback connectors config")?; - #[cfg(feature = "v2")] - let fallback_connetors_list = core_admin::ProfileWrapper::new(business_profile) - .get_default_fallback_list_of_connector_under_profile() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to get merchant default fallback connectors config")?; - let mut routing_connector_data_list = Vec::new(); pre_routing_connector_data_list.iter().for_each(|pre_val| { @@ -6876,6 +6879,34 @@ where Ok(()) } +pub async fn validate_routing_id_with_profile_id( + db: &dyn StorageInterface, + routing_id: &id_type::RoutingId, + profile_id: &id_type::ProfileId, +) -> CustomResult<(), errors::ApiErrorResponse> { + let _routing_id = db + .find_routing_algorithm_metadata_by_algorithm_id_profile_id(routing_id, profile_id) + .await + .map_err(|err| { + if err.current_context().is_db_not_found() { + logger::warn!( + "Routing id not found for routing id - {:?} and profile id - {:?}", + routing_id, + profile_id + ); + err.change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "routing_algorithm_id".to_string(), + expected_format: "A valid routing_id that belongs to the business_profile" + .to_string(), + }) + } else { + err.change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to validate routing id") + } + })?; + Ok(()) +} + #[cfg(feature = "v1")] pub async fn validate_merchant_connector_ids_in_connector_mandate_details( state: &SessionState, diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 2074b28fd00..7084fc14bb8 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -338,34 +338,14 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf // TODO: do not take the whole payment data here payment_data: &mut PaymentConfirmData<F>, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> { - use crate::core::payments::OperationSessionSetters; - - let fallback_config = admin::ProfileWrapper::new(business_profile.clone()) - .get_default_fallback_list_of_connector_under_profile() - .change_context(errors::RoutingError::FallbackConfigFetchFailed) - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - let first_chosen_connector = fallback_config - .first() - .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; - - let connector_name = first_chosen_connector.connector.to_string(); - let merchant_connector_id = first_chosen_connector - .merchant_connector_id - .clone() - .get_required_value("merchant_connector_id")?; - - payment_data.set_connector_in_payment_attempt(Some(connector_name.to_string())); - payment_data.set_merchant_connector_id_in_attempt(Some(merchant_connector_id.clone())); - - let connector_data = api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - &connector_name, - api::GetToken::Connector, - Some(merchant_connector_id), - )?; - - Ok(ConnectorCallType::PreDetermined(connector_data.into())) + payments::connector_selection( + state, + merchant_context, + business_profile, + payment_data, + None, + ) + .await } } diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index c5cb9cdba12..1cb95a2b92e 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -4,7 +4,7 @@ use api_models::{enums::FrmSuggestion, payments::PaymentsCreateIntentRequest}; use async_trait::async_trait; use common_utils::{ errors::CustomResult, - ext_traits::{AsyncExt, Encode, ValueExt}, + ext_traits::Encode, types::{authentication, keymanager::ToEncryptable}, }; use error_stack::ResultExt; @@ -15,10 +15,9 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, - payments::{self, cards::create_encrypted_data, helpers, operations}, + payments::{self, helpers, operations}, }, routes::{app::ReqState, SessionState}, - services, types::{ api, domain::{self, types as domain_types}, @@ -100,6 +99,14 @@ impl<F: Send + Clone + Sync> _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; + if let Some(routing_algorithm_id) = request.routing_algorithm_id.as_ref() { + helpers::validate_routing_id_with_profile_id( + db, + routing_algorithm_id, + profile.get_id(), + ) + .await?; + } let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index c605f9b3421..b791dab22c1 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -136,10 +136,18 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda payment_id: &common_utils::id_type::GlobalPaymentId, request: &PaymentsUpdateIntentRequest, merchant_context: &domain::MerchantContext, - _profile: &domain::Profile, + profile: &domain::Profile, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; + if let Some(routing_algorithm_id) = request.routing_algorithm_id.as_ref() { + helpers::validate_routing_id_with_profile_id( + db, + routing_algorithm_id, + profile.get_id(), + ) + .await?; + } let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index a7d8fecfe87..df36f9f5117 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -703,7 +703,6 @@ pub fn make_new_payment_attempt( todo!() } -#[cfg(feature = "v1")] pub async fn get_merchant_config_for_gsm( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index c3c4050f1d5..712d092fc77 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -2044,7 +2044,8 @@ pub async fn construct_vault_router_data<F>( ) -> RouterResult<VaultRouterDataV2<F>> { let connector_name = merchant_connector_account .get_connector_name() - .unwrap_or_default(); // always get the connector name from the merchant_connector_account + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for external vault")?; // always get the connector name from the merchant_connector_account let connector_auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 2df62a36e17..12930b680ee 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -2764,9 +2764,16 @@ pub async fn payment_confirm_intent( )) .await }, - &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( - global_payment_id, - )), + auth::api_or_client_auth( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), + req.headers(), + ), locking_action, )) .await diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index f41fa33bb2d..1e9a0d17320 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -301,20 +301,24 @@ impl ConnectorData { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn get_external_vault_connector_by_name( _connectors: &Connectors, - name: &str, + connector: &api_enums::Connector, connector_type: GetToken, connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<Self, errors::ApiErrorResponse> { - let connector = Self::convert_connector(name)?; - let external_vault_connector_name = api_enums::VaultConnectors::from_str(name) - .change_context(errors::ConnectorError::InvalidConnectorName) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| { - format!("unable to parse external vault connector name {name}") - })?; + let connector_enum = Self::convert_connector(&connector.to_string())?; + let external_vault_connector_name = + api_enums::VaultConnectors::from_str(&connector.to_string()) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "unable to parse external vault connector name {:?}", + connector + ) + })?; let connector_name = api_enums::Connector::from(external_vault_connector_name); Ok(Self { - connector, + connector: connector_enum, connector_name, get_token: connector_type, merchant_connector_id: connector_id, diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs index 21ddf6079cf..1d1f0be637a 100644 --- a/crates/router/src/types/domain.rs +++ b/crates/router/src/types/domain.rs @@ -56,6 +56,10 @@ pub mod vault { pub use hyperswitch_domain_models::vault::*; } +mod routing { + pub use hyperswitch_domain_models::routing::*; +} + pub mod payments; pub mod types; #[cfg(feature = "olap")] @@ -73,6 +77,7 @@ pub use merchant_key_store::*; pub use network_tokenization::*; pub use payment_method_data::*; pub use payment_methods::*; +pub use routing::*; #[cfg(feature = "olap")] pub use user::*; pub use user_key_store::*; diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index 0e086500cc1..e912b9f9c53 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -129,6 +129,4 @@ ALTER TABLE refund DROP COLUMN IF EXISTS refund_id, DROP COLUMN IF EXISTS merchant_connector_id; --- Run below queries only when V1 is deprecated -ALTER TABLE routing_algorithm - DROP COLUMN IF EXISTS decision_engine_routing_id; +
2025-04-03T06:58:20Z
## Description <!-- Describe your changes in detail --> Implemented rule based routing in payments v2. Straight through routing in v2 will be achieved by first configuring a straight through algorithm using `routing` endpoint and then passing the `routing_algorithm_id` field in payment create intent request. * Added validation for `routing_algorithm_id` in payment_inten_create and payment_intent_update. Three diff types of routing - Straight through - routing id sent in request - routing id activated in profile - Default fallback - in the order the MCA's are created. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
b8e7a868ade62ff21498203d9e14edae094071d9
Please use this log for checking the final list of connectors decided by routing module - `final_selected_connectors_for_routing` - Straight through routing - Create a routing algo entry, with rule and use that routing id in payment intent create create routing algorithm - <img width="1030" alt="Screenshot 2025-05-27 at 2 42 36 PM" src="https://github.com/user-attachments/assets/14786801-f860-4f0c-940c-14e3ff9d9c29" /> request - ``` curl --location 'http://localhost:8080/v2/routing-algorithm' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'X-Profile-Id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'api-key: dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --data '{ "name": "newalgo", "description": "It is my ADVANCED config", "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": [ {"connector": "bluesnap", "merchant_connector_id":"mca_xMJUJRcvk333cIPrJtdZ"} ] }, "rules": [ { "name": "bluesnap", "connectorSelection": { "type": "priority", "data": [ { "connector": "bluesnap", "merchant_connector_id":"mca_xMJUJRcvk333cIPrJtdZ"}, {"connector": "adyen", "merchant_connector_id":"mca_IpsaFXCRJa2TNYWuVkNx"}, { "connector": "stripe", "merchant_connector_id":"mca_DfyZDqHCZErTASCW170f" } ] }, "statements": [ { "condition": [ { "lhs": "amount", "comparison": "greater_than", "value": { "type": "number", "value": 100077 }, "metadata": {} } ], "nested": null } ] } ], "metadata": {} } }, "profile_id":"pro_kQqIhnCrULOPt4tmuP5v" }' ``` Response - ``` { "id": "routing_bFY4UYfNYLR0pQozeoPX", "profile_id": "pro_kQqIhnCrULOPt4tmuP5v", "name": "newalgo", "kind": "advanced", "description": "It is my ADVANCED config", "created_at": 1748843132, "modified_at": 1748843132, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` Payment intent create - ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'api-key: dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" }, "routing_algorithm_id":"routing_bFY4UYfNYLR0pQozeoPX" }' ``` Confirm intent - ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01972f2d4b007c119e0373142eac05d3/confirm-intent' \ --header 'x-client-secret: cs_01972f2d4b1a7fa091ec990921d3bea7' \ --header 'x-profile-id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_47a62e65c5124ddab58d82c3bb4d0072' \ --data-raw '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" }, "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" } }' ``` final list of connectors decided by routing module <img width="1361" alt="Screenshot 2025-06-02 at 11 17 12 AM" src="https://github.com/user-attachments/assets/53b8c78d-ebe6-496f-ba6f-65be7bdccfd0" /> payment happened with Bluesnap **Rule based routing activation at profile level -** Creating new routing algo , with adyen as priority. <img width="986" alt="Screenshot 2025-06-02 at 11 20 29 AM" src="https://github.com/user-attachments/assets/93361a49-b17f-46c1-9bc0-158ed63a0fb8" /> Activate the routing algorithm id req - ``` curl --location --request PATCH 'http://localhost:8080/v2/profiles/pro_kQqIhnCrULOPt4tmuP5v/activate-routing-algorithm' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'X-Profile-Id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'api-key: dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --data '{ "routing_algorithm_id": "routing_VdGQBkci7Wt5eoFRMJ6L" }' ``` response - ``` { "id": "routing_VdGQBkci7Wt5eoFRMJ6L", "profile_id": "pro_kQqIhnCrULOPt4tmuP5v", "name": "newalgo", "kind": "advanced", "description": "It is my ADVANCED config", "created_at": 1748843407, "modified_at": 1748843407, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` verify from profile entry, the routing algo id will be populated <img width="1540" alt="Screenshot 2025-06-02 at 11 22 11 AM" src="https://github.com/user-attachments/assets/21ec88db-6b48-45c1-b062-93b93be5d2f2" /> Create intent without passing routing id at all in the request <img width="1103" alt="Screenshot 2025-06-02 at 11 23 47 AM" src="https://github.com/user-attachments/assets/80d7bdf2-623b-4e29-b4c1-c57981f1e6d2" /> Final list of connectors - <img width="1558" alt="Screenshot 2025-06-02 at 11 24 27 AM" src="https://github.com/user-attachments/assets/f259e9e5-b40d-4c02-b78f-8798329d31fa" /> Confirm intent <img width="1182" alt="Screenshot 2025-06-02 at 11 24 10 AM" src="https://github.com/user-attachments/assets/577bbf47-ae94-4d7e-88ac-60aad4fb764b" /> **Default Fallback -** Verify in profile <img width="1728" alt="Screenshot 2025-06-02 at 11 10 08 AM" src="https://github.com/user-attachments/assets/3d154892-c583-4c55-ae82-c3048c7debcc" /> <img width="1411" alt="Screenshot 2025-06-02 at 11 11 19 AM" src="https://github.com/user-attachments/assets/c4405bfb-f066-45dd-af07-6ab88f786492" /> Payment Intent create - ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'api-key: dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` use the client secret to confirm the intent Confirm request - ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01972f2414617513a2b2387237f61eb9/confirm-intent' \ --header 'x-client-secret: cs_01972f2414cb7720be7f596e088f9bfd' \ --header 'x-profile-id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_47a62e65c5124ddab58d82c3bb4d0072' \ --data-raw '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" }, "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" } }' ``` Confirm Intent Response - here the payment went through stripe - ``` { "id": "12345_pay_01972f2414617513a2b2387237f61eb9", "status": "failed", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "stripe", "created": "2025-06-02T05:36:23.178Z", "payment_method_data": { "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": null, "connector_reference_id": null, "merchant_connector_id": "mca_DfyZDqHCZErTASCW170f", "browser_info": null, "error": { "code": "No error code", "message": "No error message", "unified_code": null, "unified_message": null, "network_advice_code": null, "network_decline_code": null, "network_error_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null } ```
[ "crates/diesel_models/src/payment_intent.rs", "crates/diesel_models/src/schema_v2.rs", "crates/hyperswitch_domain_models/src/business_profile.rs", "crates/hyperswitch_domain_models/src/payment_method_data.rs", "crates/hyperswitch_domain_models/src/payments/payment_intent.rs", "crates/hyperswitch_domain_models/src/routing.rs", "crates/payment_methods/Cargo.toml", "crates/router/src/core/payment_methods.rs", "crates/router/src/core/payment_methods/vault.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_confirm_intent.rs", "crates/router/src/core/payments/operations/payment_create_intent.rs", "crates/router/src/core/payments/operations/payment_update_intent.rs", "crates/router/src/core/payments/retry.rs", "crates/router/src/core/utils.rs", "crates/router/src/routes/payments.rs", "crates/router/src/types/api.rs", "crates/router/src/types/domain.rs", "v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7732
Bug: FEATURE(connector): [Facilitapay] Add support for Pix Bank transfer Documentation: https://sandbox-portal.facilitapay.com/#/docs
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 10682866ab7..c758e0fbb8a 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -6230,6 +6230,18 @@ "description": "CNPJ is a Brazilian company tax identification number", "example": "74469027417312", "nullable": true + }, + "source_bank_account_id": { + "type": "string", + "description": "Source bank account number", + "example": "8b2812f0-d6c8-4073-97bb-9fa964d08bc5", + "nullable": true + }, + "destination_bank_account_id": { + "type": "string", + "description": "Destination bank account number", + "example": "9b95f84e-de61-460b-a14b-f23b4e71c97b", + "nullable": true } } } @@ -7776,6 +7788,7 @@ "dlocal", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", @@ -10443,6 +10456,18 @@ "user_bank_account_number" ] }, + { + "type": "string", + "enum": [ + "user_source_bank_account_id" + ] + }, + { + "type": "string", + "enum": [ + "user_destination_bank_account_id" + ] + }, { "type": "string", "enum": [ @@ -19428,6 +19453,18 @@ "description": "Partially masked CNPJ - CNPJ is a Brazilian company tax identification number", "example": "**** 417312", "nullable": true + }, + "source_bank_account_id": { + "type": "string", + "description": "Partially masked source bank account number", + "example": "********-****-4073-****-9fa964d08bc5", + "nullable": true + }, + "destination_bank_account_id": { + "type": "string", + "description": "Partially masked destination bank account number", + "example": "********-****-460b-****-f23b4e71c97b", + "nullable": true } } }, @@ -21082,6 +21119,7 @@ "dlocal", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", diff --git a/config/config.example.toml b/config/config.example.toml index 15b9dd2fc4d..63c7c89b039 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -331,7 +331,7 @@ cards = [ "datatrans", "deutschebank", "digitalvirgo", - "facilitapay", + "facilitapay", "globalpay", "globepay", "gocardless", @@ -647,6 +647,9 @@ credit = { country = "FR", currency = "CAD, AUD, EUR, USD" } [pm_filters.digitalvirgo] direct_carrier_billing = {country = "MA, CM, ZA, EG, SN, DZ, TN, ML, GN, GH, LY, GA, CG, MG, BW, SD, NG, ID, SG, AZ, TR, FR, ES, PL, GB, PT, DE, IT, BE, IE, SK, GR, NL, CH, BR, MX, AR, CL, AE, IQ, KW, BH, SA, QA, PS, JO, OM, RU" , currency = "MAD, XOF, XAF, ZAR, EGP, DZD, TND, GNF, GHS, LYD, XAF, CDF, MGA, BWP, SDG, NGN, IDR, SGD, RUB, AZN, TRY, EUR, PLN, GBP, CHF, BRL, MXN, ARS, CLP, AED, IQD, KWD, BHD, SAR, QAR, ILS, JOD, OMR" } +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -745,7 +748,7 @@ credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,B debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,stripe,wise" [bank_config.online_banking_fpx] diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 802af333f8b..0b4c0967e14 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -166,7 +166,7 @@ force_cookies = true enabled = true [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,stripe,wise" [delayed_session_response] @@ -359,6 +359,9 @@ paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,N credit.currency = "USD" debit.currency = "USD" +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 3cc5b8c0f8a..563941cf9d0 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -15,7 +15,7 @@ open_banking_uk.adyen.banks = "aib,bank_of_scotland,danske_bank,first_direct,fir przelewy24.stripe.banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" [connector_customer] -connector_list = "stax,stripe,gocardless" +connector_list = "stax,stripe,gocardless,facilitapay" payout_connector_list = "nomupay,stripe,wise" # Connector configuration, provided attributes will be used to fulfill API requests. @@ -409,6 +409,9 @@ paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,N credit.currency = "USD" debit.currency = "USD" +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index c3555f7ea05..c861ade9aab 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -15,7 +15,7 @@ open_banking_uk.adyen.banks = "aib,bank_of_scotland,danske_bank,first_direct,fir przelewy24.stripe.banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" [connector_customer] -connector_list = "stax,stripe,gocardless" +connector_list = "stax,stripe,gocardless,facilitapay" payout_connector_list = "nomupay,stripe,wise" # Connector configuration, provided attributes will be used to fulfill API requests. @@ -411,6 +411,9 @@ paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,N credit.currency = "USD" debit.currency = "USD" +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } diff --git a/config/development.toml b/config/development.toml index 37c496efbae..f271f70fcac 100644 --- a/config/development.toml +++ b/config/development.toml @@ -574,6 +574,9 @@ paypal = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,B [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" } +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -751,7 +754,7 @@ nexixpay = { payment_method = "card" } redsys = { payment_method = "card" } [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,stripe,wise" [dummy_connector] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 4b0214b8f1b..d8f2d4bd34d 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -575,6 +575,9 @@ apple_pay = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,B google_pay = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} paypal = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -713,7 +716,7 @@ card.debit = { connector_list = "cybersource" } connector_list = "adyen,cybersource,novalnet,stripe,worldpay" [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,stripe,wise" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 212504baaa3..55857ec4412 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -237,6 +237,8 @@ pub enum FieldType { UserBlikCode, UserBank, UserBankAccountNumber, + UserSourceBankAccountId, + UserDestinationBankAccountId, Text, DropDown { options: Vec<String> }, UserDateOfBirth, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 011fd7e4431..1f7b40de7e0 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -19,6 +19,7 @@ use common_utils::{ ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, + new_type::MaskedBankAccount, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; @@ -3413,6 +3414,14 @@ pub enum BankTransferData { /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, + + /// Source bank account number + #[schema(value_type = Option<String>, example = "8b2812f0-d6c8-4073-97bb-9fa964d08bc5")] + source_bank_account_id: Option<MaskedBankAccount>, + + /// Destination bank account number + #[schema(value_type = Option<String>, example = "9b95f84e-de61-460b-a14b-f23b4e71c97b")] + destination_bank_account_id: Option<MaskedBankAccount>, }, Pse {}, LocalBankTransfer { diff --git a/crates/api_models/src/payments/additional_info.rs b/crates/api_models/src/payments/additional_info.rs index 33297e2b342..371bebe5982 100644 --- a/crates/api_models/src/payments/additional_info.rs +++ b/crates/api_models/src/payments/additional_info.rs @@ -167,6 +167,14 @@ pub struct PixBankTransferAdditionalData { /// Partially masked CNPJ - CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "**** 417312")] pub cnpj: Option<MaskedBankAccount>, + + /// Partially masked source bank account number + #[schema(value_type = Option<String>, example = "********-****-4073-****-9fa964d08bc5")] + pub source_bank_account_id: Option<MaskedBankAccount>, + + /// Partially masked destination bank account number + #[schema(value_type = Option<String>, example = "********-****-460b-****-f23b4e71c97b")] + pub destination_bank_account_id: Option<MaskedBankAccount>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 70efd457a97..0b831d63c2d 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -80,7 +80,7 @@ pub enum RoutableConnectors { Dlocal, Ebanx, Elavon, - // Facilitapay, + Facilitapay, Fiserv, Fiservemea, Fiuu, @@ -225,7 +225,7 @@ pub enum Connector { Dlocal, Ebanx, Elavon, - // Facilitapay, + Facilitapay, Fiserv, Fiservemea, Fiuu, @@ -344,6 +344,7 @@ impl Connector { | (Self::Iatapay, _) | (Self::Volt, _) | (Self::Itaubank, _) + | (Self::Facilitapay, _) ) } pub fn supports_file_storage_module(self) -> bool { @@ -387,7 +388,7 @@ impl Connector { | Self::Dlocal | Self::Ebanx | Self::Elavon - // | Self::Facilitapay + | Self::Facilitapay | Self::Fiserv | Self::Fiservemea | Self::Fiuu @@ -537,7 +538,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Dlocal => Self::Dlocal, RoutableConnectors::Ebanx => Self::Ebanx, RoutableConnectors::Elavon => Self::Elavon, - // RoutableConnectors::Facilitapay => Self::Facilitapay, + RoutableConnectors::Facilitapay => Self::Facilitapay, RoutableConnectors::Fiserv => Self::Fiserv, RoutableConnectors::Fiservemea => Self::Fiservemea, RoutableConnectors::Fiuu => Self::Fiuu, @@ -646,7 +647,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Dlocal => Ok(Self::Dlocal), Connector::Ebanx => Ok(Self::Ebanx), Connector::Elavon => Ok(Self::Elavon), - // Connector::Facilitapay => Ok(Self::Facilitapay), + Connector::Facilitapay => Ok(Self::Facilitapay), Connector::Fiserv => Ok(Self::Fiserv), Connector::Fiservemea => Ok(Self::Fiservemea), Connector::Fiuu => Ok(Self::Fiuu), diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 87c64747c69..48aa9eafd8f 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -6607,6 +6607,66 @@ pub enum RomaniaStatesAbbreviation { ValceaCounty, } +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, +)] +pub enum BrazilStatesAbbreviation { + #[strum(serialize = "AC")] + Acre, + #[strum(serialize = "AL")] + Alagoas, + #[strum(serialize = "AP")] + Amapá, + #[strum(serialize = "AM")] + Amazonas, + #[strum(serialize = "BA")] + Bahia, + #[strum(serialize = "CE")] + Ceará, + #[strum(serialize = "DF")] + DistritoFederal, + #[strum(serialize = "ES")] + EspíritoSanto, + #[strum(serialize = "GO")] + Goiás, + #[strum(serialize = "MA")] + Maranhão, + #[strum(serialize = "MT")] + MatoGrosso, + #[strum(serialize = "MS")] + MatoGrossoDoSul, + #[strum(serialize = "MG")] + MinasGerais, + #[strum(serialize = "PA")] + Pará, + #[strum(serialize = "PB")] + Paraíba, + #[strum(serialize = "PR")] + Paraná, + #[strum(serialize = "PE")] + Pernambuco, + #[strum(serialize = "PI")] + Piauí, + #[strum(serialize = "RJ")] + RioDeJaneiro, + #[strum(serialize = "RN")] + RioGrandeDoNorte, + #[strum(serialize = "RS")] + RioGrandeDoSul, + #[strum(serialize = "RO")] + Rondônia, + #[strum(serialize = "RR")] + Roraima, + #[strum(serialize = "SC")] + SantaCatarina, + #[strum(serialize = "SP")] + SãoPaulo, + #[strum(serialize = "SE")] + Sergipe, + #[strum(serialize = "TO")] + Tocantins, +} + #[derive( Clone, Copy, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 782ca4cb711..70bfe9befac 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -196,7 +196,7 @@ pub struct ConnectorConfig { pub dlocal: Option<ConnectorTomlConfig>, pub ebanx_payout: Option<ConnectorTomlConfig>, pub elavon: Option<ConnectorTomlConfig>, - // pub facilitapay: Option<ConnectorTomlConfig>, + pub facilitapay: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, pub fiservemea: Option<ConnectorTomlConfig>, pub fiuu: Option<ConnectorTomlConfig>, @@ -373,7 +373,7 @@ impl ConnectorConfig { Connector::Dlocal => Ok(connector_data.dlocal), Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Elavon => Ok(connector_data.elavon), - // Connector::Facilitapay => Ok(connector_data.facilitapay), + Connector::Facilitapay => Ok(connector_data.facilitapay), Connector::Fiserv => Ok(connector_data.fiserv), Connector::Fiservemea => Ok(connector_data.fiservemea), Connector::Fiuu => Ok(connector_data.fiuu), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 5675ad1d766..9ba3e86cac8 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -5828,3 +5828,10 @@ type="Text" api_key="Merchant ID" key1="Terminal ID" api_secret="Secret Key" + +[facilitapay] +[[facilitapay.bank_transfer]] + payment_method_type = "pix" +[facilitapay.connector_auth.Bodykey] + api_key="Password" + key1="Username" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index efc797a5a1e..da0fd93f70f 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -4353,3 +4353,10 @@ payment_method_type = "UnionPay" api_key = "Merchant ID" key1 = "Terminal ID" api_secret = "Secret Key" + +[facilitapay] +[[facilitapay.bank_transfer]] + payment_method_type = "pix" +[facilitapay.connector_auth.Bodykey] + api_key="Password" + key1="Username" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 4aa34446cbd..a2bdf1863bb 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -5800,3 +5800,10 @@ payment_method_type = "UnionPay" api_key = "Merchant ID" key1 = "Terminal ID" api_secret = "Secret Key" + +[facilitapay] +[[facilitapay.bank_transfer]] + payment_method_type = "pix" +[facilitapay.connector_auth.Bodykey] + api_key="Password" + key1="Username" diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs index 7f0ed1a2f09..9b1a6486df4 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs @@ -1,28 +1,37 @@ +mod requests; +mod responses; pub mod transformers; +use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ - router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, - payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + payments::{ + Authorize, Capture, CreateConnectorCustomer, PSync, PaymentMethodToken, Session, + SetupMandate, Void, + }, refunds::{Execute, RSync}, }, router_request_types::{ - AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, + PaymentsSyncData, RefundsData, SetupMandateRequestData, + }, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -33,27 +42,41 @@ use hyperswitch_interfaces::{ configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, - types::{self, Response}, + types::{self, RefreshTokenType, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; -use transformers as facilitapay; +use lazy_static::lazy_static; +use masking::{Mask, PeekInterface}; +use requests::{ + FacilitapayAuthRequest, FacilitapayCustomerRequest, FacilitapayPaymentsRequest, + FacilitapayRefundRequest, FacilitapayRouterData, +}; +use responses::{ + FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentsResponse, + FacilitapayRefundResponse, +}; +use transformers::parse_facilitapay_error_response; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{ + constants::headers, + types::{RefreshTokenRouterData, ResponseRouterData}, + utils::{self, RefundsRequestData}, +}; #[derive(Clone)] pub struct Facilitapay { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Facilitapay { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &StringMajorUnitForConnector, } } } +impl api::ConnectorCustomer for Facilitapay {} impl api::Payment for Facilitapay {} impl api::PaymentSession for Facilitapay {} impl api::ConnectorAccessToken for Facilitapay {} @@ -82,13 +105,23 @@ where req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + let access_token = req + .access_token + .clone() + .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; + + let headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + ), + ( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", access_token.token.clone().peek()).into_masked(), + ), + ]; + + Ok(headers) } } @@ -99,9 +132,6 @@ impl ConnectorCommon for Facilitapay { fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base - // TODO! Check connector documentation, on which unit they are processing the currency. - // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, - // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { @@ -112,58 +142,201 @@ impl ConnectorCommon for Facilitapay { connectors.facilitapay.base_url.as_ref() } - fn get_auth_header( + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + parse_facilitapay_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> + for Facilitapay +{ + fn get_headers( &self, - auth_type: &ConnectorAuthType, + req: &ConnectorCustomerRouterData, + connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let auth = facilitapay::FacilitapayAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), - )]) + self.build_headers(req, connectors) } - fn build_error_response( + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( &self, - res: Response, + _req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/subject/people", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &ConnectorCustomerRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = FacilitapayCustomerRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::ConnectorCustomerType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::ConnectorCustomerType::get_headers( + self, req, connectors, + )?) + .set_body(types::ConnectorCustomerType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &ConnectorCustomerRouterData, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: facilitapay::FacilitapayErrorResponse = res + res: Response, + ) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError> + where + ConnectorCustomerRouterData: Clone, + { + let response: FacilitapayCustomerResponse = res .response - .parse_struct("FacilitapayErrorResponse") + .parse_struct("FacilitapayCustomerResponse") .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, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, }) } -} -impl ConnectorValidation for Facilitapay { - //TODO: implement functions when support enabled + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } +impl ConnectorValidation for Facilitapay {} + impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Facilitapay { //TODO: implement sessions flow } -impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Facilitapay {} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Facilitapay { + fn get_headers( + &self, + _req: &RefreshTokenRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + Ok(vec![( + headers::CONTENT_TYPE.to_string(), + self.common_get_content_type().to_string().into(), + )]) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefreshTokenRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/sign_in", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &RefreshTokenRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = FacilitapayAuthRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefreshTokenRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .attach_default_headers() + .headers(RefreshTokenType::get_headers(self, req, connectors)?) + .url(&RefreshTokenType::get_url(self, req, connectors)?) + .set_body(RefreshTokenType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> { + let response: FacilitapayAuthResponse = res + .response + .parse_struct("FacilitapayAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + 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<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Facilitapay { + fn build_request( + &self, + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented( + "Setup Mandate flow for Facilitapay".to_string(), + ) + .into()) + } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Facilitapay { @@ -182,9 +355,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}/transactions", self.base_url(connectors))) } fn get_request_body( @@ -198,9 +371,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req.request.currency, )?; - let connector_router_data = facilitapay::FacilitapayRouterData::from((amount, req)); - let connector_req = - facilitapay::FacilitapayPaymentsRequest::try_from(&connector_router_data)?; + let connector_router_data = FacilitapayRouterData::from((amount, req)); + let connector_req = FacilitapayPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } @@ -232,12 +405,14 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: facilitapay::FacilitapayPaymentsResponse = res + let response: FacilitapayPaymentsResponse = res .response - .parse_struct("Facilitapay PaymentsAuthorizeResponse") + .parse_struct("FacilitapayPaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -269,10 +444,19 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fac fn get_url( &self, - _req: &PaymentsSyncRouterData, - _connectors: &Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_transaction_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}/transactions/{}", + self.base_url(connectors), + connector_transaction_id + )) } fn build_request( @@ -296,12 +480,14 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fac event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: facilitapay::FacilitapayPaymentsResponse = res + let response: FacilitapayPaymentsResponse = res .response - .parse_struct("facilitapay PaymentsSyncResponse") + .parse_struct("FacilitapayPaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -373,9 +559,9 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: facilitapay::FacilitapayPaymentsResponse = res + let response: FacilitapayPaymentsResponse = res .response - .parse_struct("Facilitapay PaymentsCaptureResponse") + .parse_struct("FacilitapayPaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -412,10 +598,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilit fn get_url( &self, - _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!( + "{}/transactions/{}/refund_received_transaction", + self.base_url(connectors), + req.request.connector_transaction_id + )) } fn get_request_body( @@ -429,9 +619,8 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilit req.request.currency, )?; - let connector_router_data = facilitapay::FacilitapayRouterData::from((refund_amount, req)); - let connector_req = - facilitapay::FacilitapayRefundRequest::try_from(&connector_router_data)?; + let connector_router_data = FacilitapayRouterData::from((refund_amount, req)); + let connector_req = FacilitapayRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -460,9 +649,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilit event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: facilitapay::RefundResponse = res + let response: FacilitapayRefundResponse = res .response - .parse_struct("facilitapay RefundResponse") + .parse_struct("FacilitapayRefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -497,10 +686,16 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitap fn get_url( &self, - _req: &RefundSyncRouterData, - _connectors: &Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let refund_id = req.request.get_connector_refund_id()?; + Ok(format!( + "{}/transactions/{}/refund_received_transaction/{}", + self.base_url(connectors), + req.request.connector_transaction_id, + refund_id + )) } fn build_request( @@ -514,9 +709,6 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitap .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(), )) } @@ -527,9 +719,9 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitap event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: facilitapay::RefundResponse = res + let response: FacilitapayRefundResponse = res .response - .parse_struct("facilitapay RefundSyncResponse") + .parse_struct("FacilitapayRefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -573,4 +765,48 @@ impl webhooks::IncomingWebhook for Facilitapay { } } -impl ConnectorSpecifications for Facilitapay {} +lazy_static! { + static ref FACILITAPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: + "Facilitapay", + description: + "FacilitaPay, the best and most reliable payment provider for your international business.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + static ref FACILITAPAY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + let facilitapay_supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut facilitapay_supported_payment_methods = SupportedPaymentMethods::new(); + + facilitapay_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::Pix, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: facilitapay_supported_capture_methods.clone(), + specific_features: None, + }, + ); + + facilitapay_supported_payment_methods + }; + static ref FACILITAPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); +} + +impl ConnectorSpecifications for Facilitapay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&*FACILITAPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*FACILITAPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&*FACILITAPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs new file mode 100644 index 00000000000..29c2f34f332 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs @@ -0,0 +1,150 @@ +use common_enums::CountryAlpha2; +use common_utils::{new_type::MaskedBankAccount, pii, types::StringMajorUnit}; +use masking::Secret; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +pub struct FacilitapayRouterData<T> { + pub amount: StringMajorUnit, + pub router_data: T, +} + +#[derive(Debug, Serialize)] +pub struct FacilitapayAuthRequest { + pub user: FacilitapayCredentials, +} + +#[derive(Debug, Serialize)] +pub struct FacilitapayCredentials { + pub username: Secret<String>, // email_id + pub password: Secret<String>, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct FacilitapayCardDetails { + #[serde(rename = "card_number")] + pub number: cards::CardNumber, + #[serde(rename = "card_expiration_date")] + pub expiry_date: Secret<String>, // Format: "MM/YYYY" + #[serde(rename = "card_security_code")] + pub cvc: Secret<String>, + #[serde(rename = "card_brand")] + pub brand: String, + pub fullname: Secret<String>, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct CardTransactionRequest { + pub currency: api_models::enums::Currency, + pub exchange_currency: api_models::enums::Currency, + pub value: StringMajorUnit, + pub from_credit_card: FacilitapayCardDetails, + pub to_bank_account_id: Secret<String>, // UUID + pub subject_id: String, // UUID +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct PixTransactionRequest { + pub subject_id: Secret<String>, // Customer ID (UUID) + pub from_bank_account_id: MaskedBankAccount, // UUID + pub to_bank_account_id: MaskedBankAccount, // UUID + pub currency: api_models::enums::Currency, + pub exchange_currency: api_models::enums::Currency, + pub value: StringMajorUnit, + pub use_dynamic_pix: bool, + #[serde(default, with = "common_utils::custom_serde::iso8601")] + pub dynamic_pix_expires_at: PrimitiveDateTime, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(untagged)] +pub enum FacilitapayTransactionRequest { + #[allow(dead_code)] + Card(CardTransactionRequest), + Pix(PixTransactionRequest), +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct FacilitapayPaymentsRequest { + pub transaction: FacilitapayTransactionRequest, +} + +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct FacilitapayRefundRequest { + pub amount: StringMajorUnit, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapayCustomerRequest { + pub person: FacilitapayPerson, +} + +#[derive(Debug, Serialize, Clone, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum DocumentType { + /// CC is the Cedula de Ciudadania, is a 10-digit number, which is the national identity card for Colombian citizens. + /// It is used for citizen identification purposes. + #[serde(rename = "cc")] + CedulaDeCiudadania, + /// CNPJ stands for Cadastro Nacional da Pessoa Jurídica, is a 14-digit number, + /// which is the national registry of legal entities in Brazil used as a unique identifier for Brazilian companies. + #[serde(rename = "cnpj")] + CadastroNacionaldaPessoaJurídica, + /// CPF stands for Cadastro de Pessoas Físicas, is a 11-digit number, + /// which is the national registry of natural persons in Brazil used as a unique identifier for Brazilian citizens. + #[serde(rename = "cpf")] + CadastrodePessoasFísicas, + /// CURP stands for Clave Única de Registro de Población,is a 18-digit number used as a unique identifier for Mexican citizens. + /// It is used to track tax information and other identification purposes by the government. + #[serde(rename = "curp")] + ClaveÚnicadeRegistrodePoblación, + /// NIT is the Número de Identificación Tributaria, is a 10-digit number, which is the tax identification number in Colombia. Used for companies. + #[serde(rename = "nit")] + NúmerodeIdentificaciónTributaria, + /// Passport is the travel document usually issued by a country's government + Passport, + /// RFC stands for Registro Federal de Contribuyentes, is a 13-digit number used as a unique identifier for Mexican companies. + #[serde(rename = "rfc")] + RegistroFederaldeContribuyentes, + /// RUT stands for Rol Unico Tributario, is a 9-digit number used as a unique identifier for Chilean citizens and companies. + #[serde(rename = "rut")] + RolUnicoTributario, + /// A Taxpayer Identification Number is an identifying number used for tax purposes + TaxId, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapayPerson { + pub document_number: Secret<String>, + pub document_type: DocumentType, + pub social_name: Secret<String>, + pub fiscal_country: CountryAlpha2, + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<pii::Email>, + #[serde(skip_serializing_if = "Option::is_none")] + pub birth_date: Option<time::Date>, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone_country_code: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone_area_code: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone_number: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_city: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_state: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_complement: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_country: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_number: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_postal_code: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_street: Option<Secret<String>>, + pub net_monthly_average_income: Option<StringMajorUnit>, +} diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs new file mode 100644 index 00000000000..dfa01402ce9 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs @@ -0,0 +1,217 @@ +use common_utils::{pii, types::StringMajorUnit}; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use super::requests::DocumentType; + +// Response body for POST /sign_in +#[derive(Debug, Deserialize, Serialize)] +pub struct FacilitapayAuthResponse { + username: Secret<String>, + name: Secret<String>, + pub jwt: Secret<String>, +} + +#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum SubjectKycStatus { + // Customer is able to send/receive money through the platform. No action is needed on your side. + Approved, + + // Customer is required to upload documents or uploaded documents have been rejected by KYC. + Reproved, + + // Customer has uploaded KYC documents but awaiting analysis from the backoffice. No action is needed on your side. + WaitingApproval, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapaySubject { + pub social_name: Secret<String>, + pub document_type: DocumentType, + pub document_number: Secret<String>, + // In documentation, both CountryAlpha2 and String are used. We cannot rely on CountryAlpha2. + pub fiscal_country: String, + pub updated_at: Option<String>, + pub status: SubjectKycStatus, + #[serde(rename = "id")] + pub customer_id: Secret<String>, + pub birth_date: Option<time::Date>, + pub email: Option<pii::Email>, + pub phone_country_code: Option<Secret<String>>, + pub phone_area_code: Option<Secret<String>>, + pub phone_number: Option<Secret<String>>, + pub address_street: Option<Secret<String>>, + pub address_number: Option<Secret<String>>, + pub address_complement: Option<Secret<String>>, + pub address_city: Option<String>, + pub address_state: Option<String>, + pub address_postal_code: Option<Secret<String>>, + pub address_country: Option<String>, + pub address_neighborhood: Option<Secret<String>>, + pub net_monthly_average_income: Option<StringMajorUnit>, + pub clearance_level: Option<i32>, + pub required_clearance_level: Option<i32>, + pub inserted_at: Option<String>, + pub references: Option<Vec<serde_json::Value>>, + pub rfc_pf: Option<Secret<String>>, // 13-digit RFC, specific to Mexico users + pub documents: Option<Vec<serde_json::Value>>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapayCustomerResponse { + pub data: FacilitapaySubject, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PixInfo { + #[serde(rename = "type")] + pub key_type: String, + pub key: Secret<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CreditCardResponseInfo { + pub id: String, + pub status: Option<String>, + pub document_type: String, + pub document_number: Secret<String>, + pub birthdate: Option<String>, + pub phone_country_code: Option<String>, + pub phone_area_code: Option<String>, + pub phone_number: Option<Secret<String>>, + pub inserted_at: Option<String>, +} + +// PaymentsResponse +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +#[derive(strum::Display)] +pub enum FacilitapayPaymentStatus { + /// Transaction has been created but it is waiting for an incoming TED/Wire. + /// This is the first recorded status in production mode. + #[default] + Pending, + /// Incoming TED/Wire has been identified into Facilita´s bank account. + /// When it is a deposit into an internal bank account and there is no + /// conversion involved (BRL to BRL for instance), that is the final state. + Identified, + /// The conversion rate has been closed and therefore the exchanged value + /// is defined - when it is a deposit into an internal bank account, that is the final state. + Exchanged, + /// The exchanged value has been wired to its destination (a real bank account) - that is also a final state. + Wired, + /// When for any reason the transaction cannot be concluded or need to be reversed, it is canceled. + #[serde(rename = "canceled")] + Cancelled, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct FacilitapayPaymentsResponse { + pub data: TransactionData, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct OwnerCompany { + pub social_name: Option<Secret<String>>, + #[serde(rename = "id")] + pub company_id: Option<String>, + pub document_type: DocumentType, + pub document_number: Secret<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BankInfo { + pub swift: Option<Secret<String>>, + pub name: Option<String>, + #[serde(rename = "id")] + pub bank_id: Secret<String>, + pub code: Option<Secret<String>>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BankAccountDetail { + pub routing_number: Option<Secret<String>>, + pub pix_info: Option<PixInfo>, + pub owner_name: Option<Secret<String>>, + pub owner_document_number: Option<Secret<String>>, + pub owner_company: Option<OwnerCompany>, + pub internal: Option<bool>, + pub intermediary_bank_account: Option<Secret<String>>, + pub intermediary_bank_account_id: Option<Secret<String>>, + #[serde(rename = "id")] + pub bank_account_id: Secret<String>, + pub iban: Option<Secret<String>>, + pub flow_type: Option<String>, + pub currency: api_models::enums::Currency, + pub branch_number: Option<Secret<String>>, + pub branch_country: Option<String>, + pub bank: Option<BankInfo>, + pub account_type: Option<String>, + pub account_number: Option<Secret<String>>, + pub aba: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct TransactionData { + #[serde(rename = "id")] + pub transaction_id: String, + pub value: StringMajorUnit, + pub status: FacilitapayPaymentStatus, + pub currency: api_models::enums::Currency, + pub exchange_currency: api_models::enums::Currency, + + // Details about the destination account (Required) + pub to_bank_account: BankAccountDetail, + + // Details about the source - mutually exclusive + pub from_credit_card: Option<CreditCardResponseInfo>, + pub from_bank_account: Option<BankAccountDetail>, // Populated for PIX + + // Subject information (customer) + pub subject_id: String, + pub subject: Option<FacilitapaySubject>, + pub subject_is_receiver: Option<bool>, + + // Source identification (potentially redundant with subject or card/bank info) + pub source_name: Secret<String>, + pub source_document_type: DocumentType, + pub source_document_number: Secret<String>, + + // Timestamps and flags + pub inserted_at: Option<String>, + pub for_exchange: Option<bool>, + pub exchange_under_request: Option<bool>, + pub estimated_value_until_exchange: Option<bool>, + pub cleared: Option<bool>, + + // PIX specific field + pub dynamic_pix_code: Option<String>, // QR code string for PIX + + // Exchange details + pub exchanged_value: Option<StringMajorUnit>, + + // Cancelation details + #[serde(rename = "canceled_reason")] + pub cancelled_reason: Option<String>, + #[serde(rename = "canceled_at")] + pub cancelled_at: Option<String>, + + // Other fields + pub bank_transaction: Option<Secret<serde_json::Value>>, + pub meta: Option<serde_json::Value>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RefundData { + #[serde(rename = "id")] + pub refund_id: String, + pub status: FacilitapayPaymentStatus, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FacilitapayRefundResponse { + pub data: RefundData, +} diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs index 81c2f752d3b..a123b4796cf 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs @@ -1,31 +1,45 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use api_models::payments::QrCodeInformation; +use common_enums::{enums, PaymentMethod}; +use common_utils::{ + errors::CustomResult, + ext_traits::{BytesExt, Encode}, + types::StringMajorUnit, +}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, + payment_method_data::{BankTransferData, PaymentMethodData}, + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + types, +}; +use hyperswitch_interfaces::{ + consts, errors, events::connector_api_logs::ConnectorEvent, types::Response, }; -use hyperswitch_interfaces::errors; -use masking::Secret; -use serde::{Deserialize, Serialize}; +use masking::{ExposeInterface, Secret}; +use time::PrimitiveDateTime; +use url::Url; +use super::{ + requests::{ + DocumentType, FacilitapayAuthRequest, FacilitapayCredentials, FacilitapayCustomerRequest, + FacilitapayPaymentsRequest, FacilitapayPerson, FacilitapayRefundRequest, + FacilitapayRouterData, FacilitapayTransactionRequest, PixTransactionRequest, + }, + responses::{ + FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentStatus, + FacilitapayPaymentsResponse, FacilitapayRefundResponse, + }, +}; use crate::{ - types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData}, + utils::{is_payment_failure, missing_field_err, QrImage, RouterData as OtherRouterData}, }; +type Error = error_stack::Report<errors::ConnectorError>; -//TODO: Fill the struct with respective fields -pub struct FacilitapayRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. - pub router_data: T, -} - -impl<T> From<(StringMinorUnit, T)> for FacilitapayRouterData<T> { - fn from((amount, item): (StringMinorUnit, T)) -> Self { - //Todo : use utils to convert the amount to the type of amount that a connector accepts +impl<T> From<(StringMajorUnit, T)> for FacilitapayRouterData<T> { + fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, @@ -33,196 +47,491 @@ impl<T> From<(StringMinorUnit, T)> for FacilitapayRouterData<T> { } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] -pub struct FacilitapayPaymentsRequest { - amount: StringMinorUnit, - card: FacilitapayCard, -} - -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct FacilitapayCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, -} - -impl TryFrom<&FacilitapayRouterData<&PaymentsAuthorizeRouterData>> for FacilitapayPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<&FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>> + for FacilitapayPaymentsRequest +{ + type Error = Error; fn try_from( - item: &FacilitapayRouterData<&PaymentsAuthorizeRouterData>, + item: &FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = FacilitapayCard { - number: req_card.card_number, - expiry_month: req_card.card_exp_month, - expiry_year: req_card.card_exp_year, - cvc: req_card.card_cvc, - complete: item.router_data.request.is_auto_capture()?, - }; - Ok(Self { - amount: item.amount.clone(), - card, - }) + PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data { + BankTransferData::Pix { + source_bank_account_id, + destination_bank_account_id, + .. + } => { + // Set expiry time to 15 minutes from now + let dynamic_pix_expires_at = { + let now = time::OffsetDateTime::now_utc(); + let expires_at = now + time::Duration::minutes(15); + + PrimitiveDateTime::new(expires_at.date(), expires_at.time()) + }; + + let transaction_data = + FacilitapayTransactionRequest::Pix(PixTransactionRequest { + // subject id must be generated by pre-process step and link with customer id + // might require discussions to be done + subject_id: item.router_data.get_connector_customer_id()?.into(), + from_bank_account_id: source_bank_account_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "source bank account id", + }, + )?, + + to_bank_account_id: destination_bank_account_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "destination bank account id", + }, + )?, + currency: item.router_data.request.currency, + exchange_currency: item.router_data.request.currency, + value: item.amount.clone(), + use_dynamic_pix: true, + // Format: YYYY-MM-DDThh:mm:ssZ + dynamic_pix_expires_at, + }); + + Ok(Self { + transaction: transaction_data, + }) + } + BankTransferData::AchBankTransfer {} + | BankTransferData::SepaBankTransfer {} + | BankTransferData::BacsBankTransfer {} + | BankTransferData::MultibancoBankTransfer {} + | BankTransferData::PermataBankTransfer {} + | BankTransferData::BcaBankTransfer {} + | BankTransferData::BniVaBankTransfer {} + | BankTransferData::BriVaBankTransfer {} + | BankTransferData::CimbVaBankTransfer {} + | BankTransferData::DanamonVaBankTransfer {} + | BankTransferData::MandiriVaBankTransfer {} + | BankTransferData::Pse {} + | BankTransferData::InstantBankTransfer {} + | BankTransferData::LocalBankTransfer { .. } => { + Err(errors::ConnectorError::NotImplemented( + "Selected payment method through Facilitapay".to_string(), + ) + .into()) + } + }, + PaymentMethodData::Card(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + "Selected payment method through Facilitapay".to_string(), + ) + .into()) } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } -//TODO: Fill the struct with respective fields +// Helper to build the request from Hyperswitch Auth Type +impl FacilitapayAuthRequest { + fn from_auth_type(auth: &FacilitapayAuthType) -> Self { + Self { + user: FacilitapayCredentials { + username: auth.username.clone(), + password: auth.password.clone(), + }, + } + } +} + // Auth Struct +#[derive(Debug, Clone)] pub struct FacilitapayAuthType { - pub(super) api_key: Secret<String>, + pub(super) username: Secret<String>, + pub(super) password: Secret<String>, } impl TryFrom<&ConnectorAuthType> for FacilitapayAuthType { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: api_key.to_owned(), + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + username: key1.to_owned(), + password: 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 FacilitapayPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, + +impl TryFrom<&RefreshTokenRouterData> for FacilitapayAuthRequest { + type Error = Error; + fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> { + let auth_type = FacilitapayAuthType::try_from(&item.connector_auth_type)?; + Ok(Self::from_auth_type(&auth_type)) + } } -impl From<FacilitapayPaymentStatus> for common_enums::AttemptStatus { - fn from(item: FacilitapayPaymentStatus) -> Self { - match item { - FacilitapayPaymentStatus::Succeeded => Self::Charged, - FacilitapayPaymentStatus::Failed => Self::Failure, - FacilitapayPaymentStatus::Processing => Self::Authorizing, +fn convert_to_document_type(document_type: &str) -> Result<DocumentType, errors::ConnectorError> { + match document_type.to_lowercase().as_str() { + "cc" => Ok(DocumentType::CedulaDeCiudadania), + "cnpj" => Ok(DocumentType::CadastroNacionaldaPessoaJurídica), + "cpf" => Ok(DocumentType::CadastrodePessoasFísicas), + "curp" => Ok(DocumentType::ClaveÚnicadeRegistrodePoblación), + "nit" => Ok(DocumentType::NúmerodeIdentificaciónTributaria), + "passport" => Ok(DocumentType::Passport), + "rfc" => Ok(DocumentType::RegistroFederaldeContribuyentes), + "rut" => Ok(DocumentType::RolUnicoTributario), + "tax_id" | "taxid" => Ok(DocumentType::TaxId), + _ => Err(errors::ConnectorError::NotSupported { + message: format!("Document type '{document_type}'"), + connector: "Facilitapay", + }), + } +} + +pub fn parse_facilitapay_error_response( + res: Response, + event_builder: Option<&mut ConnectorEvent>, +) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let status_code = res.status_code; + let response_body_bytes = res.response.clone(); + + let (message, raw_error) = + match response_body_bytes.parse_struct::<serde_json::Value>("FacilitapayErrorResponse") { + Ok(json_value) => { + event_builder.map(|i| i.set_response_body(&json_value)); + + let message = extract_message_from_json(&json_value); + ( + message, + serde_json::to_string(&json_value).unwrap_or_default(), + ) + } + Err(_) => match String::from_utf8(response_body_bytes.to_vec()) { + Ok(text) => { + event_builder.map(|i| i.set_response_body(&text)); + (text.clone(), text) + } + Err(_) => ( + "Invalid response format received".to_string(), + format!( + "Unable to parse response as JSON or UTF-8 string. Status code: {}", + status_code + ), + ), + }, + }; + + Ok(ErrorResponse { + status_code, + code: consts::NO_ERROR_CODE.to_string(), + message, + reason: Some(raw_error), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) +} + +// Helper function to extract a readable message from JSON error +fn extract_message_from_json(json: &serde_json::Value) -> String { + if let Some(obj) = json.as_object() { + if let Some(error) = obj.get("error").and_then(|e| e.as_str()) { + return error.to_string(); + } + + if obj.contains_key("errors") { + return "Validation error occurred".to_string(); } + + if !obj.is_empty() { + return obj + .iter() + .next() + .map(|(k, v)| format!("{}: {}", k, v)) + .unwrap_or_else(|| "Unknown error".to_string()); + } + } else if let Some(s) = json.as_str() { + return s.to_string(); } + + "Unknown error format".to_string() } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct FacilitapayPaymentsResponse { - status: FacilitapayPaymentStatus, - id: String, +impl TryFrom<&types::ConnectorCustomerRouterData> for FacilitapayCustomerRequest { + type Error = Error; + fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> { + let email = item.request.email.clone(); + + let social_name = item.get_billing_full_name()?; + + let (document_type, document_number) = match item.request.payment_method_data.clone() { + PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data { + BankTransferData::Pix { cpf, .. } => { + // Extract only digits from the CPF string + let document_number = + cpf.ok_or_else(missing_field_err("cpf"))?.map(|cpf_number| { + cpf_number + .chars() + .filter(|chars| chars.is_ascii_digit()) + .collect::<String>() + }); + + let document_type = convert_to_document_type("cpf")?; + (document_type, document_number) + } + _ => { + return Err(errors::ConnectorError::NotImplemented( + "Selected payment method through Facilitapay".to_string(), + ) + .into()) + } + }, + _ => { + return Err(errors::ConnectorError::NotImplemented( + "Selected payment method through Facilitapay".to_string(), + ) + .into()) + } + }; + + let fiscal_country = item.get_billing_country()?; + + let person = FacilitapayPerson { + document_number, + document_type, + social_name, + fiscal_country, + email, + birth_date: None, + phone_country_code: None, + phone_area_code: None, + phone_number: None, + address_city: None, + address_state: None, + address_complement: None, + address_country: None, + address_number: None, + address_postal_code: None, + address_street: None, + net_monthly_average_income: None, + }; + + Ok(Self { person }) + } } -impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>> +impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = Error; fn try_from( - item: ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - incremental_authorization_allowed: None, - charges: None, + response: Ok(PaymentsResponseData::ConnectorCustomerResponse { + connector_customer_id: item.response.data.customer_id.expose(), }), ..item.data }) } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct FacilitapayRefundRequest { - pub amount: StringMinorUnit, +impl From<FacilitapayPaymentStatus> for common_enums::AttemptStatus { + fn from(item: FacilitapayPaymentStatus) -> Self { + match item { + FacilitapayPaymentStatus::Pending => Self::Pending, + FacilitapayPaymentStatus::Identified + | FacilitapayPaymentStatus::Exchanged + | FacilitapayPaymentStatus::Wired => Self::Charged, + FacilitapayPaymentStatus::Cancelled => Self::Failure, + } + } } -impl<F> TryFrom<&FacilitapayRouterData<&RefundsRouterData<F>>> for FacilitapayRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &FacilitapayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { +impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayAuthResponse, T, AccessToken>> + for RouterData<F, T, AccessToken> +{ + type Error = Error; + fn try_from( + item: ResponseRouterData<F, FacilitapayAuthResponse, T, AccessToken>, + ) -> Result<Self, Self::Error> { Ok(Self { - amount: item.amount.to_owned(), + response: Ok(AccessToken { + token: item.response.jwt, + expires: 86400, // Facilitapay docs say 24 hours validity. 24 * 60 * 60 = 86400 seconds. + }), + ..item.data }) } } -// Type definition for Refund Response +impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = Error; + fn try_from( + item: ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let status = if item.data.payment_method == PaymentMethod::BankTransfer + && item.response.data.status == FacilitapayPaymentStatus::Identified + { + common_enums::AttemptStatus::AuthenticationPending + } else { + common_enums::AttemptStatus::from(item.response.data.status.clone()) + }; -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, + Ok(Self { + status, + response: if is_payment_failure(status) { + Err(ErrorResponse { + code: item.response.data.status.clone().to_string(), + message: item.response.data.status.clone().to_string(), + reason: item.response.data.cancelled_reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(item.response.data.transaction_id), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.data.transaction_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: get_qr_code_data(&item.response)?, + network_txn_id: None, + connector_response_reference_id: Some(item.response.data.transaction_id), + incremental_authorization_allowed: None, + charges: None, + }) + }, + ..item.data + }) + } } -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 +fn get_qr_code_data( + response: &FacilitapayPaymentsResponse, +) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> { + let expiration_time: i64 = if let Some(meta) = &response.data.meta { + if let Some(due_date_str) = meta + .get("dynamic_pix_due_date") + .and_then(|due_date_value| due_date_value.as_str()) + { + let datetime = time::OffsetDateTime::parse( + due_date_str, + &time::format_description::well_known::Rfc3339, + ) + .map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?; + + datetime.unix_timestamp() * 1000 + } else { + // If dynamic_pix_due_date isn't present, use current time + 15 minutes + let now = time::OffsetDateTime::now_utc(); + let expires_at = now + time::Duration::minutes(15); + expires_at.unix_timestamp() * 1000 } + } else { + // If meta is null, use current time + 15 minutes + let now = time::OffsetDateTime::now_utc(); + let expires_at = now + time::Duration::minutes(15); + expires_at.unix_timestamp() * 1000 + }; + + let dynamic_pix_code = response.data.dynamic_pix_code.as_ref().ok_or_else(|| { + errors::ConnectorError::MissingRequiredField { + field_name: "dynamic_pix_code", + } + })?; + + let image_data = QrImage::new_from_data(dynamic_pix_code.clone()) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + + let image_data_url = Url::parse(image_data.data.clone().as_str()) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + + let qr_code_info = QrCodeInformation::QrDataUrl { + image_data_url, + display_to_timestamp: Some(expiration_time), + }; + + Some(qr_code_info.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed) +} + +impl<F> TryFrom<&FacilitapayRouterData<&types::RefundsRouterData<F>>> for FacilitapayRefundRequest { + type Error = Error; + fn try_from( + item: &FacilitapayRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.clone(), + }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +impl From<FacilitapayPaymentStatus> for enums::RefundStatus { + fn from(item: FacilitapayPaymentStatus) -> Self { + match item { + FacilitapayPaymentStatus::Identified + | FacilitapayPaymentStatus::Exchanged + | FacilitapayPaymentStatus::Wired => Self::Success, + FacilitapayPaymentStatus::Cancelled => Self::Failure, + FacilitapayPaymentStatus::Pending => Self::Pending, + } + } } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<Execute, FacilitapayRefundResponse>> + for types::RefundsRouterData<Execute> +{ + type Error = Error; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, FacilitapayRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + connector_refund_id: item.response.data.refund_id.to_string(), + refund_status: enums::RefundStatus::from(item.response.data.status), }), ..item.data }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<RSync, FacilitapayRefundResponse>> + for types::RefundsRouterData<RSync> +{ + type Error = Error; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, FacilitapayRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + connector_refund_id: item.response.data.refund_id.to_string(), + refund_status: enums::RefundStatus::from(item.response.data.status), }), ..item.data }) } } - -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] -pub struct FacilitapayErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, -} diff --git a/crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs index 4f6cc393fc5..0ccf5518aa9 100644 --- a/crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs @@ -65,7 +65,9 @@ impl TryFrom<&ItaubankRouterData<&types::PaymentsAuthorizeRouterData>> for Itaub match item.router_data.request.payment_method_data.clone() { PaymentMethodData::BankTransfer(bank_transfer_data) => { match *bank_transfer_data { - BankTransferData::Pix { pix_key, cpf, cnpj } => { + BankTransferData::Pix { + pix_key, cpf, cnpj, .. + } => { let nome = item.router_data.get_optional_billing_full_name(); // cpf and cnpj are mutually exclusive let devedor = match (cnpj, cpf) { diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 35d95343aba..c15da205985 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -825,7 +825,6 @@ default_imp_for_create_customer!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, - connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 41817d955a6..97ac61d6470 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -2725,6 +2725,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 60cb878d9a3..4f0c2eb8639 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -13,10 +13,10 @@ use common_enums::{ enums::{ AlbaniaStatesAbbreviation, AndorraStatesAbbreviation, AttemptStatus, AustriaStatesAbbreviation, BelarusStatesAbbreviation, BelgiumStatesAbbreviation, - BosniaAndHerzegovinaStatesAbbreviation, BulgariaStatesAbbreviation, - CanadaStatesAbbreviation, CroatiaStatesAbbreviation, CzechRepublicStatesAbbreviation, - DenmarkStatesAbbreviation, FinlandStatesAbbreviation, FranceStatesAbbreviation, - FutureUsage, GermanyStatesAbbreviation, GreeceStatesAbbreviation, + BosniaAndHerzegovinaStatesAbbreviation, BrazilStatesAbbreviation, + BulgariaStatesAbbreviation, CanadaStatesAbbreviation, CroatiaStatesAbbreviation, + CzechRepublicStatesAbbreviation, DenmarkStatesAbbreviation, FinlandStatesAbbreviation, + FranceStatesAbbreviation, FutureUsage, GermanyStatesAbbreviation, GreeceStatesAbbreviation, HungaryStatesAbbreviation, IcelandStatesAbbreviation, IrelandStatesAbbreviation, ItalyStatesAbbreviation, LatviaStatesAbbreviation, LiechtensteinStatesAbbreviation, LithuaniaStatesAbbreviation, LuxembourgStatesAbbreviation, MaltaStatesAbbreviation, @@ -5118,6 +5118,52 @@ impl ForeignTryFrom<String> for UkraineStatesAbbreviation { } } +impl ForeignTryFrom<String> for BrazilStatesAbbreviation { + type Error = error_stack::Report<errors::ConnectorError>; + + fn foreign_try_from(value: String) -> Result<Self, Self::Error> { + let state_abbreviation_check = + StringExt::<Self>::parse_enum(value.clone(), "BrazilStatesAbbreviation"); + + match state_abbreviation_check { + Ok(state_abbreviation) => Ok(state_abbreviation), + Err(_) => match value.as_str() { + "Acre" => Ok(Self::Acre), + "Alagoas" => Ok(Self::Alagoas), + "Amapá" => Ok(Self::Amapá), + "Amazonas" => Ok(Self::Amazonas), + "Bahia" => Ok(Self::Bahia), + "Ceará" => Ok(Self::Ceará), + "Distrito Federal" => Ok(Self::DistritoFederal), + "Espírito Santo" => Ok(Self::EspíritoSanto), + "Goiás" => Ok(Self::Goiás), + "Maranhão" => Ok(Self::Maranhão), + "Mato Grosso" => Ok(Self::MatoGrosso), + "Mato Grosso do Sul" => Ok(Self::MatoGrossoDoSul), + "Minas Gerais" => Ok(Self::MinasGerais), + "Pará" => Ok(Self::Pará), + "Paraíba" => Ok(Self::Paraíba), + "Paraná" => Ok(Self::Paraná), + "Pernambuco" => Ok(Self::Pernambuco), + "Piauí" => Ok(Self::Piauí), + "Rio de Janeiro" => Ok(Self::RioDeJaneiro), + "Rio Grande do Norte" => Ok(Self::RioGrandeDoNorte), + "Rio Grande do Sul" => Ok(Self::RioGrandeDoSul), + "Rondônia" => Ok(Self::Rondônia), + "Roraima" => Ok(Self::Roraima), + "Santa Catarina" => Ok(Self::SantaCatarina), + "São Paulo" => Ok(Self::SãoPaulo), + "Sergipe" => Ok(Self::Sergipe), + "Tocantins" => Ok(Self::Tocantins), + _ => Err(errors::ConnectorError::InvalidDataFormat { + field_name: "address.state", + } + .into()), + }, + } + } +} + pub trait ForeignTryFrom<F>: Sized { type Error; diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index f69b9dc6855..2d386d0f002 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -18,6 +18,7 @@ use common_utils::{ use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::Date; + // We need to derive Serialize and Deserialize because some parts of payment method data are being // stored in the database as serde_json::Value #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] @@ -612,6 +613,10 @@ pub enum BankTransferData { cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number cnpj: Option<Secret<String>>, + /// Source bank account UUID + source_bank_account_id: Option<MaskedBankAccount>, + /// Destination bank account UUID. + destination_bank_account_id: Option<MaskedBankAccount>, }, Pse {}, LocalBankTransfer { @@ -1450,9 +1455,19 @@ impl From<api_models::payments::BankTransferData> for BankTransferData { api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => { Self::MandiriVaBankTransfer {} } - api_models::payments::BankTransferData::Pix { pix_key, cpf, cnpj } => { - Self::Pix { pix_key, cpf, cnpj } - } + api_models::payments::BankTransferData::Pix { + pix_key, + cpf, + cnpj, + source_bank_account_id, + destination_bank_account_id, + } => Self::Pix { + pix_key, + cpf, + cnpj, + source_bank_account_id, + destination_bank_account_id, + }, api_models::payments::BankTransferData::Pse {} => Self::Pse {}, api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => { Self::LocalBankTransfer { bank_code } @@ -1478,11 +1493,19 @@ impl From<BankTransferData> for api_models::payments::additional_info::BankTrans BankTransferData::CimbVaBankTransfer {} => Self::CimbVa {}, BankTransferData::DanamonVaBankTransfer {} => Self::DanamonVa {}, BankTransferData::MandiriVaBankTransfer {} => Self::MandiriVa {}, - BankTransferData::Pix { pix_key, cpf, cnpj } => Self::Pix(Box::new( + BankTransferData::Pix { + pix_key, + cpf, + cnpj, + source_bank_account_id, + destination_bank_account_id, + } => Self::Pix(Box::new( api_models::payments::additional_info::PixBankTransferAdditionalData { pix_key: pix_key.map(MaskedBankAccount::from), cpf: cpf.map(MaskedBankAccount::from), cnpj: cnpj.map(MaskedBankAccount::from), + source_bank_account_id, + destination_bank_account_id, }, )), BankTransferData::Pse {} => Self::Pse {}, diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 2f4fb7a8013..192d45c8fce 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -189,6 +189,8 @@ enum RequiredField { PixKey, PixCnpj, PixCpf, + PixSourceBankAccountId, + PixDestinationBankAccountId, GiftCardNumber, GiftCardCvc, DcbMsisdn, @@ -782,6 +784,27 @@ impl RequiredField { value: None, }, ), + Self::PixSourceBankAccountId => ( + "payment_method_data.bank_transfer.pix.source_bank_account_id".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_transfer.pix.source_bank_account_id" + .to_string(), + display_name: "source_bank_account_id".to_string(), + field_type: FieldType::UserSourceBankAccountId, + value: None, + }, + ), + Self::PixDestinationBankAccountId => ( + "payment_method_data.bank_transfer.pix.destination_bank_account_id".to_string(), + RequiredFieldInfo { + required_field: + "payment_method_data.bank_transfer.pix.destination_bank_account_id" + .to_string(), + display_name: "destination_bank_account_id".to_string(), + field_type: FieldType::UserDestinationBankAccountId, + value: None, + }, + ), Self::GiftCardNumber => ( "payment_method_data.gift_card.number".to_string(), RequiredFieldInfo { @@ -3068,6 +3091,20 @@ fn get_bank_transfer_required_fields() -> HashMap<enums::PaymentMethodType, Conn }, ), (Connector::Adyen, fields(vec![], vec![], vec![])), + ( + Connector::Facilitapay, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::from([ + RequiredField::PixSourceBankAccountId.to_tuple(), + RequiredField::PixDestinationBankAccountId.to_tuple(), + RequiredField::BillingAddressCountries(vec!["BR"]).to_tuple(), + RequiredField::BillingUserFirstName.to_tuple(), + RequiredField::BillingUserLastName.to_tuple(), + ]), + }, + ), ]), ), ( diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index c2f26b1ed9a..b00ed9a4600 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1370,10 +1370,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { elavon::transformers::ElavonAuthType::try_from(self.auth_type)?; Ok(()) } - // api_enums::Connector::Facilitapay => { - // facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; - // Ok(()) - // } + api_enums::Connector::Facilitapay => { + facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Fiserv => { fiserv::transformers::FiservAuthType::try_from(self.auth_type)?; fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b4d3995e994..34a8fba4767 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -40,7 +40,6 @@ use error_stack::{report, ResultExt}; use events::EventInfo; use futures::future::join_all; use helpers::{decrypt_paze_token, ApplePayData}; -use hyperswitch_domain_models::payments::{payment_intent::CustomerData, ClickToPayMetaData}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::{ PaymentCaptureData, PaymentConfirmData, PaymentIntentData, PaymentStatusData, @@ -54,6 +53,10 @@ pub use hyperswitch_domain_models::{ router_data::{PaymentMethodToken, RouterData}, router_request_types::CustomerDetails, }; +use hyperswitch_domain_models::{ + payments::{payment_intent::CustomerData, ClickToPayMetaData}, + router_data::AccessToken, +}; use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "v2")] use operations::ValidateStatusForOperation; @@ -3052,16 +3055,6 @@ where // Validating the blocklist guard and generate the fingerprint blocklist_guard(state, merchant_account, key_store, operation, payment_data).await?; - let updated_customer = call_create_connector_customer_if_required( - state, - customer, - merchant_account, - key_store, - &merchant_connector_account, - payment_data, - ) - .await?; - #[cfg(feature = "v1")] let merchant_recipient_data = if let Some(true) = payment_data .get_payment_intent() @@ -3114,6 +3107,22 @@ where &call_connector_action, ); + let updated_customer = call_create_connector_customer_if_required( + state, + customer, + merchant_account, + key_store, + &merchant_connector_account, + payment_data, + router_data.access_token.as_ref(), + ) + .await?; + + #[cfg(feature = "v1")] + if let Some(connector_customer_id) = payment_data.get_connector_customer_id() { + router_data.connector_customer = Some(connector_customer_id); + } + router_data.payment_method_token = if let Some(decrypted_token) = add_decrypted_payment_method_token(tokenization_action.clone(), payment_data).await? { @@ -4275,6 +4284,7 @@ pub async fn call_create_connector_customer_if_required<F, Req, D>( key_store: &domain::MerchantKeyStore, merchant_connector_account: &helpers::MerchantConnectorAccountType, payment_data: &mut D, + access_token: Option<&AccessToken>, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, @@ -4337,7 +4347,7 @@ where if should_call_connector { // Create customer at connector and update the customer table to store this data - let router_data = payment_data + let mut customer_router_data = payment_data .construct_router_data( state, connector.connector.id(), @@ -4350,7 +4360,9 @@ where ) .await?; - let connector_customer_id = router_data + customer_router_data.access_token = access_token.cloned(); + + let connector_customer_id = customer_router_data .create_connector_customer(state, &connector) .await?; @@ -8056,6 +8068,9 @@ pub trait OperationSessionGetters<F> { fn get_capture_method(&self) -> Option<enums::CaptureMethod>; fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>; + #[cfg(feature = "v1")] + fn get_connector_customer_id(&self) -> Option<String>; + #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>; @@ -8247,6 +8262,11 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> { self.vault_operation.as_ref() } + #[cfg(feature = "v1")] + fn get_connector_customer_id(&self) -> Option<String> { + self.connector_customer_id.clone() + } + // #[cfg(feature = "v2")] // fn get_capture_method(&self) -> Option<enums::CaptureMethod> { // Some(self.payment_intent.capture_method) diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index ad50919ae06..d130e0c5097 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -396,9 +396,9 @@ impl ConnectorData { enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } - // enums::Connector::Facilitapay => { - // Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay))) - // } + enums::Connector::Facilitapay => { + Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new()))) + } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 54abe8f7ce9..f95d80bf0d0 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -247,7 +247,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Elavon => Self::Elavon, - // api_enums::Connector::Facilitapay => Self::Facilitapay, + api_enums::Connector::Facilitapay => Self::Facilitapay, api_enums::Connector::Fiserv => Self::Fiserv, api_enums::Connector::Fiservemea => Self::Fiservemea, api_enums::Connector::Fiuu => Self::Fiuu, diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 0650e5e6a4d..2675c337029 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -47,6 +47,10 @@ key1 = "key1" api_key = "access_key" key1 = "secret_key" +[facilitapay] +api_key = "password" +key1 = "username" # email id + [fiserv] api_key = "MyApiKey" key1 = "MerchantID" diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index fc3a777ee6e..959a7a90dba 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -353,6 +353,9 @@ pix = { country = "BR", currency = "BRL" } red_compra = { country = "CL", currency = "CLP" } red_pagos = { country = "UY", currency = "UYU" } +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.globalpay] credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } @@ -404,7 +407,7 @@ gocardless = { long_lived_token = true, payment_method = "bank_debit" } billwerk = { long_lived_token = false, payment_method = "card" } [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,wise" [dummy_connector] @@ -529,4 +532,4 @@ paybox = { payment_method = "card" } redsys = { payment_method = "card" } [billing_connectors_payment_sync] -billing_connectors_which_require_payment_sync = "stripebilling, recurly" \ No newline at end of file +billing_connectors_which_require_payment_sync = "stripebilling, recurly"
2025-04-02T14:21:10Z
## Description <!-- Describe your changes in detail --> This PR does the following: - Adds Facilitapay Connector configs - Enables Facilitapay Connector in Core - Feature Matrix - Pix Bank Transfer (QRCode flow) - Does not support `Manual` capture - AccessToken flow - Requires Connector Customer to be created prior to make a payment - Adds Cypress test coverage for Facilitapay Pix Bank transfer Also, this PR involves a small core change which is explained [here](https://github.com/juspay/hyperswitch/pull/7704#discussion_r2037127714). Quoted below: > Previously, `updated_customer` was called before constructing the `router_data`. `updated_customer` returns us the `connector_customer` in `payment_data` that then gets updated in the `router_data` while it gets constructed. > > Facilitapay requires us to pass `access_token` to create the `connectorCustomer` but `access_token` is available only in the `router_data`. This creates a cyclical dependency between `updated_customer` and `router_data`. > > To comes overcome this, we need to move `updated_customer` after `router_data`. > > `updated_customer` returns us the `connector_customer` value and it never gets updated in the `router_data` since it is called before calling `updated_customer` which results in `connector_customer_id` to go missing resulting in all payments that rely on `connector_customer_id` to fail. > > Hence, we need to update the `router_data` with `connector_customer` value that we get from `payment_data` returned by the `updated_customer` and the above lines does the same. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> New connector integration. Closes #7732 #
776bde00efce8be35e0c63c1bdc6215921babddf
<details> <summary>Authorize call</summary> ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data-raw '{ "amount": 10400, "currency": "BRL", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10400, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_HqjCP9OWtYlxg0KYwPMU", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_payment_method", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_HqjCP9OWtYlxg0KYwPMU_secret_VZlpnxNdhvw9MExKApxo", "created": "2025-04-11T11:27:27.560Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T11:42:27.560Z", "fingerprint": null, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T11:27:27.583Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>Confirm call</summary> ```curl curl --location 'http://localhost:8080/payments/pay_HqjCP9OWtYlxg0KYwPMU/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_e765522f7c7543b9844fbcb1ab283a71' \ --data '{ "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": { "cpf": "866.656.235-80", "source_bank_account_id": "739d6b0a-e92a-40fd-9f58-6d4cdeb699bb", "destination_bank_account_id": "91f5cac1-9058-44b7-80e1-80c6f4a6f0bc", "pix_qr_expiry": "2025-04-11T19:53:54.807Z" } } }, "client_secret": "pay_HqjCP9OWtYlxg0KYwPMU_secret_VZlpnxNdhvw9MExKApxo" }' ``` ```json { "payment_id": "pay_HqjCP9OWtYlxg0KYwPMU", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_customer_action", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "facilitapay", "client_secret": "pay_HqjCP9OWtYlxg0KYwPMU_secret_VZlpnxNdhvw9MExKApxo", "created": "2025-04-11T11:27:27.560Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "pix": { "pix_key": null, "cpf": "866.***.**5-80", "cnpj": null, "source_bank_account_id": "739d****-****-****-****-********99bb", "destination_bank_account_id": "91f5****-****-****-****-********f0bc" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAegAAAHoCAAAAACnOyPQAAAUIklEQVR4Ae3gAZAkSZIkSRKLqpm7R0REZmZmVlVVVVV3d3d3d/fMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMdHd3d3dXV1VVVVVmZkZGRIS7m5kKz0xmV3d1d3dPz8zMzMxMYjVX/T9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxb2NeNOIK85zEFeY5iRfOXCGuMFeI5888J3GFeU7ihTNXiOdknpO4wjx/4t/GvFBUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6DyIjIvGvH8iedkrjBXiCvMFeYK8ZzMFeI5medknpO5QlxhnpN4/sQV5gpxhblCXCGek7lCPH/iCvP8mReNeJFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv5J4/szzJ56TuUI8J/OvY56TeP7MFeL5Ey+cuUI8f+b5E1eY50+8aMTzZ/5VqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5b+IeU7mCnGFeE7mOZnnT7xw4grz/JkrxBXmhTNXiH8d8ZzMFeIK85+KylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdU/ocx/zbmCnGFuUJcIV44c4W4wjx/4vkzV4h/HfNfgspV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP6VzL+NuMJcIZ6TuUJcYV44cYW5QlxhrhDPyTx/4vkTz8k8f+IK8fyJK8wV4l/H/IegctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5H49zFXiCvMFeJfR1xhrhBXmCvEFeYK8ZzEFeaFM1eI5ySuMM/JXCGuMFeIF05cYZ6T+A9F5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLzH8tcIa4wV4jnzzwn85zMFeI5iefPPH/iOYl/HXGFuUK8cOIK85zMfwoqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/HyDzwokrzBXiRWOek3jhzBXi+TNXiBfOXCH+dcxzEs+feU7iCnOFuMJcIa4wz0k8J3OFeNGYfxUqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5F5gXjXnhzBXihTNXiH8b8fyZK8QLJ64wL5x44cQV5jmJ52SuEFeYK8RzMs9JXGFeJFSu+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/QOaFE1eYF048f+YKcYV5/sQV5vkTz8k8J/GczHMSz8lcIZ6Tef7EFeY5iedkrhDPyVwhrjAvnHhO5jmJK8yLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP4F5jmJK8xzMs9JXCGuMFeIK8wV4grznMTzZ64Qz8k8f+IK85zEFeb5E1eYK8wV4grznMwV4gpzhXjRiCvMFeb5E/8mVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8Qz8lcIa4wV4jnZK4Qz594/sS/j7jCXGGuEM/JXCGuMFeIK8xzEleY509cYa4QL5x4TuYKcYW5QvyHoHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BMi+ceOHMi0ZcYa4QV5grxHMyV4jnZJ6TeE7mCnGFeU7i+TNXiCvMFeL5M8+fuMJcIa4wL5x4/sxzEleYK8QV5oWictX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVf4G5QlxhrhDPSTwnc4V4TuIK85zMFeI5medPPCfznMxzEleYK8QV5vkTV5jnJJ6TuMI8f+YKcYW5Qjwnc4V4/sQV5gpxhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v8AmRdOPH/mCvGczBXiCvP8iedkrhAvGnOFeE7mOYkrzBXiCvNvI54/8/yJK8y/jbjCPCdxhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/AXCGuMM/JPCfxnMQLZ64QV5jnT1xhrhBXmCvE82euEM+fuMJcIV405vkTz8k8J/H8mReN+DehctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wEyL5y4wjwncYV5/sQLZ144cYV5TuI5mSvEFeaFE1eY5088J3OFuMJcIZ6TuUJcYa4QV5jnTzwnc4V44cy/CpWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqLyIxPMnnj/znMRzEleYF424wjwn8fyJ589cIa4wz5+5QlxhnpN5TuIK85zMFeIK85zMFeIKcYW5QlxhrhDPSVxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/HyDzwokrzBXiOZkXTjx/5jmJK8wV4jmZ5ySuMC+ceNGY5ySuMFeIK8wV4grz/InnZJ6TuMJcIZ4/88KJK8wLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv8C88KJ589cYV44cYW5Qlxhnj/x/IkrzPNnrhAvnLjCXCGuMM/JXCGuMM/JvGjEFeZfR/yrULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v8AmRdOPCfz/IkrzBXiCvP8iRfOXCGeP/PCiSvMFeIK86IRz5+5Qjx/5grxnMwV4jmZK8QV5oUTz595oahc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/gMyLRjx/5jmJK8xzEi8ac4W4wjwncYW5QlxhnpN4TuYK8ZzM8yeuMC+cuMI8J3GFuUI8J/P8iSvMFeI5mSvEFeZFQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8i86IxV4grzBXmOYnnZP5tzBXiCnOFuUI8J/OvI64wL5y4wrxw5vkTV5grxBXmCvHvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8icYW5QrxoxBXm+TNXiP9Y4jmJF848J3OFeE7iCnOFuUJcIZ6TuMJcIV448ZzE82euEFeYF4rKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8cOIKc4V4/szzJ54/85zEczJXiOfPvGjEFeb5E8/JPH/i+TPPSVxhnpN44czzJ64wz5+4wrxQVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8wV4grzBXi+RNXmOdkXjjz/JkrxBXmOYkrzItGXGGek7lCPCdzhblCPH/i+RNXmOcknj9xhXlO4vkzLxIqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5F4jnz1whnpP59xFXmOdknpO4wlwhnpN5/szzJ1405grx/JnnZK4Qz8lcIZ6Tef7MvwuVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D5D51xH/Nub5E8/JvHDiP4d54cRzMleIF85cIa4wV4h/HXOFeE7mRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AnGFucJcIZ4/88KJF424wjx/5grx/JkrxHMyV4grzL+OuUJcYZ6TeP7MFeIK85zEFeb5E1eYK8S/CpWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqPw7meck/m3MFeI5iRfOXCFeOPOczHMSz8k8f+IK85zECyeuMM9JXGGek7jCPCfxb0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/SuIK8/yZ5ySek3nhzAsnXjTiCnOFuMJcIZ6TuUI8J/GczHMSz8k8J/GcxL+OuML8u1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMqLSFxhnpO4wlwhnpN5TuIKc4W4wjx/4oUTz5+5Qlxh/nOY5ySeP/PCiSvMczJXiOdk/lWoXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMfwxxhXlO4grznMQV5jmJK8wLJ54/8/yJK8wLJ64wz0lcYZ6TuMJcIa4wz5+4wlwhnpN5TuIK8/yJK8wLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv9G4gpzhblCvHDiOYkrzPMnrjBXiCvMFeIKc4W4wlwhrjBXiOdkXjTmCnGFucJcIZ6TuMJcIZ4/85zEFeYK8/yJK8yLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP4F4jmZK8xzEleY5ySek3nRiCvMFeIK88KZK8QV5jmZK8TzZ56TeE7mCnGFeU7m+TPPSVxhnpN54cS/CZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PkPnXEVeY509cYZ6TeE7mCnGFuUI8J/OcxHMyV4grzItGPCdzhbjCvGjEFeYK8ZzMcxJXmOckrjDPn7jCXCGuMC8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+ReI52SuEFeYK8QV5vkzV4jnZK4QV5jnJJ4/c4W4wlwhrjBXiOfPXCGek7lCPH/mCvHCmRdOXGGek3j+zL8Llav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/CuJK8wV4gpzhbjCXCGuMP825gpxhblCXGGeP/GczItGPCdzhXhO5vkzV4jnzzwn8aIRV5h/EypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fIPOiES8ac4X4j2GuEFeY50+8aMwV4gpzhXj+zPMnrjDPn3hO5grxnMxzEleYK8RzMleI52ReKCpX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fUHkRmeckrjDPSTx/5gpxhblCvHDiCnOFeE7mCnOFeE7mOYnnJJ6TeeHEFeYK8ZzMczLPn7lCXGFeOPP8mRcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QeeHEczLPSTwn85zEi8ZcIa4wV4grzAsnrjBXiH8d85zEFeYKcYW5QlxhnpN4Tub5E8+feU7iCvPvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv9G4vkTz5+5Qjwnc4V4TuI5iRfOvHDmCnGFuUJcIa4wV5grxBXmCvGcxHMyV4jnT1xhrhAvGvHCmReKylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wfIvGjEczIvGvGczHMSV5grxIvGXCGeP/OcxIvGXCFeOPP8iSvMcxJXmOdPPCdzhXhO5grxnMwLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8i85zEFeY5iSvMFebfxlwhnj/x/JnnJF405jmZ5088J/HCiRdOPH/iOZkrxL8Jlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/BuZ5888J3GFuUI8J3OF+Lcxz0lcYZ6Tef7Ei0ZcYZ4/8/yZ5ySuMM/JPH/iCnGFeU7iRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AvFvY64wV4grzBXi+TNXiCvMcxLPSTwn88KJK8zzJ64wV4grzAsnrjBXiCvMFeI5iedPXGGek3lO4grzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZUXkXnRiOckrjDPyVwhrjBXiCvMcxLPyVwhrjDPSTx/5vkTz0k8J/GczHMyV4grzHMyV4gXzrxozBXiCvNCUbnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr+SeP7MCyeuMM+feE7iCvOiEVeY50+8cOaFE1eYK8QV5jmZK8S/jvi3MS8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+W8inpP51xFXmOfPvHDiCnOFuMI8J/H8mSvEFeYK8fyZK8QV5grxnMwV4grz/IkrzIuEylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdU/puYF414TuaFE8/JPCfx/JkrxAsnrjDPSTx/5gpxhblCXGGeP3OFeE7m34TKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1T+lcy/jnlO4oUzV4grzPMnXjhzhXhO5grxnMQV5oUTz5+5QlxhrhDPSVxhnj/x/JkrxBXmX4XKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8cOLfxlwhnpN5TuIK85zEczIvGnGFuUI8J/OcxBXmOYkrzBXiCvOiEVeYK8QV5t9GPH/mRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/A2Su+n+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wf8I0R1tG46Vec2AAAAAElFTkSuQmCC", "display_to_timestamp": 1744371750000, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "aa3223d2-bd54-44d0-8816-fdbeae885c14", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "aa3223d2-bd54-44d0-8816-fdbeae885c14", "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uEuYQIIpwmhh2zZgfnCK", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T11:42:27.560Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T11:27:32.090Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>QR Code</summary> <img width="691" alt="image" src="https://github.com/user-attachments/assets/5e088c40-aaea-4056-baf5-e81b1a88603d" /> <img width="704" alt="image" src="https://github.com/user-attachments/assets/b87e6a91-a4d7-4dfa-a846-1cf785e8b298" /> </details> <details> <summary>Retrieve Call</summary> ```curl curl --location 'http://localhost:8080/payments/pay_HqjCP9OWtYlxg0KYwPMU?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' ``` ```json { "payment_id": "pay_HqjCP9OWtYlxg0KYwPMU", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_customer_action", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "facilitapay", "client_secret": "pay_HqjCP9OWtYlxg0KYwPMU_secret_VZlpnxNdhvw9MExKApxo", "created": "2025-04-11T11:27:27.560Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "pix": { "pix_key": null, "cpf": "866.***.**5-80", "cnpj": null, "source_bank_account_id": "739d****-****-****-****-********99bb", "destination_bank_account_id": "91f5****-****-****-****-********f0bc" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAegAAAHoCAAAAACnOyPQAAAUIklEQVR4Ae3gAZAkSZIkSRKLqpm7R0REZmZmVlVVVVV3d3d3d/fMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMdHd3d3dXV1VVVVVmZkZGRIS7m5kKz0xmV3d1d3dPz8zMzMxMYjVX/T9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxb2NeNOIK85zEFeY5iRfOXCGuMFeI5888J3GFeU7ihTNXiOdknpO4wjx/4t/GvFBUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6DyIjIvGvH8iedkrjBXiCvMFeYK8ZzMFeI5medknpO5QlxhnpN4/sQV5gpxhblCXCGek7lCPH/iCvP8mReNeJFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv5J4/szzJ56TuUI8J/OvY56TeP7MFeL5Ey+cuUI8f+b5E1eY50+8aMTzZ/5VqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5b+IeU7mCnGFeE7mOZnnT7xw4grz/JkrxBXmhTNXiH8d8ZzMFeIK85+KylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdU/ocx/zbmCnGFuUJcIV44c4W4wjx/4vkzV4h/HfNfgspV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP6VzL+NuMJcIZ6TuUJcYV44cYW5QlxhrhDPyTx/4vkTz8k8f+IK8fyJK8wV4l/H/IegctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5H49zFXiCvMFeJfR1xhrhBXmCvEFeYK8ZzEFeaFM1eI5ySuMM/JXCGuMFeIF05cYZ6T+A9F5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLzH8tcIa4wV4jnzzwn85zMFeI5iefPPH/iOYl/HXGFuUK8cOIK85zMfwoqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/HyDzwokrzBXiRWOek3jhzBXi+TNXiBfOXCH+dcxzEs+feU7iCnOFuMJcIa4wz0k8J3OFeNGYfxUqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5F5gXjXnhzBXihTNXiH8b8fyZK8QLJ64wL5x44cQV5jmJ52SuEFeYK8RzMs9JXGFeJFSu+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/QOaFE1eYF048f+YKcYV5/sQV5vkTz8k8J/GczHMSz8lcIZ6Tef7EFeY5iedkrhDPyVwhrjAvnHhO5jmJK8yLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP4F5jmJK8xzMs9JXCGuMFeIK8wV4grznMTzZ64Qz8k8f+IK85zEFeb5E1eYK8wV4grznMwV4gpzhXjRiCvMFeb5E/8mVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8Qz8lcIa4wV4jnZK4Qz594/sS/j7jCXGGuEM/JXCGuMFeIK8xzEleY509cYa4QL5x4TuYKcYW5QvyHoHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BMi+ceOHMi0ZcYa4QV5grxHMyV4jnZJ6TeE7mCnGFeU7i+TNXiCvMFeL5M8+fuMJcIa4wL5x4/sxzEleYK8QV5oWictX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVf4G5QlxhrhDPSTwnc4V4TuIK85zMFeI5medPPCfznMxzEleYK8QV5vkTV5jnJJ6TuMI8f+YKcYW5Qjwnc4V4/sQV5gpxhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v8AmRdOPH/mCvGczBXiCvP8iedkrhAvGnOFeE7mOYkrzBXiCvNvI54/8/yJK8y/jbjCPCdxhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/AXCGuMM/JPCfxnMQLZ64QV5jnT1xhrhBXmCvE82euEM+fuMJcIV405vkTz8k8J/H8mReN+DehctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wEyL5y4wjwncYV5/sQLZ144cYV5TuI5mSvEFeaFE1eY5088J3OFuMJcIZ6TuUJcYa4QV5jnTzwnc4V44cy/CpWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqLyIxPMnnj/znMRzEleYF424wjwn8fyJ589cIa4wz5+5QlxhnpN5TuIK85zMFeIK85zMFeIKcYW5QlxhrhDPSVxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/HyDzwokrzBXiOZkXTjx/5jmJK8wV4jmZ5ySuMC+ceNGY5ySuMFeIK8wV4grz/InnZJ6TuMJcIZ4/88KJK8wLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv8C88KJ589cYV44cYW5Qlxhnj/x/IkrzPNnrhAvnLjCXCGuMM/JXCGuMM/JvGjEFeZfR/yrULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v8AmRdOPCfz/IkrzBXiCvP8iRfOXCGeP/PCiSvMFeIK86IRz5+5Qjx/5grxnMwV4jmZK8QV5oUTz595oahc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/gMyLRjx/5jmJK8xzEi8ac4W4wjwncYW5QlxhnpN4TuYK8ZzM8yeuMC+cuMI8J3GFuUI8J/P8iSvMFeI5mSvEFeZFQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8i86IxV4grzBXmOYnnZP5tzBXiCnOFuUI8J/OvI64wL5y4wrxw5vkTV5grxBXmCvHvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8icYW5QrxoxBXm+TNXiP9Y4jmJF848J3OFeE7iCnOFuUJcIZ6TuMJcIV448ZzE82euEFeYF4rKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8cOIKc4V4/szzJ54/85zEczJXiOfPvGjEFeb5E8/JPH/i+TPPSVxhnpN44czzJ64wz5+4wrxQVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8wV4grzBXi+RNXmOdkXjjz/JkrxBXmOYkrzItGXGGek7lCPCdzhblCPH/i+RNXmOcknj9xhXlO4vkzLxIqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5F4jnz1whnpP59xFXmOdknpO4wlwhnpN5/szzJ1405grx/JnnZK4Qz8lcIZ6Tef7MvwuVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D5D51xH/Nub5E8/JvHDiP4d54cRzMleIF85cIa4wV4h/HXOFeE7mRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AnGFucJcIZ4/88KJF424wjx/5grx/JkrxHMyV4grzL+OuUJcYZ6TeP7MFeIK85zEFeb5E1eYK8S/CpWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqPw7meck/m3MFeI5iRfOXCFeOPOczHMSz8k8f+IK85zECyeuMM9JXGGek7jCPCfxb0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/SuIK8/yZ5ySek3nhzAsnXjTiCnOFuMJcIZ6TuUI8J/GczHMSz8k8J/GcxL+OuML8u1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMqLSFxhnpO4wlwhnpN5TuIKc4W4wjx/4oUTz5+5Qlxh/nOY5ySeP/PCiSvMczJXiOdk/lWoXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMfwxxhXlO4grznMQV5jmJK8wLJ54/8/yJK8wLJ64wz0lcYZ6TuMJcIa4wz5+4wlwhnpN5TuIK8/yJK8wLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv9G4gpzhblCvHDiOYkrzPMnrjBXiCvMFeIKc4W4wlwhrjBXiOdkXjTmCnGFucJcIZ6TuMJcIZ4/85zEFeYK8/yJK8yLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP4F4jmZK8xzEleY5ySek3nRiCvMFeIK88KZK8QV5jmZK8TzZ56TeE7mCnGFeU7m+TPPSVxhnpN54cS/CZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PkPnXEVeY509cYZ6TeE7mCnGFuUI8J/OcxHMyV4grzItGPCdzhbjCvGjEFeYK8ZzMcxJXmOckrjDPn7jCXCGuMC8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+ReI52SuEFeYK8QV5vkzV4jnZK4QV5jnJJ4/c4W4wlwhrjBXiOfPXCGek7lCPH/mCvHCmRdOXGGek3j+zL8Llav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/CuJK8wV4gpzhbjCXCGuMP825gpxhblCXGGeP/GczItGPCdzhXhO5vkzV4jnzzwn8aIRV5h/EypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fIPOiES8ac4X4j2GuEFeY50+8aMwV4gpzhXj+zPMnrjDPn3hO5grxnMxzEleYK8RzMleI52ReKCpX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fUHkRmeckrjDPSTx/5gpxhblCvHDiCnOFeE7mCnOFeE7mOYnnJJ6TeeHEFeYK8ZzMczLPn7lCXGFeOPP8mRcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QeeHEczLPSTwn85zEi8ZcIa4wV4grzAsnrjBXiH8d85zEFeYKcYW5QlxhnpN4Tub5E8+feU7iCvPvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv9G4vkTz5+5Qjwnc4V4TuI5iRfOvHDmCnGFuUJcIa4wV5grxBXmCvGcxHMyV4jnT1xhrhAvGvHCmReKylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wfIvGjEczIvGvGczHMSV5grxIvGXCGeP/OcxIvGXCFeOPP8iSvMcxJXmOdPPCdzhXhO5grxnMwLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8i85zEFeY5iSvMFebfxlwhnj/x/JnnJF405jmZ5088J/HCiRdOPH/iOZkrxL8Jlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/BuZ5888J3GFuUI8J3OF+Lcxz0lcYZ6Tef7Ei0ZcYZ4/8/yZ5ySuMM/JPH/iCnGFeU7iRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AvFvY64wV4grzBXi+TNXiCvMcxLPSTwn88KJK8zzJ64wV4grzAsnrjBXiCvMFeI5iedPXGGek3lO4grzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZUXkXnRiOckrjDPyVwhrjBXiCvMcxLPyVwhrjDPSTx/5vkTz0k8J/GczHMyV4grzHMyV4gXzrxozBXiCvNCUbnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr+SeP7MCyeuMM+feE7iCvOiEVeY50+8cOaFE1eYK8QV5jmZK8S/jvi3MS8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+W8inpP51xFXmOfPvHDiCnOFuMI8J/H8mSvEFeYK8fyZK8QV5grxnMwV4grz/IkrzIuEylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdU/puYF414TuaFE8/JPCfx/JkrxAsnrjDPSTx/5gpxhblCXGGeP3OFeE7m34TKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1T+lcy/jnlO4oUzV4grzPMnXjhzhXhO5grxnMQV5oUTz5+5QlxhrhDPSVxhnj/x/JkrxBXmX4XKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8cOLfxlwhnpN5TuIK85zEczIvGnGFuUI8J/OcxBXmOYkrzBXiCvOiEVeYK8QV5t9GPH/mRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/A2Su+n+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wf8I0R1tG46Vec2AAAAAElFTkSuQmCC", "display_to_timestamp": 1744371750000, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "aa3223d2-bd54-44d0-8816-fdbeae885c14", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "aa3223d2-bd54-44d0-8816-fdbeae885c14", "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uEuYQIIpwmhh2zZgfnCK", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T11:42:27.560Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T12:02:17.950Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>Refund call</summary> ```curl curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data '{ "payment_id": "pay_HqjCP9OWtYlxg0KYwPMU", "amount": 600, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "error": { "type": "invalid_request", "message": "This Payment could not be refund because it has a status of requires_customer_action. The expected state is succeeded, partially_captured", "code": "IR_14" } } ``` </details> <details> <summary>Void call</summary> Authorize ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data-raw '{ "amount": 10400, "currency": "BRL", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10400, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_oEMHiZFEcOnYfhKdCGkX", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_payment_method", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_oEMHiZFEcOnYfhKdCGkX_secret_4pCGB9AmNlBGvZUcT8La", "created": "2025-04-11T17:53:10.739Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T18:08:10.739Z", "fingerprint": null, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T17:53:10.747Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` Confirm ```curl curl --location 'http://localhost:8080/payments/pay_oEMHiZFEcOnYfhKdCGkX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_e765522f7c7543b9844fbcb1ab283a71' \ --data '{ "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": { "cpf": "866.656.235-80", "source_bank_account_id": "739d6b0a-e92a-40fd-9f58-6d4cdeb699bb", "destination_bank_account_id": "91f5cac1-9058-44b7-80e1-80c6f4a6f0bc", "pix_qr_expiry": "2025-04-11T19:53:54.807Z" } } }, "client_secret": "pay_oEMHiZFEcOnYfhKdCGkX_secret_4pCGB9AmNlBGvZUcT8La" }' ``` ```json { "payment_id": "pay_oEMHiZFEcOnYfhKdCGkX", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_customer_action", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "facilitapay", "client_secret": "pay_oEMHiZFEcOnYfhKdCGkX_secret_4pCGB9AmNlBGvZUcT8La", "created": "2025-04-11T17:53:10.739Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "pix": { "pix_key": null, "cpf": "866.***.**5-80", "cnpj": null, "source_bank_account_id": "739d****-****-****-****-********99bb", "destination_bank_account_id": "91f5****-****-****-****-********f0bc" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAegAAAHoCAAAAACnOyPQAAAUO0lEQVR4Ae3gAZAkSZIkSRKLqpm7R0REZmZmVlVVVVV3d3d3d/fMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMdHd3d3dXV1VVVVVmZkZGRIS7m5kKz0xmV3d1d3dPz8zMzMxMYjVX/T9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxb2OeP/GczHMSV5gXjbjCPH/iCvOcxBXmOYkrzHMSL5x5TuI5mSvEFeb5E/825oWictX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5F50YjnTzx/4vkTz5950YjnJK4wV5grxAsnrjBXiCvMFeL5M89JPCdxhXn+zItGvEioXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0DlX0k8f+b5E8+fuUK8aMwV4gpzhblCPCdzhbjCPCdxhXnhzBXiP4a5QrxoxPNn/lWoXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlv4i5QlwhrjBXiCvMFeIKc4W4wlwhrjAvGnGFeU7iCvOiMVeIK8wV4jmZ52SuEFeYK8QV5j8Vlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/BcRLxpxhblCPCfx/JkrxAsnXjhxhXn+xHMSV5grxBXiCvPCmf8SVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8q9k/m3MFeIKc4W4wjx/5l/HXCGek3n+xBXiOYnnZJ6TuMJcIf5zmP8QVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8iIS/zXEFeYKcYW5QlxhrhBXmCvEFeYK8ZzEFeY5mSvEFeYK8ZzEFeYKcYW5QlxhrhBXmOdPXGGek/gPReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZP5ziRfOPH/iCnOFeOHM8yeuMM+feP7MFeJfx7xw4vkz/6moXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMCyeuMFeIF4150YjnZJ4/8aIxV4h/HfPCiSvMCyeek3n+xBXmOYkXjflXoXLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BlX8nc4W4wlwhrjBXiCvMFeIK88KJK8wLJ64QV5grxHMyz5+4wrxw4vkzz8k8f+IK85zEFeYK8ZzMcxJXmBcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QedGIK8wV4jmZK8QV5vkT/z3MFeJFY64Qz5+5Qjwn88KJ5888J/GczHMSV5gXCZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqPwLxBXmOZkrxBXiCnOFuMJcIa4wV4gXzlwhrjDPSTwn8/yJF85cIa4wz8k8f+IKc4W4QlxhrhBXmOdknpO4wlxhrhDPSfybULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/AXCGek3lO5gpxhblCPH/mCvGczBXiOYnnz1whrjDPn3jhzBXiRWOek3lO4oUTV5grzBXiCvOcxL8Llav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+Q+bcRz8k8J/GvY56TeP7MFeKFM89JXGGuEM/JXCGuMFeI52Sek7jCXCGuMFeIK8zzJ54/c4W4wjwn8ZzMC0Xlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AnGFuUK8cOI5meckrjBXiCvEFeY5mefPXCGek3nhxHMyL5y5Qjwn8ZzE82euEFeY589cIa4Qz0lcYZ6TeZFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv5G5Qjwnc4V4TuKFMy+ceOHM8yeuMFeI5ySuMFeY5yReNOb5E1eY5ySuMFeIF848J3OFuMK8UFSu+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oPJvJJ4/cYV5TuYK8fyJK8y/jrlCvHDiCvPCiSvM8yeuMM+feE7mhRMvGvGczBXmRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AvOczBXiCvOczHMSV5grzBXiOZnnZJ4/c4V44cwV4jmJ58+8aMwV4oUzV4grzBXiCnOFeP7McxJXmCvEFeZFQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZF404grznMQV5grx/JkrxBXmCnGFuUJcYa4QV5jnT1xhrhDPn3lO4grznMQV5jmJ52Sek7jC/NuI52ReOHGFeZFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/wCZF424wlwhrjDPn7jCXCFeOPP8iRfOXCGek7lCXGGuEM+feU7iCnOFuMJcIa4wz0lcYZ4/8ZzMcxLPyfyHoHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BMi+cuMJcIa4wV4grzBXihTNXiOdknpN4TuY5iedkrhBXmCvEi8ZcIa4wV4grzPMnrjDPSTwn85zEczJXiCvMcxLPyVwhrjAvFJWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqLyIxPNnnpN5TuIK85zM8yeuMFeIK8QV5vkTV5grxBXm+RNXmOdkrhDPSVxhrhAvnHn+xHMyL5y4wlwh/k2oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMi0Y8f+Y5iedkrhDPn3nhxHMy/zriCnOFuMJcIV4488KJ589cIZ4/85zEczLPn3hO5kVC5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxohFXmOfPXCGuMM9JPH/mOYkrzHMSV5grxBXm+RPPyTwncYW4wjx/5gpxhblCXGGuEFeYF424wlwhrjBXiH8VKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9QeRGZK8RzEs9JvGjE82eek3hO5grxwpkrxL+OuMJcIZ6TuMJcIZ6TeOHEFeYK8cKJK8wV4grzr0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AyovInGFeU7iCvP8iSvMFeIKc4V4TuIKc4V5TuIK88KJ52SeP/HCmSvEC2euEFeY589cIZ6Tef7EczLPSVxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1B5EZkrxBXm+RNXmOcknpN40YjnZJ6TuMK8aMQV5jmJK8wV4gpzhblCPH/iOYkrzBXmOZkrxHMSV5jnJJ4/8yKhctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5F4TuL5My+cuUL865jnzzwn8cKZ589cIa4wz0k8f+YKcYW5Qlwh/nXM82f+Xahc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/gMwLJ64wz0n825jnJJ6TedGI589cIf51zHMSz8k8f+Jfxzwn8aIxV4jnZF4kVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8m9knpO4wlwhnpN5TuIKc4V4TuIK85zEczIvnHlO4gpzhbhCXGGek7lCPCdzhXlO4jmZ5yReNOY5iSvMFeJfhcpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HyLxw4jmZ5yReNOYK8ZzMFeIK85zE82euEFeYK8R/DPP8iReNeU7iCnOFeP7MFeIKc4V4/syLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HyLxoxHMyz0lcYZ6TeE7mCnGFeU7iOZnnJK4wV4grzHMSz8lcIa4wV4jnZF404grznMQV5grx/JnnJK4wV4jnZP5dqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X+AzAsnnpN5TuKFM8+feE7mOYkXzjwncYV5/sQLZ56TeE7mCnGFuUJcYa4Qz595TuL5M1eIK8wV4jmZfxUqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5VxJXmCvMFeIKc4W4QlxhnpN50ZjnJJ6TeP7EczLPSVxhrhBXmCvMcxIvGvPCiedkrhDPyVwhnj9xhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/APCdxhbjCPCdxhXn+xBXmOYnnZJ6TuMJcIa4wL5x5TuIKc4W4wlwhnpN5TuYKcYW5Qjx/5grxnMwV4gpzhbjCXGGeP/GvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZF44cYV5/sRzMs9J/McwV4grzHMSz595/sQV5vkTz5+5Qlxh/m3EFebfRjwn80JRuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv8BcIa4wz8k8J/GczPMnnpN54cTzJ64wV4grzAtnnj9xhblCXGGek7lCXGGek7jCXCGuMM+fuMI8f+I5mX8VKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+ReIF424wjwn8ZzMFeY5iSvMFeJfR1xhrhD/OuYK85zMcxIvGvOczItGPCdzhXlO4jmZF4rKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8aMRzMleI589cIa4wV4h/G/PCiSvMcxLPn7lCXGGuEC+cef7EFeYK8fyZK8S/jrlCPCfzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/ATL/OuL5M89JXGGuEM/JXCFeOPNvI64wz5+4wjx/4grz/IkrzPMnrjDPSTwn85zEczLPn7jCvEioXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0DlRSSek7lCPCfxwpl/G/H8mSvEFeYK88KZF848f+IKc4W4wlwhrjAvnLlCXGGuMP864grzQlG56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMq/QLxw5jmZ589cIa4wz8lcIZ6TuMJcIZ4/85zEczJXiCvMFeIK85zEFeYKcYW5QlxhnpO5Qlxhnj/x/IkrzBXi+TNXiBcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QeeHEczJXiH8bc4W4wrxoxBXmOYkrzHMSz595TuI5meckrjBXiOfPvHDiCvOcxPNnrhBXmOckrjAvEipX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fIPOiEc/JvHDi+TPPSVxhrhAvnLlCvHDm+RPPn7lC/OuY5ySuMFeIK8wV4grznMRzMleIK8zzJ64wLxSVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D5D5txFXmOckXjTmCvH8mSvEv455TuJfx7xw4jmZK8QLZ54/8aIxV4jnz7xQVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8m9knj/znMRzMleIK8wV4grz/JnnTzx/4jmZ509cYV44cYW5QlwhrjDPn3hO4grznMzzJ64QV5jnJF4kVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8Q/zbmCvP8mSvEcxLPn7jCPCfznMQV5grxnMQV5jmJK8xzEleYF05cYa4QL5x4/sQV5jmZ5ySuMC8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9QeRGZF414TuIK8/yZK8RzMleI5ySuMM9JvGjM82eeP/P8medP/PuYF425QlxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5VxLPn/nXEc/JXCGek7lCvHDmCvH8iReNuMK8cOI5mSvMFeIKc4V44cS/jXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayn8x8fyJK8wV4grznMzzJ64wV4jnZK4Qz8lcIa4wz0k8J/PCiSvMczJXiCvMFeIKc4W4wrxw4grzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZX/YuYKcYW5QlwhnpO4wlwhnpO5wjwnc4X41xHPyTwncYV5TuL5E8/JPCfznMzzJ64w/yZUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6Dyr2T+dcwV4jmZ589cIZ4/c4V4TuI5mefPPH/mCvH8iRfOvGjEFeaFE1eYK8wV4grzr0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AyovIvFvI64wz0lcYa4wV4jnT1xhXjTiCvP8iSvMFeI5mefPPCfxnMwV4gpzhbjCXCGeP3OFuUI8f+IK8yKhctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wEyV/0/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8D/hEoC75kZ7w7cwAAAABJRU5ErkJggg==", "display_to_timestamp": 1744394897000, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "33fe7dc7-25a0-4ba5-a7d2-4245fc0b2127", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "33fe7dc7-25a0-4ba5-a7d2-4245fc0b2127", "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uEuYQIIpwmhh2zZgfnCK", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T18:08:10.739Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T17:53:19.350Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` Void ```curl curl --location 'http://localhost:8080/payments/pay_oEMHiZFEcOnYfhKdCGkX/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data '{"cancellation_reason":"requested_by_customer"}' ``` ```json { "payment_id": "pay_oEMHiZFEcOnYfhKdCGkX", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "cancelled", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "facilitapay", "client_secret": "pay_oEMHiZFEcOnYfhKdCGkX_secret_4pCGB9AmNlBGvZUcT8La", "created": "2025-04-11T17:53:10.739Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "pix": { "pix_key": null, "cpf": "866.***.**5-80", "cnpj": null, "source_bank_account_id": "739d****-****-****-****-********99bb", "destination_bank_account_id": "91f5****-****-****-****-********f0bc" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAegAAAHoCAAAAACnOyPQAAAUO0lEQVR4Ae3gAZAkSZIkSRKLqpm7R0REZmZmVlVVVVV3d3d3d/fMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMdHd3d3dXV1VVVVVmZkZGRIS7m5kKz0xmV3d1d3dPz8zMzMxMYjVX/T9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxb2OeP/GczHMSV5gXjbjCPH/iCvOcxBXmOYkrzHMSL5x5TuI5mSvEFeb5E/825oWictX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5F50YjnTzx/4vkTz5950YjnJK4wV5grxAsnrjBXiCvMFeL5M89JPCdxhXn+zItGvEioXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0DlX0k8f+b5E8+fuUK8aMwV4gpzhblCPCdzhbjCPCdxhXnhzBXiP4a5QrxoxPNn/lWoXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlv4i5QlwhrjBXiCvMFeIKc4W4wlwhrjAvGnGFeU7iCvOiMVeIK8wV4jmZ52SuEFeYK8QV5j8Vlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/BcRLxpxhblCPCfx/JkrxAsnXjhxhXn+xHMSV5grxBXiCvPCmf8SVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8q9k/m3MFeIKc4W4wjx/5l/HXCGek3n+xBXiOYnnZJ6TuMJcIf5zmP8QVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8iIS/zXEFeYKcYW5QlxhrhBXmCvEFeYK8ZzEFeY5mSvEFeYK8ZzEFeYKcYW5QlxhrhBXmOdPXGGek/gPReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZP5ziRfOPH/iCnOFeOHM8yeuMM+feP7MFeJfx7xw4vkz/6moXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMCyeuMFeIF4150YjnZJ4/8aIxV4h/HfPCiSvMCyeek3n+xBXmOYkXjflXoXLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BlX8nc4W4wlwhrjBXiCvMFeIK88KJK8wLJ64QV5grxHMyz5+4wrxw4vkzz8k8f+IK85zEFeYK8ZzMcxJXmBcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QedGIK8wV4jmZK8QV5vkT/z3MFeJFY64Qz5+5Qjwn88KJ5888J/GczHMSV5gXCZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqPwLxBXmOZkrxBXiCnOFuMJcIa4wV4gXzlwhrjDPSTwn8/yJF85cIa4wz8k8f+IKc4W4QlxhrhBXmOdknpO4wlxhrhDPSfybULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/AXCGek3lO5gpxhblCPH/mCvGczBXiOYnnz1whrjDPn3jhzBXiRWOek3lO4oUTV5grzBXiCvOcxL8Llav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+Q+bcRz8k8J/GvY56TeP7MFeKFM89JXGGuEM/JXCGuMFeI52Sek7jCXCGuMFeIK8zzJ54/c4W4wjwn8ZzMC0Xlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AnGFuUK8cOI5meckrjBXiCvEFeY5mefPXCGek3nhxHMyL5y5Qjwn8ZzE82euEFeY589cIa4Qz0lcYZ6TeZFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv5G5Qjwnc4V4TuKFMy+ceOHM8yeuMFeI5ySuMFeY5yReNOb5E1eY5ySuMFeIF848J3OFuMK8UFSu+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oPJvJJ4/cYV5TuYK8fyJK8y/jrlCvHDiCvPCiSvM8yeuMM+feE7mhRMvGvGczBXmRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AvOczBXiCvOczHMSV5grzBXiOZnnZJ4/c4V44cwV4jmJ58+8aMwV4oUzV4grzBXiCnOFeP7McxJXmCvEFeZFQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZF404grznMQV5grx/JkrxBXmCnGFuUJcYa4QV5jnT1xhrhDPn3lO4grznMQV5jmJ52Sek7jC/NuI52ReOHGFeZFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/wCZF424wlwhrjDPn7jCXCFeOPP8iRfOXCGek7lCXGGuEM+feU7iCnOFuMJcIa4wz0lcYZ4/8ZzMcxLPyfyHoHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BMi+cuMJcIa4wV4grzBXihTNXiOdknpN4TuY5iedkrhBXmCvEi8ZcIa4wV4grzPMnrjDPSTwn85zEczJXiCvMcxLPyVwhrjAvFJWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqLyIxPNnnpN5TuIK85zM8yeuMFeIK8QV5vkTV5grxBXm+RNXmOdkrhDPSVxhrhAvnHn+xHMyL5y4wlwh/k2oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMi0Y8f+Y5iedkrhDPn3nhxHMy/zriCnOFuMJcIV4488KJ589cIZ4/85zEczLPn3hO5kVC5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxohFXmOfPXCGuMM9JPH/mOYkrzHMSV5grxBXm+RPPyTwncYW4wjx/5gpxhblCXGGuEFeYF424wlwhrjBXiH8VKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9QeRGZK8RzEs9JvGjE82eek3hO5grxwpkrxL+OuMJcIZ6TuMJcIZ6TeOHEFeYK8cKJK8wV4grzr0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AyovInGFeU7iCvP8iSvMFeIKc4V4TuIKc4V5TuIK88KJ52SeP/HCmSvEC2euEFeY589cIZ6Tef7EczLPSVxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1B5EZkrxBXm+RNXmOcknpN40YjnZJ6TuMK8aMQV5jmJK8wV4gpzhblCPH/iOYkrzBXmOZkrxHMSV5jnJJ4/8yKhctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5F4TuL5My+cuUL865jnzzwn8cKZ589cIa4wz0k8f+YKcYW5Qlwh/nXM82f+Xahc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/gMwLJ64wz0n825jnJJ6TedGI589cIf51zHMSz8k8f+Jfxzwn8aIxV4jnZF4kVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8m9knpO4wlwhnpN5TuIKc4V4TuIK85zEczIvnHlO4gpzhbhCXGGek7lCPCdzhXlO4jmZ5yReNOY5iSvMFeJfhcpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HyLxw4jmZ5yReNOYK8ZzMFeIK85zE82euEFeYK8R/DPP8iReNeU7iCnOFeP7MFeIKc4V4/syLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HyLxoxHMyz0lcYZ6TeE7mCnGFeU7iOZnnJK4wV4grzHMSz8lcIa4wV4jnZF404grznMQV5grx/JnnJK4wV4jnZP5dqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X+AzAsnnpN5TuKFM8+feE7mOYkXzjwncYV5/sQLZ56TeE7mCnGFuUJcYa4Qz595TuL5M1eIK8wV4jmZfxUqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5VxJXmCvMFeIKc4W4QlxhnpN50ZjnJJ6TeP7EczLPSVxhrhBXmCvMcxIvGvPCiedkrhDPyVwhnj9xhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/APCdxhbjCPCdxhXn+xBXmOYnnZJ6TuMJcIa4wL5x5TuIKc4W4wlwhnpN5TuYKcYW5Qjx/5grxnMwV4gpzhbjCXGGeP/GvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZF44cYV5/sRzMs9J/McwV4grzHMSz595/sQV5vkTz5+5Qlxh/m3EFebfRjwn80JRuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv8BcIa4wz8k8J/GczPMnnpN54cTzJ64wV4grzAtnnj9xhblCXGGek7lCXGGek7jCXCGuMM+fuMI8f+I5mX8VKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+ReIF424wjwn8ZzMFeY5iSvMFeJfR1xhrhD/OuYK85zMcxIvGvOczItGPCdzhXlO4jmZF4rKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8aMRzMleI589cIa4wV4h/G/PCiSvMcxLPn7lCXGGuEC+cef7EFeYK8fyZK8S/jrlCPCfzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/ATL/OuL5M89JXGGuEM/JXCFeOPNvI64wz5+4wjx/4grz/IkrzPMnrjDPSTwn85zEczLPn7jCvEioXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0DlRSSek7lCPCfxwpl/G/H8mSvEFeYK88KZF848f+IKc4W4wlwhrjAvnLlCXGGuMP864grzQlG56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMq/QLxw5jmZ589cIa4wz8lcIZ6TuMJcIZ4/85zEczJXiCvMFeIK85zEFeYKcYW5QlxhnpO5Qlxhnj/x/IkrzBXi+TNXiBcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QeeHEczJXiH8bc4W4wrxoxBXmOYkrzHMSz595TuI5meckrjBXiOfPvHDiCvOcxPNnrhBXmOckrjAvEipX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fIPOiEc/JvHDi+TPPSVxhrhAvnLlCvHDm+RPPn7lC/OuY5ySuMFeIK8wV4grznMRzMleIK8zzJ64wLxSVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D5D5txFXmOckXjTmCvH8mSvEv455TuJfx7xw4jmZK8QLZ54/8aIxV4jnz7xQVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8m9knj/znMRzMleIK8wV4grz/JnnTzx/4jmZ509cYV44cYW5QlwhrjDPn3hO4grznMzzJ64QV5jnJF4kVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8Q/zbmCvP8mSvEcxLPn7jCPCfznMQV5grxnMQV5jmJK8xzEleYF05cYa4QL5x4/sQV5jmZ5ySuMC8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9QeRGZF414TuIK8/yZK8RzMleI5ySuMM9JvGjM82eeP/P8medP/PuYF425QlxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5VxLPn/nXEc/JXCGek7lCvHDmCvH8iReNuMK8cOI5mSvMFeIKc4V44cS/jXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayn8x8fyJK8wV4grznMzzJ64wV4jnZK4Qz8lcIa4wz0k8J/PCiSvMczJXiCvMFeIKc4W4wrxw4grzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZX/YuYKcYW5QlwhnpO4wlwhnpO5wjwnc4X41xHPyTwncYV5TuL5E8/JPCfznMzzJ64w/yZUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6Dyr2T+dcwV4jmZ589cIZ4/c4V4TuI5mefPPH/mCvH8iRfOvGjEFeaFE1eYK8wV4grzr0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AyovIvFvI64wz0lcYa4wV4jnT1xhXjTiCvP8iSvMFeI5mefPPCfxnMwV4gpzhbjCXCGeP3OFuUI8f+IK8yKhctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wEyV/0/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8D/hEoC75kZ7w7cwAAAABJRU5ErkJggg==", "display_to_timestamp": 1744394897000, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": "requested_by_customer", "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "33fe7dc7-25a0-4ba5-a7d2-4245fc0b2127", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "33fe7dc7-25a0-4ba5-a7d2-4245fc0b2127", "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uEuYQIIpwmhh2zZgfnCK", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T18:08:10.739Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T17:53:20.936Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>Manual Capture</summary> Authorize ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data-raw '{ "amount": 10400, "currency": "BRL", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10400, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_ytZ1ZAAsTwKK0F7uA2IH", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_payment_method", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_ytZ1ZAAsTwKK0F7uA2IH_secret_HjrEsQIrDAQunFZVLQY4", "created": "2025-04-11T17:55:46.411Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T18:10:46.411Z", "fingerprint": null, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T17:55:46.418Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` Confirm ```curl curl --location 'http://localhost:8080/payments/pay_ytZ1ZAAsTwKK0F7uA2IH/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_e765522f7c7543b9844fbcb1ab283a71' \ --data '{ "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": { "cpf": "866.656.235-80", "source_bank_account_id": "739d6b0a-e92a-40fd-9f58-6d4cdeb699bb", "destination_bank_account_id": "91f5cac1-9058-44b7-80e1-80c6f4a6f0bc", "pix_qr_expiry": "2025-04-11T19:53:54.807Z" } } }, "client_secret": "pay_ytZ1ZAAsTwKK0F7uA2IH_secret_HjrEsQIrDAQunFZVLQY4" }' ``` ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "manual is not supported by facilitapay" } } ``` </details> <details> <summary>Cypress tests</summary> <img width="889" alt="image" src="https://github.com/user-attachments/assets/09dd0c44-5ca4-4387-bcd4-0555bdc6a615" /> </details>
[ "api-reference-v2/openapi_spec.json", "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/enums.rs", "crates/api_models/src/payments.rs", "crates/api_models/src/payments/additional_info.rs", "crates/common_enums/src/connector_enums.rs", "crates/common_enums/src/enums.rs", "crates/connector_configs/src/connector.rs", "crates/connector_configs/toml/development.toml", "crates/connector_configs/toml/production.toml", "crates/connector_configs/toml/sandbox.toml", "crates/hyperswitch_connectors/src/connectors/facilitapay.rs", "crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs", "crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs", "crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs", "crates/hyperswitch_connectors/src/default_implementations.rs", "crates/hyperswitch_connectors/src/default_implementations_v2.rs", "crates/hyperswitch_connectors/src/utils.rs", "crates/hyperswitch_domain_models/src/payment_method_data.rs", "crates/payment_methods/src/configs/payment_connector_required_fields.rs", "crates/router/src/core/admin.rs", "crates/router/src/core/payments.rs", "crates/router/src/types/api.rs", "crates/router/src/types/transformers.rs", "crates/router/tests/connectors/sample_auth.toml", "loadtest/config/development.toml" ]
juspay/hyperswitch
juspay__hyperswitch-7668
Bug: Update Postman Collection Need to update the Postman Collection for all the connectors, to use API Key instead of AdminAPI Key, to avoid throwing errors on Jenkins Pipeline.
diff --git a/postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 2898675c1f2..39bc76dc5f7 100644 --- a/postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 60c38c826af..9422cfc60d0 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json index e4b52afd7ca..351a1e5facb 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json index c3696696ddf..bfb34b5f81f 100644 --- a/postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 2570bc3f1d5..9a7056a3458 100644 --- a/postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json index 3ea447df397..e5ae7c9bc42 100644 --- a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json +++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 83c58bd9680..a5e94d7fd8c 100644 --- a/postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 83c58bd9680..a5e94d7fd8c 100644 --- a/postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/API Key/.meta.json b/postman/collection-dir/bankofamerica/API Key/.meta.json index 0388c2d61b4..bad437ba719 100644 --- a/postman/collection-dir/bankofamerica/API Key/.meta.json +++ b/postman/collection-dir/bankofamerica/API Key/.meta.json @@ -3,7 +3,6 @@ "Create API Key", "Update API Key", "Retrieve API Key", - "List API Keys", - "Delete API Key" + "List API Keys" ] } diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index cc19ac2bab2..8d3a6dd36e0 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -48,8 +48,8 @@ "payment_method_data": { "card": { "card_number": "4242424242424242", - "card_exp_month": "01", - "card_exp_year": "24", + "card_exp_month": "10", + "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json index 14f671d7f6f..320472d2566 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json @@ -40,8 +40,8 @@ "payment_method_data": { "card": { "card_number": "4242424242424242", - "card_exp_month": "01", - "card_exp_year": "24", + "card_exp_month": "10", + "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json index f47c4f9d3bb..b8ea1c556dd 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json b/postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json index 3f8bc360dd4..6d68eeab4ab 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json @@ -5,6 +5,7 @@ "Payment Connector - Update", "List Connectors by MID", "Payment Connector - Delete", - "Merchant Account - Delete" + "Merchant Account - Delete", + "Delete API Key" ] } diff --git a/postman/collection-dir/bankofamerica/API Key/Delete API Key/.event.meta.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/.event.meta.json similarity index 100% rename from postman/collection-dir/bankofamerica/API Key/Delete API Key/.event.meta.json rename to postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/.event.meta.json diff --git a/postman/collection-dir/bankofamerica/API Key/Delete API Key/event.test.js b/postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/event.test.js similarity index 100% rename from postman/collection-dir/bankofamerica/API Key/Delete API Key/event.test.js rename to postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/event.test.js diff --git a/postman/collection-dir/bankofamerica/API Key/Delete API Key/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/request.json similarity index 100% rename from postman/collection-dir/bankofamerica/API Key/Delete API Key/request.json rename to postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/request.json diff --git a/postman/collection-dir/bankofamerica/API Key/Delete API Key/response.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/response.json similarity index 100% rename from postman/collection-dir/bankofamerica/API Key/Delete API Key/response.json rename to postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/response.json diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json index 89aa4e59406..0ae1fe13e0a 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json index f47c4f9d3bb..b8ea1c556dd 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json index b87e6538125..bf901d6b467 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json index db33632a3ad..a3d3b6b9189 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 572a23fd7a2..2b58056d193 100644 --- a/postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json index b65988d0f19..94a18d71e90 100644 --- a/postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 68f12ba04e1..a9b14b69df7 100644 --- a/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 35bf67cdd4e..8971181613d 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 9ad21398b73..c8699219e41 100644 --- a/postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 89739480aa8..1d02bdf748d 100644 --- a/postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/API Key/.meta.json b/postman/collection-dir/hyperswitch/API Key/.meta.json index 0388c2d61b4..bad437ba719 100644 --- a/postman/collection-dir/hyperswitch/API Key/.meta.json +++ b/postman/collection-dir/hyperswitch/API Key/.meta.json @@ -3,7 +3,6 @@ "Create API Key", "Update API Key", "Retrieve API Key", - "List API Keys", - "Delete API Key" + "List API Keys" ] } diff --git a/postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json index 29cf7b13b01..f4ab0deef92 100644 --- a/postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json b/postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json index 3f8bc360dd4..6d68eeab4ab 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json @@ -5,6 +5,7 @@ "Payment Connector - Update", "List Connectors by MID", "Payment Connector - Delete", - "Merchant Account - Delete" + "Merchant Account - Delete", + "Delete API Key" ] } diff --git a/postman/collection-dir/hyperswitch/API Key/Delete API Key/.event.meta.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/.event.meta.json similarity index 100% rename from postman/collection-dir/hyperswitch/API Key/Delete API Key/.event.meta.json rename to postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/.event.meta.json diff --git a/postman/collection-dir/hyperswitch/API Key/Delete API Key/event.test.js b/postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/event.test.js similarity index 100% rename from postman/collection-dir/hyperswitch/API Key/Delete API Key/event.test.js rename to postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/event.test.js diff --git a/postman/collection-dir/hyperswitch/API Key/Delete API Key/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/request.json similarity index 100% rename from postman/collection-dir/hyperswitch/API Key/Delete API Key/request.json rename to postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/request.json diff --git a/postman/collection-dir/hyperswitch/API Key/Delete API Key/response.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/response.json similarity index 100% rename from postman/collection-dir/hyperswitch/API Key/Delete API Key/response.json rename to postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/response.json diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json index 81d0ea5ef1e..f731ff3a422 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json index 38cf4e46f2e..3b12122e568 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json index 7536380bcf0..05f84b5771e 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json index 9deb9f0addc..4cd08383649 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json index 29cf7b13b01..f4ab0deef92 100644 --- a/postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 4f209de9030..dee607ae12a 100644 --- a/postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 1385e967bbd..317065ac581 100644 --- a/postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json b/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json index eb5a39cc56c..de7f5dfeebd 100644 --- a/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json +++ b/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 4928ee1d4bd..a1a6e69049d 100644 --- a/postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 23629d0fa75..fee1cb79ce5 100644 --- a/postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 32e3afc6348..db7adca82fe 100644 --- a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 71463f2446f..b7ba97dc3ea 100644 --- a/postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json index cdcee289022..583b419632a 100644 --- a/postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 3b60b0db2e4..e6fb6924ae6 100644 --- a/postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json index fd47c40ce19..936435de29c 100644 --- a/postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json index d19329121f5..ae74abf20ab 100644 --- a/postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 9b7f48dca22..a9321943c5d 100644 --- a/postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/API Key/.meta.json b/postman/collection-dir/stripe/API Key/.meta.json index 0388c2d61b4..bad437ba719 100644 --- a/postman/collection-dir/stripe/API Key/.meta.json +++ b/postman/collection-dir/stripe/API Key/.meta.json @@ -3,7 +3,6 @@ "Create API Key", "Update API Key", "Retrieve API Key", - "List API Keys", - "Delete API Key" + "List API Keys" ] } diff --git a/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 140ececab9a..2922d5654c0 100644 --- a/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/.meta.json b/postman/collection-dir/stripe/PaymentConnectors/.meta.json index 3f8bc360dd4..6d68eeab4ab 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/.meta.json +++ b/postman/collection-dir/stripe/PaymentConnectors/.meta.json @@ -5,6 +5,7 @@ "Payment Connector - Update", "List Connectors by MID", "Payment Connector - Delete", - "Merchant Account - Delete" + "Merchant Account - Delete", + "Delete API Key" ] } diff --git a/postman/collection-dir/stripe/API Key/Delete API Key/.event.meta.json b/postman/collection-dir/stripe/PaymentConnectors/Delete API Key/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/API Key/Delete API Key/.event.meta.json rename to postman/collection-dir/stripe/PaymentConnectors/Delete API Key/.event.meta.json diff --git a/postman/collection-dir/stripe/API Key/Delete API Key/event.test.js b/postman/collection-dir/stripe/PaymentConnectors/Delete API Key/event.test.js similarity index 100% rename from postman/collection-dir/stripe/API Key/Delete API Key/event.test.js rename to postman/collection-dir/stripe/PaymentConnectors/Delete API Key/event.test.js diff --git a/postman/collection-dir/stripe/API Key/Delete API Key/request.json b/postman/collection-dir/stripe/PaymentConnectors/Delete API Key/request.json similarity index 100% rename from postman/collection-dir/stripe/API Key/Delete API Key/request.json rename to postman/collection-dir/stripe/PaymentConnectors/Delete API Key/request.json diff --git a/postman/collection-dir/stripe/API Key/Delete API Key/response.json b/postman/collection-dir/stripe/PaymentConnectors/Delete API Key/response.json similarity index 100% rename from postman/collection-dir/stripe/API Key/Delete API Key/response.json rename to postman/collection-dir/stripe/PaymentConnectors/Delete API Key/response.json diff --git a/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json b/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json index e3ed8ab2925..637e403e782 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json index 1e810266994..afe396aa8f1 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json index f88a293e6ad..f2da67aa6f4 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json index bb5f920fc50..ef06cfc1cc4 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json index 97afd9f26e7..d592bad50f6 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json index f9631103356..31a26118750 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json index 658889d26dc..af8ae95c3e9 100644 --- a/postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json b/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json index 84c7a2fa48c..980c77b8515 100644 --- a/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json +++ b/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json index b6c15ab9af2..77bf15bf889 100644 --- a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 532d3672d7e..e99e7a249a8 100644 --- a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json b/postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json index 6b4757c18c3..9b3725fe8ad 100644 --- a/postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json +++ b/postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 4225d477936..aa161413fd5 100644 --- a/postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 4a2d34a4aa9..58766c99271 100644 --- a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json index db15acdaaee..8ee4d78ae89 100644 --- a/postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, {
2025-04-02T10:04:20Z
## Description <!-- Describe your changes in detail --> Modified the Auth in the postman collection for payment connectors, from Admin API Key to API Key. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Ensure proper testing for the Payment Connector APIs. # ### Stripe <img width="1191" alt="Screenshot 2025-04-02 at 5 04 26 PM" src="https://github.com/user-attachments/assets/29c5b2a7-bd54-42e1-907b-827927379f17" /> <img width="992" alt="image" src="https://github.com/user-attachments/assets/e7dc40b0-ddde-4c8d-bd5b-8496278d966e" /> ### Bankofamerica <img width="1197" alt="image" src="https://github.com/user-attachments/assets/f6b1526a-ac1d-4ef1-9e12-e8f92ba84229" /> <img width="1171" alt="image" src="https://github.com/user-attachments/assets/8c8f686d-cab5-4e82-af6b-77eb15a4f76b" /> ### Hyperswitch <img width="1214" alt="image" src="https://github.com/user-attachments/assets/a96a79c8-f16c-47bc-8367-2d92e1aef5e4" /> <img width="984" alt="image" src="https://github.com/user-attachments/assets/19306109-9c27-40fc-a6a6-8bd757a2c40e" />
b8f66155d4a23c10f129591994a8a30715375b87
### Stripe <img width="1191" alt="Screenshot 2025-04-02 at 5 04 26 PM" src="https://github.com/user-attachments/assets/29c5b2a7-bd54-42e1-907b-827927379f17" /> <img width="992" alt="image" src="https://github.com/user-attachments/assets/e7dc40b0-ddde-4c8d-bd5b-8496278d966e" /> ### Bankofamerica <img width="1197" alt="image" src="https://github.com/user-attachments/assets/f6b1526a-ac1d-4ef1-9e12-e8f92ba84229" /> <img width="1171" alt="image" src="https://github.com/user-attachments/assets/8c8f686d-cab5-4e82-af6b-77eb15a4f76b" /> ### Hyperswitch <img width="1214" alt="image" src="https://github.com/user-attachments/assets/a96a79c8-f16c-47bc-8367-2d92e1aef5e4" /> <img width="984" alt="image" src="https://github.com/user-attachments/assets/19306109-9c27-40fc-a6a6-8bd757a2c40e" />
[ "postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json", "postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json", "postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/bankofamerica/API Key/.meta.json", "postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json", "postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json", "postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json", "postman/collection-dir/bankofamerica/API Key/Delete API Key/.event.meta.json", "postman/collection-dir/bankofamerica/API Key/Delete API Key/event.test.js", "postman/collection-dir/bankofamerica/API Key/Delete API Key/request.json", "postman/collection-dir/bankofamerica/API Key/Delete API Key/response.json", "postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json", "postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json", "postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json", "postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json", "postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/hyperswitch/API Key/.meta.json", "postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json", "postman/collection-dir/hyperswitch/API Key/Delete API Key/.event.meta.json", "postman/collection-dir/hyperswitch/API Key/Delete API Key/event.test.js", "postman/collection-dir/hyperswitch/API Key/Delete API Key/request.json", "postman/collection-dir/hyperswitch/API Key/Delete API Key/response.json", "postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json", "postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json", "postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json", "postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json", "postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json", "postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/stripe/API Key/.meta.json", "postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/stripe/PaymentConnectors/.meta.json", "postman/collection-dir/stripe/API Key/Delete API Key/.event.meta.json", "postman/collection-dir/stripe/API Key/Delete API Key/event.test.js", "postman/collection-dir/stripe/API Key/Delete API Key/request.json", "postman/collection-dir/stripe/API Key/Delete API Key/response.json", "postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json", "postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json", "postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json", "postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json", "postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json", "postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json", "postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json", "postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json", "postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json", "postman/collection-dir/aci/Flow", "postman/collection-dir/adyen_uk/Flow", "postman/collection-dir/airwallex/Flow", "postman/collection-dir/authorizedotnet/Flow", "postman/collection-dir/bambora/Flow", "postman/collection-dir/bambora_3ds/Flow", "postman/collection-dir/bankofamerica/API", "postman/collection-dir/bankofamerica/Flow", "postman/collection-dir/bankofamerica/PaymentConnectors/List", "postman/collection-dir/bankofamerica/PaymentConnectors/Payment", "postman/collection-dir/bluesnap/Flow", "postman/collection-dir/braintree/Flow", "postman/collection-dir/checkout/Flow", "postman/collection-dir/cybersource/Flow", "postman/collection-dir/forte/Flow", "postman/collection-dir/globalpay/Flow", "postman/collection-dir/hyperswitch/API", "postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment", "postman/collection-dir/hyperswitch/PaymentConnectors/List", "postman/collection-dir/hyperswitch/PaymentConnectors/Payment", "postman/collection-dir/hyperswitch/QuickStart/Payment", "postman/collection-dir/mollie/Flow", "postman/collection-dir/multisafepay/Flow", "postman/collection-dir/nexinets/Flow", "postman/collection-dir/nmi/Flow", "postman/collection-dir/nuvei/Flow", "postman/collection-dir/payme/Flow", "postman/collection-dir/paypal/Flow", "postman/collection-dir/powertranz/Flow", "postman/collection-dir/prophetpay/Flow", "postman/collection-dir/rapyd/Flow", "postman/collection-dir/shift4/Flow", "postman/collection-dir/stripe/API", "postman/collection-dir/stripe/Flow", "postman/collection-dir/stripe/PaymentConnectors/List", "postman/collection-dir/stripe/PaymentConnectors/Payment", "postman/collection-dir/stripe/QuickStart/Payment", "postman/collection-dir/trustpay/Flow", "postman/collection-dir/volt/Flow", "postman/collection-dir/wise/Flow", "postman/collection-dir/worldline/Flow", "postman/collection-dir/zen/Flow", "postman/collection-dir/zsl/Flow" ]
juspay/hyperswitch
juspay__hyperswitch-7699
Bug: web-docker pull from docker hub
diff --git a/docker-compose.yml b/docker-compose.yml index ea1ebb3dd12..cb39b23b133 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -149,15 +149,14 @@ services: ### Web Client hyperswitch-web: + image: docker.juspay.io/juspaydotin/hyperswitch-web:latest + pull_policy: always ports: - "9050:9050" - "9060:9060" - "5252:5252" networks: - router_net - build: - context: ./docker - dockerfile: web.Dockerfile depends_on: hyperswitch-server: condition: service_healthy
2025-04-02T09:57:03Z
## Description Docker pull from latest stable tag ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Web Docker Image was not working properly <img width="1043" alt="Screenshot 2025-04-02 at 3 40 52 PM" src="https://github.com/user-attachments/assets/514b49c8-6a63-4c5b-934b-9d2f0709fc5f" /> Now with this fix its working #
cfe226943dc5b473e88b7830c54ac73a943ba04b
Via locally running Docker Image
[ "docker-compose.yml" ]
juspay/hyperswitch
juspay__hyperswitch-7696
Bug: Modify API doc Auth for Profile - Delete Need to update the API doc to display Admin API Key instead of API key for Profile - Delete.
diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs index 2b72375f988..e2dfffa2d1f 100644 --- a/crates/openapi/src/routes/profile.rs +++ b/crates/openapi/src/routes/profile.rs @@ -108,7 +108,7 @@ pub async fn profile_retrieve() {} ), tag = "Profile", operation_id = "Delete the Profile", - security(("api_key" = [])) + security(("admin_api_key" = [])) )] pub async fn profile_delete() {}
2025-04-02T09:16:22Z
## Description <!-- Describe your changes in detail --> Need to update the API doc to display Admin API Key instead of API key for Profile - Delete. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Correct Information to be displayed in the API docs. #
cfe226943dc5b473e88b7830c54ac73a943ba04b
Cannot be tested.
[ "crates/openapi/src/routes/profile.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7669
Bug: Update API Collection Docs Need to update the API Collection present on the website, to use API Key instead of AdminAPI Key. cc: @gorakhnathy7
diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs index 2b72375f988..e2dfffa2d1f 100644 --- a/crates/openapi/src/routes/profile.rs +++ b/crates/openapi/src/routes/profile.rs @@ -108,7 +108,7 @@ pub async fn profile_retrieve() {} ), tag = "Profile", operation_id = "Delete the Profile", - security(("api_key" = [])) + security(("admin_api_key" = [])) )] pub async fn profile_delete() {}
2025-04-02T09:16:22Z
## Description <!-- Describe your changes in detail --> Need to update the API doc to display Admin API Key instead of API key for Profile - Delete. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Correct Information to be displayed in the API docs. #
cfe226943dc5b473e88b7830c54ac73a943ba04b
Cannot be tested.
[ "crates/openapi/src/routes/profile.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7694
Bug: Default value for `forex_enabled` if config is not set Currently, if the `forex_enabled` flag is not present as an ENV, it is leading to deserialization errors. Need to modify it in such a way to assume the default value (false) if the ENV is not present.
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 89f5cbd5b9c..2cd2da30e45 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -1010,25 +1010,28 @@ impl AnalyticsProvider { } #[derive(Clone, Debug, serde::Deserialize)] -#[serde(tag = "source")] -#[serde(rename_all = "lowercase")] +#[serde(tag = "source", rename_all = "lowercase")] pub enum AnalyticsConfig { Sqlx { sqlx: Database, + #[serde(default)] forex_enabled: bool, }, Clickhouse { clickhouse: ClickhouseConfig, + #[serde(default)] forex_enabled: bool, }, CombinedCkh { sqlx: Database, clickhouse: ClickhouseConfig, + #[serde(default)] forex_enabled: bool, }, CombinedSqlx { sqlx: Database, clickhouse: ClickhouseConfig, + #[serde(default)] forex_enabled: bool, }, }
2025-04-02T09:12:31Z
## Description <!-- Describe your changes in detail --> Currently, if the `forex_enabled` feature flag is not present as an ENV, it is leading to deserialization errors. Modified it in such a way to assume the default value (false) if the ENV is not present. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fix deserialization errors for analytics #
cfe226943dc5b473e88b7830c54ac73a943ba04b
Removed the `forex_enabled` feature flag from local envs, and replicated the error <img width="806" alt="Screenshot 2025-04-02 at 2 34 43 PM" src="https://github.com/user-attachments/assets/b275cc79-1fad-4ee7-81a5-acaf780e771c" /> Need to remove the env `forex_enabled` during deployment, and then test out the analytics section.. Tested on local, by removing the `forex_enabled` env and checking the analytics API calls, worked as expected <img width="638" alt="image" src="https://github.com/user-attachments/assets/56ba5d51-ff1c-4d42-8401-ea00e7bc6d22" /> Curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2RlMDFhYWYtOWVkMi00YTY5LTg3YWItNWU1YmI2ZWFiNGQ5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQyMjEyMzQxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Mjk4MDgyOCwib3JnX2lkIjoib3JnX3pMQmRNTnpLaDZrNmhiT2tockdJIiwicHJvZmlsZV9pZCI6InByb19LWnhHZ21rUHFkMldQdXBFa2psWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.aD185AZEOcIjHnLnZZ9GJ2ujSHIdRPbPtrYhzNo0V4M' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-03-01T18:30:00Z", "endTime": "2025-03-31T09:22:00Z" }, "source": "BATCH", "metrics": [ "payment_processed_amount" ], "timeSeries": { "granularity": "G_ONEDAY" }, "delta": true } ]' ```
[ "crates/analytics/src/lib.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7691
Bug: refactor(cypress): BOA testcases are failing due to failed assertions of Refunds and Connector Agnostic
2025-04-02T08:19:33Z
## Description <!-- Describe your changes in detail --> Refunds for Manually Captured No3DS Payments and Connector Agnostic NTID Test Cases in Cypress were failing for `Bank of America` Payment Processor. - The Refunds for Manually Captured No3DS Payments were staying in `pending` status instead of `succeeded` with `error_message` as `null` and on RSync, it yields `errorInformation.message` as `"Request was processed successfully."` with status still as `pending`. - The `00024-ConnectorAgnosticNTID` was failing with the error message in the response as `"No eligible connector was found for the current payment method configuration"` because it did not support Connector Agnostic. So, made the following changes:- - Mapped the status accordingly. Changed `succeeded` to `pending` for No3DS Manual Payment Refunds. - Excluded `bankofamerica` from the Connectors which are allowing Connector Agnostic. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Bank of America Cypress Test Cases were failing. #
961c875ecc225c924160448f01bf38a8e5a4ca03
<img width="718" alt="image" src="https://github.com/user-attachments/assets/440774ed-944e-4a10-8447-4fa75e05e915" /> _(Tested on Integ Environment)_
[]
juspay/hyperswitch
juspay__hyperswitch-7685
Bug: Missing next steps after deployment setup on Readme Next steps after deployment setup on Readme are missing
diff --git a/README.md b/README.md index 5b5518d31fc..72ac7e0e3a7 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,13 @@ Check out the [local setup guide][local-setup-guide] for a more details on setti Attaching to hyperswitch-control-center-1, hyperswitch-server-1, hyperswitch-web-1, migration_runner-1, pg-1, redis-standalone-1 ``` +You've now setup Hyperswitch in your local machine. In order to verify that the server is up and running hit the health endpoint: +```shell +curl --head --request GET 'http://localhost:8080/health' +``` +The expected response here is a `200 OK` status code. This indicates that the server and all of its dependent services are functioning correctly. +Now, you can access the Control Center in your browser at `http://localhost:9000`. +The next step is to configure a connector with the Hyperswitch Control Center and try a payment. ### 2. Deployment on cloud
2025-04-01T21:15:14Z
## Description <!-- Describe your changes in detail --> Updated next steps after deployment setup on Readme ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Updated next steps after deployment setup on Readme closes : #7685 7685 #
446716ee20440c1937c1b988b2ea3ce58d23089c
[ "README.md" ]
juspay/hyperswitch
juspay__hyperswitch-7679
Bug: Modify Openspec API for updating API Reference Doc with the updated auth Update the Openspec API, to use the latest API Key auth for profiles and mca routes.
diff --git a/crates/openapi/src/routes/merchant_connector_account.rs b/crates/openapi/src/routes/merchant_connector_account.rs index 372f8688a26..9a205abb1a2 100644 --- a/crates/openapi/src/routes/merchant_connector_account.rs +++ b/crates/openapi/src/routes/merchant_connector_account.rs @@ -57,7 +57,7 @@ ), tag = "Merchant Connector Account", operation_id = "Create a Merchant Connector", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn connector_create() {} @@ -142,7 +142,7 @@ pub async fn connector_create() {} ), tag = "Merchant Connector Account", operation_id = "Retrieve a Merchant Connector", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn connector_retrieve() {} @@ -183,7 +183,7 @@ pub async fn connector_retrieve() {} ), tag = "Merchant Connector Account", operation_id = "List all Merchant Connectors", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn connector_list() {} @@ -231,7 +231,7 @@ pub async fn connector_list() {} ), tag = "Merchant Connector Account", operation_id = "Update a Merchant Connector", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn connector_update() {} diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs index cc484aa3f95..2b72375f988 100644 --- a/crates/openapi/src/routes/profile.rs +++ b/crates/openapi/src/routes/profile.rs @@ -33,7 +33,7 @@ ), tag = "Profile", operation_id = "Create A Profile", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn profile_create() {} @@ -65,7 +65,7 @@ pub async fn profile_create() {} ), tag = "Profile", operation_id = "Update a Profile", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn profile_update() {} @@ -86,7 +86,7 @@ pub async fn profile_update() {} ), tag = "Profile", operation_id = "Retrieve a Profile", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn profile_retrieve() {}
2025-04-01T11:40:04Z
## Description <!-- Describe your changes in detail --> Modified the authentication for profile and mca routes to use API Key instead of Admin API Key. This PR has the corresponding OpenAPI spec changes. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
1100dcc6053990cf832c00cf29db700d77f78480
Cannot test Corresponding code changes are there in this PR: [https://github.com/juspay/hyperswitch/pull/7656](https://github.com/juspay/hyperswitch/pull/7656)
[ "crates/openapi/src/routes/merchant_connector_account.rs", "crates/openapi/src/routes/profile.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7673
Bug: refactor(ci): map respective error messages for `Stripe` `Sofort` Bank Transfers The `Stripe` payment processor has deprecated the `Sofort` Bank Transfer Payment Method. Map the relevant error codes and messages in the cypress test cases.
2025-04-01T07:41:28Z
## Description <!-- Describe your changes in detail --> Mapping `status`, `error_code`, and `error_message` for `Stripe` Payment Processor `Sofort` Bank Transfer Payment Method as `Sofort` has been deprecated by `Stripe`. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> `Stripe` Payment Processor has deprecated `Sofort` Bank Transfer Payment Method. #
c6078c5827907ee4315c533b5f729607c1c4e3cd
![image](https://github.com/user-attachments/assets/bc3de0de-13ad-4609-85ae-84b67bb2473f)
[]
juspay/hyperswitch
juspay__hyperswitch-7715
Bug: refactor(NMI,PAYONE) , Move files from router to hyperswitch connectors Move the connectors from routers to hyperswitch_connectors
diff --git a/Cargo.lock b/Cargo.lock index ea92a99a2c3..068bb1cecb7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3870,6 +3870,7 @@ dependencies = [ "serde", "serde_json", "serde_qs", + "serde_repr", "serde_urlencoded", "serde_with", "sha1", @@ -6535,7 +6536,6 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_qs", - "serde_repr", "serde_urlencoded", "serde_with", "serial_test", diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml index 0d981bf35ba..b8b74ae272a 100644 --- a/crates/hyperswitch_connectors/Cargo.toml +++ b/crates/hyperswitch_connectors/Cargo.toml @@ -36,6 +36,7 @@ roxmltree = "0.19.0" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_qs = "0.12.0" +serde_repr = "0.1.19" serde_urlencoded = "0.7.1" serde_with = "3.7.0" sha1 = { version = "0.10.6" } diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 93db897bfaf..80e1253940b 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -47,6 +47,7 @@ pub mod moneris; pub mod multisafepay; pub mod nexinets; pub mod nexixpay; +pub mod nmi; pub mod nomupay; pub mod noon; pub mod novalnet; @@ -56,6 +57,7 @@ pub mod opennode; pub mod paybox; pub mod payeezy; pub mod payme; +pub mod payone; pub mod paypal; pub mod paystack; pub mod payu; @@ -66,6 +68,7 @@ pub mod rapyd; pub mod razorpay; pub mod recurly; pub mod redsys; +pub mod riskified; pub mod shift4; pub mod square; pub mod stax; @@ -82,7 +85,6 @@ pub mod worldpay; pub mod xendit; pub mod zen; pub mod zsl; - pub use self::{ aci::Aci, adyen::Adyen, airwallex::Airwallex, amazonpay::Amazonpay, authorizedotnet::Authorizedotnet, bambora::Bambora, bamboraapac::Bamboraapac, @@ -96,13 +98,13 @@ pub use self::{ helcim::Helcim, hipay::Hipay, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay, - nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, noon::Noon, novalnet::Novalnet, - nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, - paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, - prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, - shift4::Shift4, square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, - thunes::Thunes, trustpay::Trustpay, tsys::Tsys, - unified_authentication_service::UnifiedAuthenticationService, volt::Volt, - wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, - zsl::Zsl, + nexinets::Nexinets, nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, + novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, + payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, + placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, + razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, + square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, thunes::Thunes, + trustpay::Trustpay, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, + volt::Volt, wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, + zen::Zen, zsl::Zsl, }; diff --git a/crates/router/src/connector/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rs similarity index 51% rename from crates/router/src/connector/nmi.rs rename to crates/hyperswitch_connectors/src/connectors/nmi.rs index 575f4b136eb..b2037c45256 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs @@ -1,31 +1,54 @@ pub mod transformers; - +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::{enums, CallConnectorAction, PaymentAction}; use common_utils::{ crypto, + errors::CustomResult, ext_traits::ByteSliceExt, - request::RequestContent, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; -use diesel_models::enums; use error_stack::{report, ResultExt}; -use regex::Regex; -use transformers as nmi; - -use super::utils as connector_utils; -use crate::{ - configs::settings, - core::{ - errors::{self, CustomResult}, - payments, +use hyperswitch_domain_models::{ + router_data::{AccessToken, ErrorResponse, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, CompleteAuthorize, Execute, PSync, PaymentMethodToken, + PreProcessing, RSync, Session, SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, + PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, + PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, + ConnectorSpecifications, ConnectorValidation, + }, + configs::Connectors, + errors::ConnectorError, events::connector_api_logs::ConnectorEvent, - services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - transformers::ForeignFrom, - ErrorResponse, + PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, + PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, + RefundSyncType, Response, }, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::Maskable; +use regex::Regex; +use transformers as nmi; + +use crate::{ + types::ResponseRouterData, + utils::{construct_not_supported_error_report, convert_amount, get_header_key_value}, }; #[derive(Clone)] @@ -60,9 +83,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>)>, ConnectorError> { Ok(vec![( "Content-Type".to_string(), "application/x-www-form-urlencoded".to_string().into(), @@ -79,19 +102,19 @@ impl ConnectorCommon for Nmi { api::CurrencyUnit::Base } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.nmi.base_url.as_ref() } fn build_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: nmi::StandardResponse = res .response .parse_struct("StandardResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -116,94 +139,78 @@ impl ConnectorValidation for Nmi { capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { + ) -> CustomResult<(), ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + construct_not_supported_error_report(capture_method, self.id()), ), } } fn validate_psync_reference_id( &self, - _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _data: &PaymentsSyncData, _is_three_ds: bool, _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, - ) -> CustomResult<(), errors::ConnectorError> { + ) -> CustomResult<(), ConnectorError> { // in case we dont have transaction id, we can make psync using attempt id Ok(()) } } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Nmi -{ -} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Nmi { } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Nmi -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nmi {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Nmi -{ +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nmi {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::SetupMandateRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::SetupMandateRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::SetupMandateRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &SetupMandateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiPaymentsRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - _req: &types::SetupMandateRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("Setup Mandate flow for Nmi".to_string()).into()) + _req: &SetupMandateRouterData, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Err(ConnectorError::NotImplemented("Setup Mandate flow for Nmi".to_string()).into()) // Ok(Some( - // services::RequestBuilder::new() - // .method(services::Method::Post) - // .url(&types::SetupMandateType::get_url(self, req, connectors)?) - // .headers(types::SetupMandateType::get_headers(self, req, connectors)?) - // .set_body(types::SetupMandateType::get_request_body( + // RequestBuilder::new() + // .method(Method::Post) + // .url(&SetupMandateType::get_url(self, req, connectors)?) + // .headers(SetupMandateType::get_headers(self, req, connectors)?) + // .set_body(SetupMandateType::get_request_body( // self, req, connectors, // )?) // .build(), @@ -212,15 +219,15 @@ impl fn handle_response( &self, - data: &types::SetupMandateRouterData, + data: &SetupMandateRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<SetupMandateRouterData, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(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, @@ -229,27 +236,21 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentsPreProcessing for Nmi {} -impl - ConnectorIntegration< - api::PreProcessing, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, - > for Nmi -{ +impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::PaymentsPreProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsPreProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -259,37 +260,35 @@ impl fn get_url( &self, - _req: &types::PaymentsPreProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsPreProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsPreProcessingRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PaymentsPreProcessingRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiVaultRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsPreProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsPreProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { let req = Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .attach_default_headers() - .headers(types::PaymentsPreProcessingType::get_headers( - self, req, connectors, - )?) - .url(&types::PaymentsPreProcessingType::get_url( + .headers(PaymentsPreProcessingType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsPreProcessingType::get_request_body( + .url(&PaymentsPreProcessingType::get_url(self, req, connectors)?) + .set_body(PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), @@ -299,15 +298,15 @@ impl fn handle_response( &self, - data: &types::PaymentsPreProcessingRouterData, + data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsPreProcessingRouterData, ConnectorError> { let response: nmi::NmiVaultResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(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, @@ -316,38 +315,36 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Nmi -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nmi { 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>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -359,19 +356,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>, 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(), @@ -380,15 +373,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(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, @@ -397,27 +390,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentsCompleteAuthorize for Nmi {} -impl - ConnectorIntegration< - api::CompleteAuthorize, - types::CompleteAuthorizeData, - types::PaymentsResponseData, - > for Nmi -{ +impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -425,17 +412,17 @@ impl } fn get_url( &self, - _req: &types::PaymentsCompleteAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsCompleteAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -446,20 +433,20 @@ impl } fn build_request( &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCompleteAuthorizeType::get_url( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() - .headers(types::PaymentsCompleteAuthorizeType::get_headers( + .headers(PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + .set_body(PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -468,15 +455,15 @@ impl fn handle_response( &self, - data: &types::PaymentsCompleteAuthorizeRouterData, + data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, ConnectorError> { let response: nmi::NmiCompleteResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(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, @@ -485,69 +472,65 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Nmi -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nmi { 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>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/query.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiSyncRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) - .set_body(types::PaymentsSyncType::get_request_body( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) + .set_body(PaymentsSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, ConnectorError> { let response = nmi::SyncResponse::try_from(res.response.to_vec())?; event_builder.map(|i| i.set_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -556,38 +539,36 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Nmi -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nmi { 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>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, @@ -599,17 +580,15 @@ 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>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) - .headers(types::PaymentsCaptureType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsCaptureType::get_request_body( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCaptureType::get_url(self, req, connectors)?) + .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) + .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), @@ -618,15 +597,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(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, @@ -635,69 +614,65 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Nmi -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nmi { 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>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiCancelRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, 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)?) - .set_body(types::PaymentsVoidType::get_request_body( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsVoidType::get_url(self, req, connectors)?) + .headers(PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsCancelRouterData, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(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, @@ -706,36 +681,36 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Nmi { +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nmi { 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>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let refund_amount = connector_utils::convert_amount( + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let refund_amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, @@ -748,34 +723,30 @@ 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> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers( - self, req, connectors, - )?) - .set_body(types::RefundExecuteType::get_request_body( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&RefundExecuteType::get_url(self, req, connectors)?) + .headers(RefundExecuteType::get_headers(self, req, connectors)?) + .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(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, @@ -784,68 +755,66 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Nmi { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nmi { fn get_headers( &self, - req: &types::RefundsRouterData<api::RSync>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<RSync>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::RefundsRouterData<api::RSync>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &RefundsRouterData<RSync>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/query.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::RSync>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &RefundsRouterData<RSync>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiSyncRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::RefundsRouterData<api::RSync>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundsRouterData<RSync>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .set_body(types::RefundSyncType::get_request_body( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&RefundSyncType::get_url(self, req, connectors)?) + .headers(RefundSyncType::get_headers(self, req, connectors)?) + .set_body(RefundSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::RefundsRouterData<api::RSync>, + data: &RefundsRouterData<RSync>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<RefundsRouterData<RSync>, ConnectorError> { let response = nmi::NmiRefundSyncResponse::try_from(res.response.to_vec())?; 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, @@ -854,81 +823,79 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] -impl api::IncomingWebhook for Nmi { +impl IncomingWebhook for Nmi { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } 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 sig_header = - connector_utils::get_header_key_value("webhook-signature", request.headers)?; + ) -> CustomResult<Vec<u8>, ConnectorError> { + let sig_header = get_header_key_value("webhook-signature", request.headers)?; let regex_pattern = r"t=(.*),s=(.*)"; if let Some(captures) = Regex::new(regex_pattern) - .change_context(errors::ConnectorError::WebhookSignatureNotFound)? + .change_context(ConnectorError::WebhookSignatureNotFound)? .captures(sig_header) { let signature = captures .get(1) - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)? + .ok_or(ConnectorError::WebhookSignatureNotFound)? .as_str(); return Ok(signature.as_bytes().to_vec()); } - Err(report!(errors::ConnectorError::WebhookSignatureNotFound)) + Err(report!(ConnectorError::WebhookSignatureNotFound)) } 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> { - let sig_header = - connector_utils::get_header_key_value("webhook-signature", request.headers)?; + ) -> CustomResult<Vec<u8>, ConnectorError> { + let sig_header = get_header_key_value("webhook-signature", request.headers)?; let regex_pattern = r"t=(.*),s=(.*)"; if let Some(captures) = Regex::new(regex_pattern) - .change_context(errors::ConnectorError::WebhookSignatureNotFound)? + .change_context(ConnectorError::WebhookSignatureNotFound)? .captures(sig_header) { let nonce = captures .get(0) - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)? + .ok_or(ConnectorError::WebhookSignatureNotFound)? .as_str(); let message = format!("{}.{}", nonce, String::from_utf8_lossy(request.body)); return Ok(message.into_bytes()); } - Err(report!(errors::ConnectorError::WebhookSignatureNotFound)) + Err(report!(ConnectorError::WebhookSignatureNotFound)) } fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { let reference_body: nmi::NmiWebhookObjectReference = request .body .parse_struct("nmi NmiWebhookObjectReference") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; let object_reference_id = match reference_body.event_body.action.action_type { nmi::NmiActionType::Sale => api_models::webhooks::ObjectReferenceId::PaymentId( @@ -954,7 +921,7 @@ impl api::IncomingWebhook for Nmi { nmi::NmiActionType::Refund => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::RefundId(reference_body.event_body.order_id), ), - _ => Err(errors::ConnectorError::WebhooksNotImplemented)?, + _ => Err(ConnectorError::WebhooksNotImplemented)?, }; Ok(object_reference_id) @@ -962,26 +929,26 @@ impl api::IncomingWebhook for Nmi { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { let event_type_body: nmi::NmiWebhookEventBody = request .body .parse_struct("nmi NmiWebhookEventType") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; - Ok(api::IncomingWebhookEvent::foreign_from( + Ok(transformers::get_nmi_webhook_event( event_type_body.event_type, )) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { let webhook_body: nmi::NmiWebhookBody = request .body .parse_struct("nmi NmiWebhookBody") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; match webhook_body.event_body.action.action_type { nmi::NmiActionType::Sale @@ -996,33 +963,32 @@ impl api::IncomingWebhook for Nmi { } } -impl services::ConnectorRedirectResponse for Nmi { +impl ConnectorRedirectResponse for Nmi { fn get_flow_type( &self, _query_params: &str, json_payload: Option<serde_json::Value>, - action: services::PaymentAction, - ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + action: PaymentAction, + ) -> CustomResult<CallConnectorAction, ConnectorError> { match action { - services::PaymentAction::CompleteAuthorize => { - let payload_data = - json_payload.ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "connector_metadata", - })?; + PaymentAction::CompleteAuthorize => { + let payload_data = json_payload.ok_or(ConnectorError::MissingRequiredField { + field_name: "connector_metadata", + })?; let redirect_res: nmi::NmiRedirectResponse = serde_json::from_value(payload_data) .change_context( - errors::ConnectorError::MissingConnectorRedirectionPayload { + ConnectorError::MissingConnectorRedirectionPayload { field_name: "redirect_res", }, )?; match redirect_res { transformers::NmiRedirectResponse::NmiRedirectResponseData(_) => { - Ok(payments::CallConnectorAction::Trigger) + Ok(CallConnectorAction::Trigger) } transformers::NmiRedirectResponse::NmiErrorResponseData(error_res) => { - Ok(payments::CallConnectorAction::StatusUpdate { + Ok(CallConnectorAction::StatusUpdate { status: enums::AttemptStatus::Failure, error_code: Some(error_res.code), error_message: Some(error_res.message), @@ -1030,9 +996,8 @@ impl services::ConnectorRedirectResponse for Nmi { } } } - services::PaymentAction::PSync - | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { - Ok(payments::CallConnectorAction::Trigger) + PaymentAction::PSync | PaymentAction::PaymentAuthenticateCompleteAuthorize => { + Ok(CallConnectorAction::Trigger) } } } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs similarity index 62% rename from crates/router/src/connector/nmi/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs index da1231d1d8c..c8dbea3844d 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs @@ -1,22 +1,43 @@ -use api_models::webhooks; +use api_models::webhooks::IncomingWebhookEvent; use cards::CardNumber; -use common_enums::CountryAlpha2; +use common_enums::{ + AttemptStatus, AuthenticationType, CaptureMethod, CountryAlpha2, Currency, RefundStatus, +}; use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit}; use error_stack::{report, Report, ResultExt}; +use hyperswitch_domain_models::{ + payment_method_data::{ + ApplePayWalletData, Card, GooglePayWalletData, PaymentMethodData, WalletData, + }, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + Authorize, Capture, CompleteAuthorize, Execute, PreProcessing, RSync, SetupMandate, Void, + }, + router_request_types::{ + CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, + PaymentsPreProcessingData, ResponseId, + }, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, + }, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{ - self, AddressDetailsData, PaymentsAuthorizeRequestData, - PaymentsCompleteAuthorizeRequestData, RouterData, + types::{PaymentsResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, + utils::{ + get_unimplemented_payment_method_error_message, to_currency_base_unit_asf64, + AddressDetailsData as _, CardData as _, PaymentsAuthorizeRequestData, + PaymentsCompleteAuthorizeRequestData as _, RouterData as _, }, - core::errors, - services, - types::{self, api, domain, storage::enums, transformers::ForeignFrom, ConnectorAuthType}, }; -type Error = Report<errors::ConnectorError>; +type Error = Report<ConnectorError>; #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] @@ -46,7 +67,7 @@ impl TryFrom<&ConnectorAuthType> for NmiAuthType { api_key: api_key.to_owned(), public_key: Some(key1.to_owned()), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } @@ -90,9 +111,9 @@ pub enum CustomerAction { UpdateCustomer, } -impl TryFrom<&types::PaymentsPreProcessingRouterData> for NmiVaultRequest { +impl TryFrom<&PaymentsPreProcessingRouterData> for NmiVaultRequest { type Error = Error; - fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; let (ccnumber, ccexp, cvv) = get_card_details(item.request.payment_method_data.clone())?; let billing_details = item.get_billing_address()?; @@ -120,21 +141,18 @@ impl TryFrom<&types::PaymentsPreProcessingRouterData> for NmiVaultRequest { } fn get_card_details( - payment_method_data: Option<domain::PaymentMethodData>, -) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), errors::ConnectorError> { + payment_method_data: Option<PaymentMethodData>, +) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), ConnectorError> { match payment_method_data { - Some(domain::PaymentMethodData::Card(ref card_details)) => Ok(( + Some(PaymentMethodData::Card(ref card_details)) => Ok(( card_details.card_number.clone(), - utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( - card_details, - "".to_string(), - )?, + card_details.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?, card_details.card_cvc.clone(), )), - _ => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Nmi"), - ) - .into()), + _ => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message("Nmi")) + .into(), + ), } } @@ -149,59 +167,56 @@ pub struct NmiVaultResponse { impl TryFrom< - types::ResponseRouterData< - api::PreProcessing, + ResponseRouterData< + PreProcessing, NmiVaultResponse, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, + PaymentsPreProcessingData, + PaymentsResponseData, >, - > for types::PaymentsPreProcessingRouterData + > for PaymentsPreProcessingRouterData { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::PreProcessing, + item: ResponseRouterData< + PreProcessing, NmiVaultResponse, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, + PaymentsPreProcessingData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.data.connector_auth_type).try_into()?; - let amount_data = - item.data - .request - .amount - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "amount", - })?; + let amount_data = item + .data + .request + .amount + .ok_or(ConnectorError::MissingRequiredField { + field_name: "amount", + })?; let currency_data = item.data .request .currency - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?; let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::NoResponseId, - redirection_data: Box::new(Some(services::RedirectForm::Nmi { - amount: utils::to_currency_base_unit_asf64( - amount_data, - currency_data.to_owned(), - )? - .to_string(), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Box::new(Some(RedirectForm::Nmi { + amount: to_currency_base_unit_asf64(amount_data, currency_data.to_owned())? + .to_string(), currency: currency_data, customer_vault_id: item .response .customer_vault_id - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "customer_vault_id", })? .peek() .to_string(), public_key: auth_type.public_key.ok_or( - errors::ConnectorError::InvalidConnectorConfig { + ConnectorError::InvalidConnectorConfig { config: "public_key", }, )?, @@ -214,10 +229,10 @@ impl incremental_authorization_allowed: None, charges: None, }), - enums::AttemptStatus::AuthenticationPending, + AttemptStatus::AuthenticationPending, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse { + Err(ErrorResponse { code: item.response.response_code, message: item.response.responsetext.to_owned(), reason: Some(item.response.responsetext), @@ -228,7 +243,7 @@ impl network_decline_code: None, network_error_message: None, }), - enums::AttemptStatus::Failure, + AttemptStatus::Failure, ), }; Ok(Self { @@ -285,10 +300,10 @@ pub struct NmiRedirectResponseData { customer_vault_id: Secret<String>, } -impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest { +impl TryFrom<&NmiRouterData<&PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest { type Error = Error; fn try_from( - item: &NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + item: &NmiRouterData<&PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, @@ -302,7 +317,7 @@ impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for Nm .expose(); let three_ds_data: NmiRedirectResponseData = serde_json::from_value(payload_data) - .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload { + .change_context(ConnectorError::MissingConnectorRedirectionPayload { field_name: "three_ds_data", })?; @@ -340,29 +355,27 @@ pub struct NmiCompleteResponse { impl TryFrom< - types::ResponseRouterData< - api::CompleteAuthorize, + ResponseRouterData< + CompleteAuthorize, NmiCompleteResponse, - types::CompleteAuthorizeData, - types::PaymentsResponseData, + CompleteAuthorizeData, + PaymentsResponseData, >, - > for types::PaymentsCompleteAuthorizeRouterData + > for PaymentsCompleteAuthorizeRouterData { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::CompleteAuthorize, + item: ResponseRouterData< + CompleteAuthorize, NmiCompleteResponse, - types::CompleteAuthorizeData, - types::PaymentsResponseData, + CompleteAuthorizeData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transactionid, - ), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.transactionid), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, @@ -371,20 +384,15 @@ impl incremental_authorization_allowed: None, charges: None, }), - if let Some(diesel_models::enums::CaptureMethod::Automatic) = - item.data.request.capture_method - { - enums::AttemptStatus::CaptureInitiated + if let Some(CaptureMethod::Automatic) = item.data.request.capture_method { + AttemptStatus::CaptureInitiated } else { - enums::AttemptStatus::Authorizing + AttemptStatus::Authorizing }, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::Failure, + Err(get_nmi_error_response(item.response, item.http_code)), + AttemptStatus::Failure, ), }; Ok(Self { @@ -395,19 +403,17 @@ impl } } -impl ForeignFrom<(NmiCompleteResponse, u16)> for types::ErrorResponse { - fn foreign_from((response, http_code): (NmiCompleteResponse, u16)) -> Self { - Self { - code: response.response_code, - message: response.responsetext.to_owned(), - reason: Some(response.responsetext), - status_code: http_code, - attempt_status: None, - connector_transaction_id: Some(response.transactionid), - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - } +fn get_nmi_error_response(response: NmiCompleteResponse, http_code: u16) -> ErrorResponse { + ErrorResponse { + code: response.response_code, + message: response.responsetext.to_owned(), + reason: Some(response.responsetext), + status_code: http_code, + attempt_status: None, + connector_transaction_id: Some(response.transactionid), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, } } @@ -417,7 +423,7 @@ pub struct NmiPaymentsRequest { transaction_type: TransactionType, amount: FloatMajorUnit, security_key: Secret<String>, - currency: enums::Currency, + currency: Currency, #[serde(flatten)] payment_method: PaymentMethod, #[serde(flatten)] @@ -488,11 +494,9 @@ pub struct ApplePayData { applepay_payment_data: Secret<String>, } -impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPaymentsRequest { +impl TryFrom<&NmiRouterData<&PaymentsAuthorizeRouterData>> for NmiPaymentsRequest { type Error = Error; - fn try_from( - item: &NmiRouterData<&types::PaymentsAuthorizeRouterData>, - ) -> Result<Self, Self::Error> { + fn try_from(item: &NmiRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, false => TransactionType::Auth, @@ -521,102 +525,85 @@ impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPayment } } -impl - TryFrom<( - &domain::PaymentMethodData, - Option<&types::PaymentsAuthorizeRouterData>, - )> for PaymentMethod -{ +impl TryFrom<(&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>)> for PaymentMethod { type Error = Error; fn try_from( - item: ( - &domain::PaymentMethodData, - Option<&types::PaymentsAuthorizeRouterData>, - ), + item: (&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>), ) -> Result<Self, Self::Error> { let (payment_method_data, router_data) = item; match payment_method_data { - domain::PaymentMethodData::Card(ref card) => match router_data { + PaymentMethodData::Card(ref card) => match router_data { Some(data) => match data.auth_type { - common_enums::AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?), - common_enums::AuthenticationType::ThreeDs => { - Ok(Self::try_from((card, &data.request))?) - } + AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?), + AuthenticationType::ThreeDs => Ok(Self::try_from((card, &data.request))?), }, None => Ok(Self::try_from(card)?), }, - domain::PaymentMethodData::Wallet(ref wallet_type) => match wallet_type { - domain::WalletData::GooglePay(ref googlepay_data) => Ok(Self::from(googlepay_data)), - domain::WalletData::ApplePay(ref applepay_data) => Ok(Self::from(applepay_data)), - domain::WalletData::AliPayQr(_) - | domain::WalletData::AliPayRedirect(_) - | domain::WalletData::AliPayHkRedirect(_) - | domain::WalletData::AmazonPayRedirect(_) - | domain::WalletData::MomoRedirect(_) - | domain::WalletData::KakaoPayRedirect(_) - | domain::WalletData::GoPayRedirect(_) - | domain::WalletData::GcashRedirect(_) - | domain::WalletData::ApplePayRedirect(_) - | domain::WalletData::ApplePayThirdPartySdk(_) - | domain::WalletData::DanaRedirect {} - | domain::WalletData::GooglePayRedirect(_) - | domain::WalletData::GooglePayThirdPartySdk(_) - | domain::WalletData::MbWayRedirect(_) - | domain::WalletData::MobilePayRedirect(_) - | domain::WalletData::PaypalRedirect(_) - | domain::WalletData::PaypalSdk(_) - | domain::WalletData::Paze(_) - | domain::WalletData::SamsungPay(_) - | domain::WalletData::TwintRedirect {} - | domain::WalletData::VippsRedirect {} - | domain::WalletData::TouchNGoRedirect(_) - | domain::WalletData::WeChatPayRedirect(_) - | domain::WalletData::WeChatPayQr(_) - | domain::WalletData::CashappQr(_) - | domain::WalletData::SwishQr(_) - | domain::WalletData::Mifinity(_) => { - Err(report!(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("nmi"), - ))) - } + PaymentMethodData::Wallet(ref wallet_type) => match wallet_type { + WalletData::GooglePay(ref googlepay_data) => Ok(Self::from(googlepay_data)), + WalletData::ApplePay(ref applepay_data) => Ok(Self::from(applepay_data)), + WalletData::AliPayQr(_) + | WalletData::AliPayRedirect(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::AmazonPayRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::MobilePayRedirect(_) + | WalletData::PaypalRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::Paze(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::WeChatPayQr(_) + | WalletData::CashappQr(_) + | WalletData::SwishQr(_) + | WalletData::Mifinity(_) => Err(report!(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("nmi"), + ))), }, - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::MobilePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) - | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("nmi"), - ) - .into()) - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "nmi", + )) + .into(), + ), } } } -impl TryFrom<(&domain::payments::Card, &types::PaymentsAuthorizeData)> for PaymentMethod { +impl TryFrom<(&Card, &PaymentsAuthorizeData)> for PaymentMethod { type Error = Error; - fn try_from( - val: (&domain::payments::Card, &types::PaymentsAuthorizeData), - ) -> Result<Self, Self::Error> { + fn try_from(val: (&Card, &PaymentsAuthorizeData)) -> Result<Self, Self::Error> { let (card_data, item) = val; let auth_data = &item.get_authentication_data()?; - let ccexp = utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( - card_data, - "".to_string(), - )?; + let ccexp = card_data.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?; let card_3ds_details = CardThreeDsData { ccnumber: card_data.card_number.clone(), @@ -640,13 +627,10 @@ impl TryFrom<(&domain::payments::Card, &types::PaymentsAuthorizeData)> for Payme } } -impl TryFrom<&domain::payments::Card> for PaymentMethod { +impl TryFrom<&Card> for PaymentMethod { type Error = Error; - fn try_from(card: &domain::payments::Card) -> Result<Self, Self::Error> { - let ccexp = utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( - card, - "".to_string(), - )?; + fn try_from(card: &Card) -> Result<Self, Self::Error> { + let ccexp = card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?; let card = CardData { ccnumber: card.card_number.clone(), ccexp, @@ -656,8 +640,8 @@ impl TryFrom<&domain::payments::Card> for PaymentMethod { } } -impl From<&domain::GooglePayWalletData> for PaymentMethod { - fn from(wallet_data: &domain::GooglePayWalletData) -> Self { +impl From<&GooglePayWalletData> for PaymentMethod { + fn from(wallet_data: &GooglePayWalletData) -> Self { let gpay_data = GooglePayData { googlepay_payment_data: Secret::new(wallet_data.tokenization_data.token.clone()), }; @@ -665,8 +649,8 @@ impl From<&domain::GooglePayWalletData> for PaymentMethod { } } -impl From<&domain::ApplePayWalletData> for PaymentMethod { - fn from(wallet_data: &domain::ApplePayWalletData) -> Self { +impl From<&ApplePayWalletData> for PaymentMethod { + fn from(wallet_data: &ApplePayWalletData) -> Self { let apple_pay_data = ApplePayData { applepay_payment_data: Secret::new(wallet_data.payment_data.clone()), }; @@ -674,9 +658,9 @@ impl From<&domain::ApplePayWalletData> for PaymentMethod { } } -impl TryFrom<&types::SetupMandateRouterData> for NmiPaymentsRequest { +impl TryFrom<&SetupMandateRouterData> for NmiPaymentsRequest { type Error = Error; - fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; let payment_method = PaymentMethod::try_from((&item.request.payment_method_data, None))?; Ok(Self { @@ -697,9 +681,9 @@ pub struct NmiSyncRequest { pub security_key: Secret<String>, } -impl TryFrom<&types::PaymentsSyncRouterData> for NmiSyncRequest { +impl TryFrom<&PaymentsSyncRouterData> for NmiSyncRequest { type Error = Error; - fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { security_key: auth.api_key, @@ -717,11 +701,9 @@ pub struct NmiCaptureRequest { pub amount: Option<FloatMajorUnit>, } -impl TryFrom<&NmiRouterData<&types::PaymentsCaptureRouterData>> for NmiCaptureRequest { +impl TryFrom<&NmiRouterData<&PaymentsCaptureRouterData>> for NmiCaptureRequest { type Error = Error; - fn try_from( - item: &NmiRouterData<&types::PaymentsCaptureRouterData>, - ) -> Result<Self, Self::Error> { + fn try_from(item: &NmiRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { transaction_type: TransactionType::Capture, @@ -734,27 +716,22 @@ impl TryFrom<&NmiRouterData<&types::PaymentsCaptureRouterData>> for NmiCaptureRe impl TryFrom< - types::ResponseRouterData< - api::Capture, - StandardResponse, - types::PaymentsCaptureData, - types::PaymentsResponseData, - >, - > for types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + ResponseRouterData<Capture, StandardResponse, PaymentsCaptureData, PaymentsResponseData>, + > for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::Capture, + item: ResponseRouterData< + Capture, StandardResponse, - types::PaymentsCaptureData, - types::PaymentsResponseData, + PaymentsCaptureData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.to_owned(), ), redirection_data: Box::new(None), @@ -765,14 +742,11 @@ impl incremental_authorization_allowed: None, charges: None, }), - enums::AttemptStatus::CaptureInitiated, + AttemptStatus::CaptureInitiated, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::CaptureFailed, + Err(get_standard_error_response(item.response, item.http_code)), + AttemptStatus::CaptureFailed, ), }; Ok(Self { @@ -803,14 +777,14 @@ pub enum NmiVoidReason { PosTimeout, } -impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest { +impl TryFrom<&PaymentsCancelRouterData> for NmiCancelRequest { type Error = Error; - fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; match &item.request.cancellation_reason { Some(cancellation_reason) => { let void_reason: NmiVoidReason = serde_json::from_str(&format!("\"{}\"", cancellation_reason)) - .map_err(|_| errors::ConnectorError::NotSupported { + .map_err(|_| ConnectorError::NotSupported { message: format!("Json deserialise error: unknown variant `{}` expected to be one of `fraud`, `user_cancel`, `icc_rejected`, `icc_card_removed`, `icc_no_confirmation`, `pos_timeout`. This cancellation_reason", cancellation_reason), connector: "nmi" })?; @@ -821,7 +795,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest { void_reason, }) } - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "cancellation_reason", } .into()), @@ -851,29 +825,17 @@ pub struct StandardResponse { pub response_code: String, } -impl<T> - TryFrom< - types::ResponseRouterData< - api::SetupMandate, - StandardResponse, - T, - types::PaymentsResponseData, - >, - > for types::RouterData<api::SetupMandate, T, types::PaymentsResponseData> +impl<T> TryFrom<ResponseRouterData<SetupMandate, StandardResponse, T, PaymentsResponseData>> + for RouterData<SetupMandate, T, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::SetupMandate, - StandardResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<SetupMandate, StandardResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), @@ -884,14 +846,11 @@ impl<T> incremental_authorization_allowed: None, charges: None, }), - enums::AttemptStatus::Charged, + AttemptStatus::Charged, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::Failure, + Err(get_standard_error_response(item.response, item.http_code)), + AttemptStatus::Failure, ), }; Ok(Self { @@ -901,39 +860,36 @@ impl<T> }) } } - -impl ForeignFrom<(StandardResponse, u16)> for types::ErrorResponse { - fn foreign_from((response, http_code): (StandardResponse, u16)) -> Self { - Self { - code: response.response_code, - message: response.responsetext.to_owned(), - reason: Some(response.responsetext), - status_code: http_code, - attempt_status: None, - connector_transaction_id: Some(response.transactionid), - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - } +fn get_standard_error_response(response: StandardResponse, http_code: u16) -> ErrorResponse { + ErrorResponse { + code: response.response_code, + message: response.responsetext.to_owned(), + reason: Some(response.responsetext), + status_code: http_code, + attempt_status: None, + connector_transaction_id: Some(response.transactionid), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, } } -impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> - for types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> +impl TryFrom<PaymentsResponseRouterData<StandardResponse>> + for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::Authorize, + item: ResponseRouterData< + Authorize, StandardResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), @@ -944,20 +900,15 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> incremental_authorization_allowed: None, charges: None, }), - if let Some(diesel_models::enums::CaptureMethod::Automatic) = - item.data.request.capture_method - { - enums::AttemptStatus::CaptureInitiated + if let Some(CaptureMethod::Automatic) = item.data.request.capture_method { + AttemptStatus::CaptureInitiated } else { - enums::AttemptStatus::Authorized + AttemptStatus::Authorized }, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::Failure, + Err(get_standard_error_response(item.response, item.http_code)), + AttemptStatus::Failure, ), }; Ok(Self { @@ -968,23 +919,17 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> } } -impl<T> - TryFrom<types::ResponseRouterData<api::Void, StandardResponse, T, types::PaymentsResponseData>> - for types::RouterData<api::Void, T, types::PaymentsResponseData> +impl<T> TryFrom<ResponseRouterData<Void, StandardResponse, T, PaymentsResponseData>> + for RouterData<Void, T, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::Void, - StandardResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<Void, StandardResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), @@ -995,14 +940,11 @@ impl<T> incremental_authorization_allowed: None, charges: None, }), - enums::AttemptStatus::VoidInitiated, + AttemptStatus::VoidInitiated, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::VoidFailed, + Err(get_standard_error_response(item.response, item.http_code)), + AttemptStatus::VoidFailed, ), }; Ok(Self { @@ -1026,18 +968,18 @@ pub enum NmiStatus { Unknown, } -impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.transaction { Some(trn) => Ok(Self { - status: enums::AttemptStatus::from(NmiStatus::from(trn.condition)), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(trn.transaction_id), + status: AttemptStatus::from(NmiStatus::from(trn.condition)), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(trn.transaction_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, @@ -1057,10 +999,10 @@ impl TryFrom<Vec<u8>> for SyncResponse { type Error = Error; fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { let query_response = String::from_utf8(bytes) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; query_response .parse_xml::<Self>() - .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .change_context(ConnectorError::ResponseDeserializationFailed) } } @@ -1068,14 +1010,14 @@ impl TryFrom<Vec<u8>> for NmiRefundSyncResponse { type Error = Error; fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { let query_response = String::from_utf8(bytes) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; query_response .parse_xml::<Self>() - .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .change_context(ConnectorError::ResponseDeserializationFailed) } } -impl From<NmiStatus> for enums::AttemptStatus { +impl From<NmiStatus> for AttemptStatus { fn from(item: NmiStatus) -> Self { match item { NmiStatus::Abandoned => Self::AuthenticationFailed, @@ -1099,9 +1041,9 @@ pub struct NmiRefundRequest { amount: FloatMajorUnit, } -impl<F> TryFrom<&NmiRouterData<&types::RefundsRouterData<F>>> for NmiRefundRequest { +impl<F> TryFrom<&NmiRouterData<&RefundsRouterData<F>>> for NmiRefundRequest { type Error = Error; - fn try_from(item: &NmiRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { + fn try_from(item: &NmiRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; Ok(Self { transaction_type: TransactionType::Refund, @@ -1113,16 +1055,14 @@ impl<F> TryFrom<&NmiRouterData<&types::RefundsRouterData<F>>> for NmiRefundReque } } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, StandardResponse>> - for types::RefundsRouterData<api::Execute> -{ +impl TryFrom<RefundsResponseRouterData<Execute, StandardResponse>> for RefundsRouterData<Execute> { type Error = Error; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, StandardResponse>, + item: RefundsResponseRouterData<Execute, StandardResponse>, ) -> Result<Self, Self::Error> { - let refund_status = enums::RefundStatus::from(item.response.response); + let refund_status = RefundStatus::from(item.response.response); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.orderid, refund_status, }), @@ -1131,16 +1071,14 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, StandardResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::Capture, StandardResponse>> - for types::RefundsRouterData<api::Capture> -{ +impl TryFrom<RefundsResponseRouterData<Capture, StandardResponse>> for RefundsRouterData<Capture> { type Error = Error; fn try_from( - item: types::RefundsResponseRouterData<api::Capture, StandardResponse>, + item: RefundsResponseRouterData<Capture, StandardResponse>, ) -> Result<Self, Self::Error> { - let refund_status = enums::RefundStatus::from(item.response.response); + let refund_status = RefundStatus::from(item.response.response); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.transactionid, refund_status, }), @@ -1149,7 +1087,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Capture, StandardResponse>> } } -impl From<Response> for enums::RefundStatus { +impl From<Response> for RefundStatus { fn from(item: Response) -> Self { match item { Response::Approved => Self::Pending, @@ -1158,9 +1096,9 @@ impl From<Response> for enums::RefundStatus { } } -impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest { +impl TryFrom<&RefundSyncRouterData> for NmiSyncRequest { type Error = Error; - fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { @@ -1169,22 +1107,20 @@ impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest { .request .connector_refund_id .clone() - .ok_or(errors::ConnectorError::MissingConnectorRefundID)?, + .ok_or(ConnectorError::MissingConnectorRefundID)?, }) } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>> - for types::RefundsRouterData<api::RSync> -{ - type Error = Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<RSync, NmiRefundSyncResponse>> for RefundsRouterData<RSync> { + type Error = Report<ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>, + item: RefundsResponseRouterData<RSync, NmiRefundSyncResponse>, ) -> Result<Self, Self::Error> { let refund_status = - enums::RefundStatus::from(NmiStatus::from(item.response.transaction.condition)); + RefundStatus::from(NmiStatus::from(item.response.transaction.condition)); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction.order_id, refund_status, }), @@ -1193,7 +1129,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse> } } -impl From<NmiStatus> for enums::RefundStatus { +impl From<NmiStatus> for RefundStatus { fn from(item: NmiStatus) -> Self { match item { NmiStatus::Abandoned @@ -1310,25 +1246,23 @@ pub enum NmiWebhookEventType { CaptureUnknown, } -impl ForeignFrom<NmiWebhookEventType> for webhooks::IncomingWebhookEvent { - fn foreign_from(status: NmiWebhookEventType) -> Self { - match status { - NmiWebhookEventType::SaleSuccess => Self::PaymentIntentSuccess, - NmiWebhookEventType::SaleFailure => Self::PaymentIntentFailure, - NmiWebhookEventType::RefundSuccess => Self::RefundSuccess, - NmiWebhookEventType::RefundFailure => Self::RefundFailure, - NmiWebhookEventType::VoidSuccess => Self::PaymentIntentCancelled, - NmiWebhookEventType::AuthSuccess => Self::PaymentIntentAuthorizationSuccess, - NmiWebhookEventType::CaptureSuccess => Self::PaymentIntentCaptureSuccess, - NmiWebhookEventType::AuthFailure => Self::PaymentIntentAuthorizationFailure, - NmiWebhookEventType::CaptureFailure => Self::PaymentIntentCaptureFailure, - NmiWebhookEventType::VoidFailure => Self::PaymentIntentCancelFailure, - NmiWebhookEventType::SaleUnknown - | NmiWebhookEventType::RefundUnknown - | NmiWebhookEventType::AuthUnknown - | NmiWebhookEventType::VoidUnknown - | NmiWebhookEventType::CaptureUnknown => Self::EventNotSupported, - } +pub fn get_nmi_webhook_event(status: NmiWebhookEventType) -> IncomingWebhookEvent { + match status { + NmiWebhookEventType::SaleSuccess => IncomingWebhookEvent::PaymentIntentSuccess, + NmiWebhookEventType::SaleFailure => IncomingWebhookEvent::PaymentIntentFailure, + NmiWebhookEventType::RefundSuccess => IncomingWebhookEvent::RefundSuccess, + NmiWebhookEventType::RefundFailure => IncomingWebhookEvent::RefundFailure, + NmiWebhookEventType::VoidSuccess => IncomingWebhookEvent::PaymentIntentCancelled, + NmiWebhookEventType::AuthSuccess => IncomingWebhookEvent::PaymentIntentAuthorizationSuccess, + NmiWebhookEventType::CaptureSuccess => IncomingWebhookEvent::PaymentIntentCaptureSuccess, + NmiWebhookEventType::AuthFailure => IncomingWebhookEvent::PaymentIntentAuthorizationFailure, + NmiWebhookEventType::CaptureFailure => IncomingWebhookEvent::PaymentIntentCaptureFailure, + NmiWebhookEventType::VoidFailure => IncomingWebhookEvent::PaymentIntentCancelFailure, + NmiWebhookEventType::SaleUnknown + | NmiWebhookEventType::RefundUnknown + | NmiWebhookEventType::AuthUnknown + | NmiWebhookEventType::VoidUnknown + | NmiWebhookEventType::CaptureUnknown => IncomingWebhookEvent::EventNotSupported, } } diff --git a/crates/router/src/connector/payone.rs b/crates/hyperswitch_connectors/src/connectors/payone.rs similarity index 57% rename from crates/router/src/connector/payone.rs rename to crates/hyperswitch_connectors/src/connectors/payone.rs index db862274fe1..ca3e9b2cba9 100644 --- a/crates/router/src/connector/payone.rs +++ b/crates/hyperswitch_connectors/src/connectors/payone.rs @@ -1,44 +1,73 @@ pub mod transformers; +use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use base64::Engine; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; +use common_utils::{consts::BASE64_ENGINE, errors::CustomResult, ext_traits::BytesExt}; #[cfg(feature = "payouts")] -use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; +use common_utils::{ + request::{Method, Request, RequestBuilder}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; use error_stack::{report, ResultExt}; -use masking::{ExposeInterface, PeekInterface}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_data::RouterData, + router_flow_types::PoFulfill, + types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}, +}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; +use hyperswitch_interfaces::{ + api::{ + ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + ConnectorSpecifications, ConnectorValidation, CurrencyUnit, MandateSetup, Payment, + PaymentAuthorize, PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, + Refund, RefundExecute, RefundSync, + }, + configs::Connectors, + consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::{ + api::{PayoutFulfill, Payouts}, + types::PayoutFulfillType, +}; +use masking::{ExposeInterface, Mask, Maskable, PeekInterface}; use ring::hmac; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use self::transformers as payone; #[cfg(feature = "payouts")] -use crate::connector::utils::convert_amount; +use crate::constants::headers::DATE; #[cfg(feature = "payouts")] use crate::get_formatted_date_time; -#[cfg(feature = "payouts")] -use crate::services; use crate::{ - configs::settings, - connector::{ - utils as connector_utils, - utils::{ConnectorErrorType, ConnectorErrorTypeMapping}, - }, - consts, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - request::{self, Mask}, - ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, + constants::headers::AUTHORIZATION, + utils::{ + get_error_code_error_message_based_on_priority, ConnectorErrorType, + ConnectorErrorTypeMapping, }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, - }, - utils::BytesExt, }; +#[cfg(feature = "payouts")] +use crate::{types::ResponseRouterData, utils::convert_amount}; #[derive(Clone)] pub struct Payone { #[cfg(feature = "payouts")] @@ -59,7 +88,7 @@ impl Payone { canonicalized_path: String, content_type: String, date_header: String, - ) -> CustomResult<String, errors::ConnectorError> { + ) -> CustomResult<String, ConnectorError> { let payone::PayoneAuthType { api_key, api_secret, @@ -73,32 +102,28 @@ impl Payone { canonicalized_path.trim() ); let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.expose().as_bytes()); - let hash_hmac = consts::BASE64_ENGINE.encode(hmac::sign(&key, string_to_hash.as_bytes())); + let hash_hmac = BASE64_ENGINE.encode(hmac::sign(&key, string_to_hash.as_bytes())); let signature_header = format!("GCS v1HMAC:{}:{}", api_key.peek(), hash_hmac); Ok(signature_header) } } -impl api::Payment for Payone {} -impl api::PaymentSession for Payone {} -impl api::ConnectorAccessToken for Payone {} -impl api::MandateSetup for Payone {} -impl api::PaymentAuthorize for Payone {} -impl api::PaymentSync for Payone {} -impl api::PaymentCapture for Payone {} -impl api::PaymentVoid for Payone {} -impl api::Refund for Payone {} -impl api::RefundExecute for Payone {} -impl api::RefundSync for Payone {} -impl api::PaymentToken for Payone {} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Payone +impl Payment for Payone {} +impl PaymentSession for Payone {} +impl ConnectorAccessToken for Payone {} +impl MandateSetup for Payone {} +impl PaymentAuthorize for Payone {} +impl PaymentSync for Payone {} +impl PaymentCapture for Payone {} +impl PaymentVoid for Payone {} +impl Refund for Payone {} +impl RefundExecute for Payone {} +impl RefundSync for Payone {} +impl PaymentToken for Payone {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Payone { } @@ -109,9 +134,9 @@ where #[cfg(feature = "payouts")] 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>)>, ConnectorError> { let auth = payone::PayoneAuthType::try_from(&req.connector_auth_type)?; let http_method = self.get_http_method().to_string(); let content_type = Self::get_content_type(self); @@ -129,9 +154,9 @@ where date_header.clone(), )?; let headers = vec![ - (headers::DATE.to_string(), date_header.to_string().into()), + (DATE.to_string(), date_header.to_string().into()), ( - headers::AUTHORIZATION.to_string(), + AUTHORIZATION.to_string(), authorization_header.to_string().into(), ), ]; @@ -145,26 +170,26 @@ impl ConnectorCommon for Payone { "payone" } - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Minor + fn get_currency_unit(&self) -> CurrencyUnit { + CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.payone.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = payone::PayoneAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( - headers::AUTHORIZATION.to_string(), + AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } @@ -173,34 +198,33 @@ impl ConnectorCommon for Payone { &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: payone::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let errors_list = response.errors.clone().unwrap_or_default(); - let option_error_code_message = - connector_utils::get_error_code_error_message_based_on_priority( - self.clone(), - errors_list - .into_iter() - .map(|errors| errors.into()) - .collect(), - ); + let option_error_code_message = get_error_code_error_message_based_on_priority( + self.clone(), + errors_list + .into_iter() + .map(|errors| errors.into()) + .collect(), + ); match response.errors { Some(errors) => Ok(ErrorResponse { status_code: res.status_code, code: option_error_code_message .clone() .map(|error_code_message| error_code_message.error_code) - .unwrap_or(consts::NO_ERROR_CODE.to_string()), + .unwrap_or(NO_ERROR_CODE.to_string()), message: option_error_code_message .clone() .map(|error_code_message| error_code_message.error_code) - .unwrap_or(consts::NO_ERROR_CODE.to_string()), + .unwrap_or(NO_ERROR_CODE.to_string()), reason: Some( errors .iter() @@ -216,8 +240,8 @@ impl ConnectorCommon for Payone { }), None => Ok(ErrorResponse { status_code: res.status_code, - code: consts::NO_ERROR_CODE.to_string(), - message: consts::NO_ERROR_MESSAGE.to_string(), + code: NO_ERROR_CODE.to_string(), + message: NO_ERROR_MESSAGE.to_string(), reason: None, attempt_status: None, connector_transaction_id: None, @@ -230,64 +254,38 @@ impl ConnectorCommon for Payone { } impl ConnectorValidation for Payone {} -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Payone -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payone {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Payone -{ -} +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Payone {} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payone {} -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Payone {} -impl api::Payouts for Payone {} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Payone {} +#[cfg(feature = "payouts")] +impl Payouts for Payone {} #[cfg(feature = "payouts")] -impl api::PayoutFulfill for Payone {} +impl PayoutFulfill for Payone {} #[cfg(feature = "payouts")] -impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> - for Payone -{ +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Payone { fn get_url( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let auth = payone::PayoneAuthType::try_from(&req.connector_auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(format!( "{}v2/{}/payouts", self.base_url(_connectors), @@ -297,17 +295,17 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, @@ -320,19 +318,15 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp fn build_request( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutFulfillType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutFulfillType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } @@ -340,19 +334,19 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp #[instrument(skip_all)] fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoFulfill>, + data: &PayoutsRouterData<PoFulfill>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { + ) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> { let response: payone::PayonePayoutFulfillResponse = res .response .parse_struct("PayonePayoutFulfillResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(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,32 +357,32 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] -impl api::IncomingWebhook for Payone { +impl IncomingWebhook for Payone { fn get_webhook_object_reference_id( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } } diff --git a/crates/router/src/connector/payone/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payone/transformers.rs similarity index 61% rename from crates/router/src/connector/payone/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/payone/transformers.rs index 2ac9c083018..8beae986e3a 100644 --- a/crates/router/src/connector/payone/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payone/transformers.rs @@ -2,31 +2,36 @@ use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use cards::CardNumber; +#[cfg(feature = "payouts")] +use common_enums::{PayoutStatus, PayoutType}; use common_utils::types::MinorUnit; #[cfg(feature = "payouts")] +use common_utils::{ext_traits::OptionExt, transformers::ForeignFrom}; +#[cfg(feature = "payouts")] use error_stack::ResultExt; +use hyperswitch_domain_models::router_data::ConnectorAuthType; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::PoFulfill, + types::{PayoutsResponseData, PayoutsRouterData}, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; -use serde_repr::{Deserialize_repr, Serialize_repr}; - -use crate::connector::{ - utils, - utils::{get_unimplemented_payment_method_error_message, CardIssuer}, -}; #[cfg(feature = "payouts")] -type Error = error_stack::Report<errors::ConnectorError>; - +use crate::utils::CardData as _; +use crate::utils::{ + get_unimplemented_payment_method_error_message, CardIssuer, ErrorCodeAndMessage, +}; #[cfg(feature = "payouts")] use crate::{ - connector::utils::{CardData, PayoutsData, RouterData}, - core::errors, - types::{self, api, storage::enums as storage_enums, transformers::ForeignFrom}, - utils::OptionExt, + types::PayoutsResponseRouterData, + utils::{PayoutsData, RouterData}, }; -#[cfg(not(feature = "payouts"))] -use crate::{core::errors, types}; - +#[cfg(feature = "payouts")] +type Error = error_stack::Report<ConnectorError>; +use serde_repr::{Deserialize_repr, Serialize_repr}; pub struct PayoneRouterData<T> { pub amount: MinorUnit, pub router_data: T, @@ -54,7 +59,7 @@ pub struct SubError { pub http_status_code: u16, } -impl From<SubError> for utils::ErrorCodeAndMessage { +impl From<SubError> for ErrorCodeAndMessage { fn from(error: SubError) -> Self { Self { error_code: error.code.to_string(), @@ -69,11 +74,11 @@ pub struct PayoneAuthType { pub api_secret: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for PayoneAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorAuthType> for PayoneAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::SignatureKey { + ConnectorAuthType::SignatureKey { api_key, key1, api_secret, @@ -82,7 +87,7 @@ impl TryFrom<&types::ConnectorAuthType> for PayoneAuthType { merchant_account: key1.to_owned(), api_secret: api_secret.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, + _ => Err(ConnectorError::FailedToObtainAuthType)?, } } } @@ -121,60 +126,54 @@ pub struct Card { } #[cfg(feature = "payouts")] -impl TryFrom<PayoneRouterData<&types::PayoutsRouterData<api::PoFulfill>>> - for PayonePayoutFulfillRequest -{ +impl TryFrom<PayoneRouterData<&PayoutsRouterData<PoFulfill>>> for PayonePayoutFulfillRequest { type Error = Error; fn try_from( - item: PayoneRouterData<&types::PayoutsRouterData<api::PoFulfill>>, + item: PayoneRouterData<&PayoutsRouterData<PoFulfill>>, ) -> Result<Self, Self::Error> { let request = item.router_data.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { - storage_enums::PayoutType::Card => { + PayoutType::Card => { let amount_of_money: AmountOfMoney = AmountOfMoney { amount: item.amount, currency_code: item.router_data.request.destination_currency.to_string(), }; - let card_payout_method_specific_input = match item - .router_data - .get_payout_method_data()? - { - PayoutMethodData::Card(card_data) => CardPayoutMethodSpecificInput { - card: Card { - card_number: card_data.card_number.clone(), - card_holder_name: card_data - .card_holder_name - .clone() - .get_required_value("card_holder_name") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "payout_method_data.card.holder_name", - })?, - expiry_date: card_data - .get_card_expiry_month_year_2_digit_with_delimiter( - "".to_string(), - )?, + let card_payout_method_specific_input = + match item.router_data.get_payout_method_data()? { + PayoutMethodData::Card(card_data) => CardPayoutMethodSpecificInput { + card: Card { + card_number: card_data.card_number.clone(), + card_holder_name: card_data + .card_holder_name + .clone() + .get_required_value("card_holder_name") + .change_context(ConnectorError::MissingRequiredField { + field_name: "payout_method_data.card.holder_name", + })?, + expiry_date: card_data + .get_card_expiry_month_year_2_digit_with_delimiter( + "".to_string(), + )?, + }, + payment_product_id: PaymentProductId::try_from( + card_data.get_card_issuer()?, + )?, }, - payment_product_id: PaymentProductId::try_from( - card_data.get_card_issuer()?, - )?, - }, - PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { - Err(errors::ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Payone"), - ))? - } - }; + PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Payone"), + ))? + } + }; Ok(Self { amount_of_money, card_payout_method_specific_input, }) } - storage_enums::PayoutType::Wallet | storage_enums::PayoutType::Bank => { - Err(errors::ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Payone"), - ))? - } + PayoutType::Wallet | PayoutType::Bank => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Payone"), + ))?, } } } @@ -187,7 +186,7 @@ pub enum PaymentProductId { } impl TryFrom<CardIssuer> for PaymentProductId { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> { match issuer { CardIssuer::Master => Ok(Self::MasterCard), @@ -197,7 +196,7 @@ impl TryFrom<CardIssuer> for PaymentProductId { | CardIssuer::Discover | CardIssuer::DinersClub | CardIssuer::JCB - | CardIssuer::CarteBlanche => Err(errors::ConnectorError::NotImplemented( + | CardIssuer::CarteBlanche => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("payone"), ) .into()), @@ -237,7 +236,7 @@ pub struct PayoutOutput { } #[cfg(feature = "payouts")] -impl ForeignFrom<PayoneStatus> for storage_enums::PayoutStatus { +impl ForeignFrom<PayoneStatus> for PayoutStatus { fn foreign_from(payone_status: PayoneStatus) -> Self { match payone_status { PayoneStatus::AccountCredited => Self::Success, @@ -251,18 +250,18 @@ impl ForeignFrom<PayoneStatus> for storage_enums::PayoutStatus { } #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>> - for types::PayoutsRouterData<F> +impl<F> TryFrom<PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>> + for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>, + item: PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>, ) -> Result<Self, Self::Error> { let response: PayonePayoutFulfillResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::foreign_from(response.status)), + response: Ok(PayoutsResponseData { + status: Some(PayoutStatus::foreign_from(response.status)), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, diff --git a/crates/router/src/connector/riskified.rs b/crates/hyperswitch_connectors/src/connectors/riskified.rs similarity index 51% rename from crates/router/src/connector/riskified.rs rename to crates/hyperswitch_connectors/src/connectors/riskified.rs index 971bd5de04f..269ac0700c4 100644 --- a/crates/router/src/connector/riskified.rs +++ b/crates/hyperswitch_connectors/src/connectors/riskified.rs @@ -1,51 +1,96 @@ pub mod transformers; - +#[cfg(feature = "frm")] +use api_models::webhooks::{ConnectorWebhookSecrets, IncomingWebhookEvent, ObjectReferenceId}; #[cfg(feature = "frm")] use base64::Engine; -use common_utils::types::{ - AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, +#[cfg(feature = "frm")] +use common_utils::types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}; +#[cfg(feature = "frm")] +use common_utils::{ + consts::BASE64_ENGINE, + request::{Method, RequestBuilder}, + types::MinorUnit, }; #[cfg(feature = "frm")] use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{errors::CustomResult, request::Request}; #[cfg(feature = "frm")] use error_stack::ResultExt; #[cfg(feature = "frm")] -use masking::{ExposeInterface, PeekInterface, Secret}; +use hyperswitch_domain_models::{ + router_data::ErrorResponse, + router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; +use hyperswitch_interfaces::{ + api::{ + ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + ConnectorSpecifications, ConnectorValidation, MandateSetup, Payment, PaymentAuthorize, + PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund, + RefundExecute, RefundSync, + }, + configs::Connectors, + errors::ConnectorError, +}; +#[cfg(feature = "frm")] +use hyperswitch_interfaces::{ + api::{ + FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, + FraudCheckSale, FraudCheckTransaction, + }, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +#[cfg(feature = "frm")] +use masking::Maskable; +#[cfg(feature = "frm")] +use masking::{ExposeInterface, Mask, PeekInterface, Secret}; #[cfg(feature = "frm")] use ring::hmac; #[cfg(feature = "frm")] use transformers as riskified; -use super::utils::convert_amount; #[cfg(feature = "frm")] -use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest}; +use crate::constants::headers; +#[cfg(feature = "frm")] +use crate::utils::convert_amount; +#[cfg(feature = "frm")] use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - services::{self, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, + FrmCheckoutRouterData, FrmCheckoutType, FrmFulfillmentRouterData, FrmFulfillmentType, + FrmTransactionRouterData, FrmTransactionType, ResponseRouterData, }, -}; -#[cfg(feature = "frm")] -use crate::{ - consts, - events::connector_api_logs::ConnectorEvent, - headers, - services::request, - types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, - utils::BytesExt, + utils::FrmTransactionRouterDataRequest, }; #[derive(Clone)] pub struct Riskified { + #[cfg(feature = "frm")] amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Riskified { pub fn new() -> &'static Self { &Self { + #[cfg(feature = "frm")] amount_converter: &StringMajorUnitForConnector, } } @@ -55,7 +100,7 @@ impl Riskified { &self, auth: &riskified::RiskifiedAuthType, payload: &str, - ) -> CustomResult<String, errors::ConnectorError> { + ) -> CustomResult<String, ConnectorError> { let key = hmac::Key::new( hmac::HMAC_SHA256, auth.secret_token.clone().expose().as_bytes(), @@ -76,9 +121,9 @@ where #[cfg(feature = "frm")] 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>)>, ConnectorError> { let auth: riskified::RiskifiedAuthType = riskified::RiskifiedAuthType::try_from(&req.connector_auth_type)?; @@ -89,7 +134,7 @@ where let digest = self .generate_authorization_signature(&auth, payload) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + .change_context(ConnectorError::RequestEncodingFailed)?; let header = vec![ ( @@ -102,7 +147,7 @@ where ), ( "X-RISKIFIED-HMAC-SHA256".to_string(), - request::Mask::into_masked(digest), + Mask::into_masked(digest), ), ( "Accept".to_string(), @@ -122,7 +167,7 @@ impl ConnectorCommon for Riskified { fn common_get_content_type(&self) -> &'static str { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.riskified.base_url.as_ref() } @@ -131,11 +176,13 @@ impl ConnectorCommon for Riskified { &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { + use hyperswitch_interfaces::consts::NO_ERROR_CODE; + let response: riskified::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -143,7 +190,7 @@ impl ConnectorCommon for Riskified { Ok(ErrorResponse { status_code: res.status_code, attempt_status: None, - code: consts::NO_ERROR_CODE.to_string(), + code: NO_ERROR_CODE.to_string(), message: response.error.message.clone(), reason: None, connector_transaction_id: None, @@ -155,18 +202,12 @@ impl ConnectorCommon for Riskified { } #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Checkout, - frm_types::FraudCheckCheckoutData, - frm_types::FraudCheckResponseData, - > for Riskified -{ +impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> for Riskified { fn get_headers( &self, - req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -176,23 +217,23 @@ impl fn get_url( &self, - _req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/decide")) } fn get_request_body( &self, - req: &frm_types::FrmCheckoutRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &FrmCheckoutRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount), req.request .currency - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?, )?; @@ -203,37 +244,33 @@ impl fn build_request( &self, - req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmCheckoutType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&FrmCheckoutType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(frm_types::FrmCheckoutType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmCheckoutType::get_request_body( - self, req, connectors, - )?) + .headers(FrmCheckoutType::get_headers(self, req, connectors)?) + .set_body(FrmCheckoutType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &frm_types::FrmCheckoutRouterData, + data: &FrmCheckoutRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> { + ) -> CustomResult<FrmCheckoutRouterData, ConnectorError> { let response: riskified::RiskifiedPaymentsResponse = res .response .parse_struct("RiskifiedPaymentsResponse Checkout") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - <frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData { + <FrmCheckoutRouterData>::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -243,47 +280,36 @@ impl &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl api::Payment for Riskified {} -impl api::PaymentAuthorize for Riskified {} -impl api::PaymentSync for Riskified {} -impl api::PaymentVoid for Riskified {} -impl api::PaymentCapture for Riskified {} -impl api::MandateSetup for Riskified {} -impl api::ConnectorAccessToken for Riskified {} -impl api::PaymentToken for Riskified {} -impl api::Refund for Riskified {} -impl api::RefundExecute for Riskified {} -impl api::RefundSync for Riskified {} +impl Payment for Riskified {} +impl PaymentAuthorize for Riskified {} +impl PaymentSync for Riskified {} +impl PaymentVoid for Riskified {} +impl PaymentCapture for Riskified {} +impl MandateSetup for Riskified {} +impl ConnectorAccessToken for Riskified {} +impl PaymentToken for Riskified {} +impl Refund for Riskified {} +impl RefundExecute for Riskified {} +impl RefundSync for Riskified {} impl ConnectorValidation for Riskified {} #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Sale, - frm_types::FraudCheckSaleData, - frm_types::FraudCheckResponseData, - > for Riskified -{ -} +impl ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for Riskified {} #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Transaction, - frm_types::FraudCheckTransactionData, - frm_types::FraudCheckResponseData, - > for Riskified +impl ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> + for Riskified { fn get_headers( &self, - req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -293,9 +319,9 @@ impl fn get_url( &self, - req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { match req.is_payment_successful() { Some(false) => Ok(format!( "{}{}", @@ -308,9 +334,9 @@ impl fn get_request_body( &self, - req: &frm_types::FrmTransactionRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &FrmTransactionRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { match req.is_payment_successful() { Some(false) => { let req_obj = riskified::TransactionFailedRequest::try_from(req)?; @@ -322,7 +348,7 @@ impl MinorUnit::new(req.request.amount), req.request .currency - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?, )?; @@ -335,50 +361,44 @@ impl fn build_request( &self, - req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmTransactionType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&FrmTransactionType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(frm_types::FrmTransactionType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmTransactionType::get_request_body( - self, req, connectors, - )?) + .headers(FrmTransactionType::get_headers(self, req, connectors)?) + .set_body(FrmTransactionType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &frm_types::FrmTransactionRouterData, + data: &FrmTransactionRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> { + ) -> CustomResult<FrmTransactionRouterData, ConnectorError> { let response: riskified::RiskifiedTransactionResponse = res .response .parse_struct("RiskifiedPaymentsResponse Transaction") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); match response { riskified::RiskifiedTransactionResponse::FailedResponse(response_data) => { - <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { + <FrmTransactionRouterData>::try_from(ResponseRouterData { response: response_data, data: data.clone(), http_code: res.status_code, }) } riskified::RiskifiedTransactionResponse::SuccessResponse(response_data) => { - <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { + <FrmTransactionRouterData>::try_from(ResponseRouterData { response: response_data, data: data.clone(), http_code: res.status_code, @@ -390,24 +410,20 @@ impl &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Fulfillment, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, - > for Riskified +impl ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> + for Riskified { fn get_headers( &self, - req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -417,58 +433,52 @@ impl fn get_url( &self, - _req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/fulfill")) } fn get_request_body( &self, - req: &frm_types::FrmFulfillmentRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &FrmFulfillmentRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, - req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmFulfillmentType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&FrmFulfillmentType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(frm_types::FrmFulfillmentType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmFulfillmentType::get_request_body( - self, req, connectors, - )?) + .headers(FrmFulfillmentType::get_headers(self, req, connectors)?) + .set_body(FrmFulfillmentType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &frm_types::FrmFulfillmentRouterData, + data: &FrmFulfillmentRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> { + ) -> CustomResult<FrmFulfillmentRouterData, ConnectorError> { let response: riskified::RiskifiedFulfilmentResponse = res .response .parse_struct("RiskifiedFulfilmentResponse fulfilment") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData { + FrmFulfillmentRouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -479,136 +489,93 @@ impl &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::RecordReturn, - frm_types::FraudCheckRecordReturnData, - frm_types::FraudCheckResponseData, - > for Riskified -{ -} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Riskified +impl ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> + for Riskified { } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Riskified { } -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Riskified +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Riskified {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Riskified { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err( - errors::ConnectorError::NotImplemented("Setup Mandate flow for Riskified".to_string()) - .into(), - ) + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Err(ConnectorError::NotImplemented("Setup Mandate flow for Riskified".to_string()).into()) } } -impl api::PaymentSession for Riskified {} +impl PaymentSession for Riskified {} -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Riskified {} -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Riskified {} #[cfg(feature = "frm")] -impl api::FraudCheck for Riskified {} +impl FraudCheck for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckSale for Riskified {} +impl FraudCheckSale for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckCheckout for Riskified {} +impl FraudCheckCheckout for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckTransaction for Riskified {} +impl FraudCheckTransaction for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckFulfillment for Riskified {} +impl FraudCheckFulfillment for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckRecordReturn for Riskified {} +impl FraudCheckRecordReturn for Riskified {} #[cfg(feature = "frm")] #[async_trait::async_trait] -impl api::IncomingWebhook for Riskified { +impl IncomingWebhook for Riskified { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, ConnectorError> { let header_value = - connector_utils::get_header_key_value("x-riskified-hmac-sha256", request.headers)?; + crate::utils::get_header_key_value("x-riskified-hmac-sha256", request.headers)?; Ok(header_value.as_bytes().to_vec()) } async fn verify_webhook_source( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, - ) -> CustomResult<bool, errors::ConnectorError> { + ) -> CustomResult<bool, ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, @@ -616,11 +583,11 @@ impl api::IncomingWebhook for Riskified { connector_webhook_details, ) .await - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( @@ -628,55 +595,55 @@ impl api::IncomingWebhook for Riskified { merchant_id, &connector_webhook_secrets, ) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret); let signed_message = hmac::sign(&signing_key, &message); - let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref()); + let payload_sign = BASE64_ENGINE.encode(signed_message.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } 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> { + _connector_webhook_secrets: &ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, ConnectorError> { Ok(request.body.to_vec()) } fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - Ok(api::webhooks::ObjectReferenceId::PaymentId( + .change_context(ConnectorError::WebhookReferenceIdNotFound)?; + Ok(ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(resource.id), )) } fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") - .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(api::IncomingWebhookEvent::from(resource.status)) + .change_context(ConnectorError::WebhookEventTypeNotFound)?; + Ok(IncomingWebhookEvent::from(resource.status)) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(resource)) } } diff --git a/crates/router/src/connector/riskified/transformers.rs b/crates/hyperswitch_connectors/src/connectors/riskified/transformers.rs similarity index 100% rename from crates/router/src/connector/riskified/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/riskified/transformers.rs diff --git a/crates/router/src/connector/riskified/transformers/api.rs b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs similarity index 82% rename from crates/router/src/connector/riskified/transformers/api.rs rename to crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs index e8c1b874417..7ce3ac979e3 100644 --- a/crates/router/src/connector/riskified/transformers/api.rs +++ b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs @@ -1,4 +1,5 @@ -use api_models::payments::AdditionalPaymentData; +use api_models::{payments::AdditionalPaymentData, webhooks::IncomingWebhookEvent}; +use common_enums::{Currency, FraudCheckStatus}; use common_utils::{ ext_traits::ValueExt, id_type, @@ -6,26 +7,32 @@ use common_utils::{ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{self, ResultExt}; +use hyperswitch_domain_models::{ + router_data::RouterData, + router_flow_types::Fulfillment, + router_request_types::{ + fraud_check::{FraudCheckFulfillmentData, FulfillmentStatus}, + BrowserInformation, ResponseId, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ - connector::utils::{ - convert_amount, AddressDetailsData, FraudCheckCheckoutRequest, - FraudCheckTransactionRequest, RouterData, - }, - core::{errors, fraud_check::types as core_types}, types::{ - self, - api::{self, Fulfillment}, - fraud_check as frm_types, - storage::enums as storage_enums, - ResponseId, ResponseRouterData, + FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmTransactionRouterData, + ResponseRouterData, + }, + utils::{ + convert_amount, AddressDetailsData as _, FraudCheckCheckoutRequest, + FraudCheckTransactionRequest, RouterData as _, }, }; -type Error = error_stack::Report<errors::ConnectorError>; +type Error = error_stack::Report<ConnectorError>; pub struct RiskifiedRouterData<T> { pub amount: StringMajorUnit, @@ -55,7 +62,7 @@ pub struct CheckoutRequest { email: Option<Email>, #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, - currency: Option<common_enums::Currency>, + currency: Option<Currency>, #[serde(with = "common_utils::custom_serde::iso8601")] updated_at: PrimitiveDateTime, gateway: Option<String>, @@ -157,22 +164,20 @@ pub struct RiskifiedMetadata { shipping_lines: Vec<ShippingLines>, } -impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> - for RiskifiedPaymentsCheckoutRequest -{ +impl TryFrom<&RiskifiedRouterData<&FrmCheckoutRouterData>> for RiskifiedPaymentsCheckoutRequest { type Error = Error; fn try_from( - payment: &RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>, + payment: &RiskifiedRouterData<&FrmCheckoutRouterData>, ) -> Result<Self, Self::Error> { let payment_data = payment.router_data.clone(); let metadata: RiskifiedMetadata = payment_data .frm_metadata .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Riskified Metadata") - .change_context(errors::ConnectorError::InvalidDataFormat { + .change_context(ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let billing_address = payment_data.get_billing()?; @@ -187,7 +192,7 @@ impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> payment.amount_converter, order_detail.amount, payment_data.request.currency.ok_or_else(|| { - errors::ConnectorError::MissingRequiredField { + ConnectorError::MissingRequiredField { field_name: "currency", } })?, @@ -251,7 +256,7 @@ impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> .as_ref() .and_then(|browser_info| browser_info.user_agent.clone()), accept_language: payment_data.request.browser_info.as_ref().and_then( - |browser_info: &types::BrowserInformation| browser_info.language.clone(), + |browser_info: &BrowserInformation| browser_info.language.clone(), ), }, note: payment_data.description.clone(), @@ -312,23 +317,17 @@ pub enum PaymentStatus { Processing, } -impl<F, T> - TryFrom<ResponseRouterData<F, RiskifiedPaymentsResponse, T, frm_types::FraudCheckResponseData>> - for types::RouterData<F, T, frm_types::FraudCheckResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, RiskifiedPaymentsResponse, T, FraudCheckResponseData>> + for RouterData<F, T, FraudCheckResponseData> { type Error = Error; fn try_from( - item: ResponseRouterData< - F, - RiskifiedPaymentsResponse, - T, - frm_types::FraudCheckResponseData, - >, + item: ResponseRouterData<F, RiskifiedPaymentsResponse, T, FraudCheckResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::TransactionResponse { + response: Ok(FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order.id), - status: storage_enums::FraudCheckStatus::from(item.response.order.status), + status: FraudCheckStatus::from(item.response.order.status), connector_metadata: None, score: None, reason: item.response.order.description.map(serde_json::Value::from), @@ -338,7 +337,7 @@ impl<F, T> } } -impl From<PaymentStatus> for storage_enums::FraudCheckStatus { +impl From<PaymentStatus> for FraudCheckStatus { fn from(item: PaymentStatus) -> Self { match item { PaymentStatus::Approved => Self::Legit, @@ -372,9 +371,9 @@ pub struct AuthorizationError { message: Option<String>, } -impl TryFrom<&frm_types::FrmTransactionRouterData> for TransactionFailedRequest { +impl TryFrom<&FrmTransactionRouterData> for TransactionFailedRequest { type Error = Error; - fn try_from(item: &frm_types::FrmTransactionRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> { Ok(Self { checkout: FailedTransactionData { id: item.attempt_id.clone(), @@ -404,28 +403,17 @@ pub enum RiskifiedTransactionResponse { } impl<F, T> - TryFrom< - ResponseRouterData< - F, - RiskifiedFailedTransactionResponse, - T, - frm_types::FraudCheckResponseData, - >, - > for types::RouterData<F, T, frm_types::FraudCheckResponseData> + TryFrom<ResponseRouterData<F, RiskifiedFailedTransactionResponse, T, FraudCheckResponseData>> + for RouterData<F, T, FraudCheckResponseData> { type Error = Error; fn try_from( - item: ResponseRouterData< - F, - RiskifiedFailedTransactionResponse, - T, - frm_types::FraudCheckResponseData, - >, + item: ResponseRouterData<F, RiskifiedFailedTransactionResponse, T, FraudCheckResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::TransactionResponse { + response: Ok(FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.checkout.id), - status: storage_enums::FraudCheckStatus::from(item.response.checkout.status), + status: FraudCheckStatus::from(item.response.checkout.status), connector_metadata: None, score: None, reason: item @@ -455,7 +443,7 @@ pub struct TransactionDecisionData { external_status: TransactionStatus, reason: Option<String>, amount: StringMajorUnit, - currency: storage_enums::Currency, + currency: Currency, #[serde(with = "common_utils::custom_serde::iso8601")] decided_at: PrimitiveDateTime, payment_details: Vec<TransactionPaymentDetails>, @@ -472,12 +460,10 @@ pub enum TransactionStatus { Approved, } -impl TryFrom<&RiskifiedRouterData<&frm_types::FrmTransactionRouterData>> - for TransactionSuccessRequest -{ +impl TryFrom<&RiskifiedRouterData<&FrmTransactionRouterData>> for TransactionSuccessRequest { type Error = Error; fn try_from( - item_data: &RiskifiedRouterData<&frm_types::FrmTransactionRouterData>, + item_data: &RiskifiedRouterData<&FrmTransactionRouterData>, ) -> Result<Self, Self::Error> { let item = item_data.router_data.clone(); Ok(Self { @@ -530,16 +516,16 @@ pub struct FulfilmentData { tracking_url: Option<String>, } -impl TryFrom<&frm_types::FrmFulfillmentRouterData> for RiskifiedFulfillmentRequest { +impl TryFrom<&FrmFulfillmentRouterData> for RiskifiedFulfillmentRequest { type Error = Error; - fn try_from(item: &frm_types::FrmFulfillmentRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> { let tracking_number = item .request .fulfillment_req .tracking_numbers .as_ref() .and_then(|numbers| numbers.first().cloned()) - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "tracking_number", })?; let tracking_url = item @@ -565,7 +551,7 @@ impl TryFrom<&frm_types::FrmFulfillmentRouterData> for RiskifiedFulfillmentReque .fulfillment_req .tracking_company .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "tracking_company", })?, tracking_number, @@ -581,27 +567,22 @@ impl ResponseRouterData< Fulfillment, RiskifiedFulfilmentResponse, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, + FraudCheckFulfillmentData, + FraudCheckResponseData, >, - > - for types::RouterData< - Fulfillment, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, - > + > for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> { type Error = Error; fn try_from( item: ResponseRouterData< Fulfillment, RiskifiedFulfilmentResponse, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, + FraudCheckFulfillmentData, + FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::FulfillmentResponse { + response: Ok(FraudCheckResponseData::FulfillmentResponse { order_id: item.response.order.id, shipment_ids: Vec::new(), }), @@ -625,13 +606,12 @@ impl TryFrom<&hyperswitch_domain_models::address::Address> for OrderAddress { fn try_from( address_info: &hyperswitch_domain_models::address::Address, ) -> Result<Self, Self::Error> { - let address = - address_info - .clone() - .address - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "address", - })?; + let address = address_info + .clone() + .address + .ok_or(ConnectorError::MissingRequiredField { + field_name: "address", + })?; Ok(Self { first_name: address.first_name.clone(), last_name: address.last_name.clone(), @@ -648,13 +628,11 @@ impl TryFrom<&hyperswitch_domain_models::address::Address> for OrderAddress { } } -fn get_fulfillment_status( - status: core_types::FulfillmentStatus, -) -> Option<FulfillmentRequestStatus> { +fn get_fulfillment_status(status: FulfillmentStatus) -> Option<FulfillmentRequestStatus> { match status { - core_types::FulfillmentStatus::COMPLETE => Some(FulfillmentRequestStatus::Success), - core_types::FulfillmentStatus::CANCELED => Some(FulfillmentRequestStatus::Cancelled), - core_types::FulfillmentStatus::PARTIAL | core_types::FulfillmentStatus::REPLACEMENT => None, + FulfillmentStatus::COMPLETE => Some(FulfillmentRequestStatus::Success), + FulfillmentStatus::CANCELED => Some(FulfillmentRequestStatus::Cancelled), + FulfillmentStatus::PARTIAL | FulfillmentStatus::REPLACEMENT => None, } } @@ -670,7 +648,7 @@ pub enum RiskifiedWebhookStatus { Declined, } -impl From<RiskifiedWebhookStatus> for api::IncomingWebhookEvent { +impl From<RiskifiedWebhookStatus> for IncomingWebhookEvent { fn from(value: RiskifiedWebhookStatus) -> Self { match value { RiskifiedWebhookStatus::Declined => Self::FrmRejected, diff --git a/crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs new file mode 100644 index 00000000000..2835ea01f8d --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs @@ -0,0 +1,22 @@ +use error_stack; +use hyperswitch_domain_models::router_data::ConnectorAuthType; +use hyperswitch_interfaces::errors::ConnectorError; +use masking::{ExposeInterface, Secret}; + +pub struct RiskifiedAuthType { + pub secret_token: Secret<String>, + pub domain_name: String, +} + +impl TryFrom<&ConnectorAuthType> for RiskifiedAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + secret_token: api_key.to_owned(), + domain_name: key1.to_owned().expose(), + }), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), + } + } +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index c21c1d716b1..3acb8c54e27 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -158,6 +158,7 @@ default_imp_for_authorize_session_token!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -168,6 +169,7 @@ default_imp_for_authorize_session_token!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -182,6 +184,7 @@ default_imp_for_authorize_session_token!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Stripebilling, @@ -266,12 +269,14 @@ default_imp_for_calculate_tax!( connectors::Opayo, connectors::Opennode, connectors::Paybox, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, connectors::Nuvei, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -282,6 +287,7 @@ default_imp_for_calculate_tax!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -355,6 +361,7 @@ default_imp_for_session_update!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -364,6 +371,7 @@ default_imp_for_session_update!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -375,6 +383,7 @@ default_imp_for_session_update!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -455,6 +464,7 @@ default_imp_for_post_session_tokens!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Square, connectors::Stax, @@ -464,6 +474,7 @@ default_imp_for_post_session_tokens!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -475,6 +486,7 @@ default_imp_for_post_session_tokens!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -573,12 +585,14 @@ default_imp_for_update_metadata!( connectors::Opayo, connectors::Opennode, connectors::Nuvei, + connectors::Nmi, connectors::Paybox, connectors::Payeezy, connectors::Payme, connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Payone, connectors::Fiuu, connectors::Globalpay, connectors::Globepay, @@ -590,6 +604,7 @@ default_imp_for_update_metadata!( connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, + connectors::Riskified, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -660,12 +675,14 @@ default_imp_for_complete_authorize!( connectors::Opayo, connectors::Opennode, connectors::Payeezy, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, + connectors::Riskified, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -740,6 +757,7 @@ default_imp_for_incremental_authorization!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -751,6 +769,7 @@ default_imp_for_incremental_authorization!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -765,6 +784,7 @@ default_imp_for_incremental_authorization!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -844,6 +864,7 @@ default_imp_for_create_customer!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -855,6 +876,7 @@ default_imp_for_create_customer!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -865,6 +887,7 @@ default_imp_for_create_customer!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Square, connectors::Stripebilling, @@ -944,6 +967,7 @@ default_imp_for_connector_redirect_response!( connectors::Opennode, connectors::Payeezy, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -952,6 +976,7 @@ default_imp_for_connector_redirect_response!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1030,6 +1055,7 @@ default_imp_for_pre_processing_steps!( connectors::Paybox, connectors::Payeezy, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1041,6 +1067,7 @@ default_imp_for_pre_processing_steps!( connectors::Rapyd, connectors::Razorpay, connectors::Recurly, + connectors::Riskified, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -1115,6 +1142,7 @@ default_imp_for_post_processing_steps!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1126,6 +1154,7 @@ default_imp_for_post_processing_steps!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -1140,6 +1169,7 @@ default_imp_for_post_processing_steps!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1224,12 +1254,14 @@ default_imp_for_approve!( connectors::Nexixpay, connectors::Opayo, connectors::Opennode, + connectors::Nmi, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1242,6 +1274,7 @@ default_imp_for_approve!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1319,6 +1352,7 @@ default_imp_for_reject!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1329,6 +1363,7 @@ default_imp_for_reject!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Payone, connectors::Payme, connectors::Paypal, connectors::Paystack, @@ -1344,6 +1379,7 @@ default_imp_for_reject!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1421,6 +1457,7 @@ default_imp_for_webhook_source_verification!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1429,6 +1466,7 @@ default_imp_for_webhook_source_verification!( connectors::Opayo, connectors::Opennode, connectors::Nuvei, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payme, @@ -1445,6 +1483,7 @@ default_imp_for_webhook_source_verification!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1521,6 +1560,7 @@ default_imp_for_accept_dispute!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1532,6 +1572,7 @@ default_imp_for_accept_dispute!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -1546,6 +1587,7 @@ default_imp_for_accept_dispute!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1621,6 +1663,7 @@ default_imp_for_submit_evidence!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1633,6 +1676,7 @@ default_imp_for_submit_evidence!( connectors::Payeezy, connectors::Payme, connectors::Paypal, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -1646,6 +1690,7 @@ default_imp_for_submit_evidence!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1721,6 +1766,7 @@ default_imp_for_defend_dispute!( connectors::Juspaythreedsserver, connectors::Klarna, connectors::Helcim, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1732,6 +1778,7 @@ default_imp_for_defend_dispute!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -1746,6 +1793,7 @@ default_imp_for_defend_dispute!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1830,6 +1878,7 @@ default_imp_for_file_upload!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1841,6 +1890,7 @@ default_imp_for_file_upload!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -1855,6 +1905,7 @@ default_imp_for_file_upload!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1932,6 +1983,7 @@ default_imp_for_payouts!( connectors::Opayo, connectors::Opennode, connectors::Paybox, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nuvei, @@ -1946,6 +1998,7 @@ default_imp_for_payouts!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Square, connectors::Stax, @@ -2023,6 +2076,7 @@ default_imp_for_payouts_create!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2033,6 +2087,7 @@ default_imp_for_payouts_create!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -2046,6 +2101,7 @@ default_imp_for_payouts_create!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2125,6 +2181,7 @@ default_imp_for_payouts_retrieve!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2137,6 +2194,7 @@ default_imp_for_payouts_retrieve!( connectors::Payme, connectors::Paystack, connectors::Payu, + connectors::Payone, connectors::Placetopay, connectors::Powertranz, connectors::Prophetpay, @@ -2148,6 +2206,7 @@ default_imp_for_payouts_retrieve!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2226,6 +2285,7 @@ default_imp_for_payouts_eligibility!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2238,6 +2298,7 @@ default_imp_for_payouts_eligibility!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2250,6 +2311,7 @@ default_imp_for_payouts_eligibility!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2333,6 +2395,7 @@ default_imp_for_payouts_fulfill!( connectors::Nexixpay, connectors::Opayo, connectors::Opennode, + connectors::Nmi, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, @@ -2350,6 +2413,7 @@ default_imp_for_payouts_fulfill!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2428,6 +2492,7 @@ default_imp_for_payouts_cancel!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2440,6 +2505,7 @@ default_imp_for_payouts_cancel!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2452,6 +2518,7 @@ default_imp_for_payouts_cancel!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2531,6 +2598,7 @@ default_imp_for_payouts_quote!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2540,6 +2608,7 @@ default_imp_for_payouts_quote!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Payone, connectors::Payme, connectors::Paypal, connectors::Paystack, @@ -2555,6 +2624,7 @@ default_imp_for_payouts_quote!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2634,6 +2704,7 @@ default_imp_for_payouts_recipient!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2644,6 +2715,7 @@ default_imp_for_payouts_recipient!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -2658,6 +2730,7 @@ default_imp_for_payouts_recipient!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2737,6 +2810,7 @@ default_imp_for_payouts_recipient_account!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2747,6 +2821,7 @@ default_imp_for_payouts_recipient_account!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -2761,6 +2836,7 @@ default_imp_for_payouts_recipient_account!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2841,6 +2917,7 @@ default_imp_for_frm_sale!( connectors::Juspaythreedsserver, connectors::Klarna, connectors::Nomupay, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2851,6 +2928,7 @@ default_imp_for_frm_sale!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -2944,6 +3022,7 @@ default_imp_for_frm_checkout!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -2955,6 +3034,7 @@ default_imp_for_frm_checkout!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3048,6 +3128,7 @@ default_imp_for_frm_transaction!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3059,6 +3140,7 @@ default_imp_for_frm_transaction!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3152,6 +3234,7 @@ default_imp_for_frm_fulfillment!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3160,6 +3243,7 @@ default_imp_for_frm_fulfillment!( connectors::Opayo, connectors::Opennode, connectors::Nuvei, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payme, @@ -3256,6 +3340,7 @@ default_imp_for_frm_record_return!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3267,6 +3352,7 @@ default_imp_for_frm_record_return!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3355,6 +3441,7 @@ default_imp_for_revoking_mandates!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Novalnet, connectors::Nexinets, @@ -3365,6 +3452,7 @@ default_imp_for_revoking_mandates!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3379,6 +3467,7 @@ default_imp_for_revoking_mandates!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3455,6 +3544,7 @@ default_imp_for_uas_pre_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3465,6 +3555,7 @@ default_imp_for_uas_pre_authentication!( connectors::Nuvei, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3480,6 +3571,7 @@ default_imp_for_uas_pre_authentication!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3554,6 +3646,7 @@ default_imp_for_uas_post_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3564,6 +3657,7 @@ default_imp_for_uas_post_authentication!( connectors::Nuvei, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3579,6 +3673,7 @@ default_imp_for_uas_post_authentication!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3654,6 +3749,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3664,6 +3760,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Nuvei, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Powertranz, @@ -3679,6 +3776,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3746,6 +3844,7 @@ default_imp_for_connector_request_id!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Novalnet, connectors::Noon, @@ -3757,6 +3856,7 @@ default_imp_for_connector_request_id!( connectors::Paystack, connectors::Payu, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Powertranz, connectors::Prophetpay, @@ -3770,6 +3870,7 @@ default_imp_for_connector_request_id!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3841,6 +3942,7 @@ default_imp_for_fraud_check!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Novalnet, connectors::Noon, @@ -3861,6 +3963,7 @@ default_imp_for_fraud_check!( connectors::Opennode, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, @@ -3967,6 +4070,7 @@ default_imp_for_connector_authentication!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3978,6 +4082,7 @@ default_imp_for_connector_authentication!( connectors::Payeezy, connectors::Paystack, connectors::Payu, + connectors::Payone, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -3992,6 +4097,7 @@ default_imp_for_connector_authentication!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -4066,6 +4172,7 @@ default_imp_for_uas_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Novalnet, connectors::Nexinets, @@ -4086,11 +4193,13 @@ default_imp_for_uas_authentication!( connectors::Opennode, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -4159,6 +4268,7 @@ default_imp_for_revenue_recovery! { connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -4179,11 +4289,13 @@ default_imp_for_revenue_recovery! { connectors::Multisafepay, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -4263,6 +4375,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Jpmorgan, connectors::Klarna, connectors::Nomupay, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -4282,10 +4395,12 @@ default_imp_for_billing_connector_payment_sync!( connectors::Multisafepay, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -4362,6 +4477,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -4382,10 +4498,12 @@ default_imp_for_revenue_recovery_record_back!( connectors::Multisafepay, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 41817d955a6..e593cdfc4bf 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -280,6 +280,8 @@ default_imp_for_new_connector_integration_payment!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -300,6 +302,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -383,6 +386,8 @@ default_imp_for_new_connector_integration_refund!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -403,6 +408,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -481,6 +487,8 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -501,6 +509,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -584,6 +593,8 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -604,6 +615,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -686,6 +698,8 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -706,6 +720,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -789,6 +804,8 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -809,6 +826,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -900,6 +918,8 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Nmi, + connectors::Payone, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, @@ -922,6 +942,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1010,6 +1031,8 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Opayo, connectors::Opennode, connectors::Nuvei, + connectors::Nmi, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payme, @@ -1027,6 +1050,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1112,6 +1136,8 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1132,6 +1158,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1217,6 +1244,8 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1237,6 +1266,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1322,6 +1352,8 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1342,6 +1374,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1427,6 +1460,8 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1447,6 +1482,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1532,6 +1568,8 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1552,6 +1590,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1637,6 +1676,8 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1657,6 +1698,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1742,6 +1784,8 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1762,6 +1806,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1845,6 +1890,8 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1865,6 +1912,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1950,6 +1998,8 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1970,6 +2020,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2055,6 +2106,8 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2075,6 +2128,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2160,6 +2214,8 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2180,6 +2236,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2265,6 +2322,8 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2285,6 +2344,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2370,6 +2430,8 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2390,6 +2452,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2472,6 +2535,8 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2491,6 +2556,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2553,6 +2619,8 @@ default_imp_for_new_connector_integration_frm!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payu, @@ -2564,6 +2632,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2667,6 +2736,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2740,6 +2810,8 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payu, @@ -2751,6 +2823,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs index 63b857e7ca2..209360d32b7 100644 --- a/crates/hyperswitch_connectors/src/types.rs +++ b/crates/hyperswitch_connectors/src/types.rs @@ -3,20 +3,24 @@ use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData}; use hyperswitch_domain_models::{ router_data::{AccessToken, RouterData}, router_flow_types::{ - Accept, AccessTokenAuth, Authorize, Capture, Defend, Evidence, PSync, PreProcessing, - Session, Upload, Void, + Accept, AccessTokenAuth, Authorize, Capture, Checkout, Defend, Evidence, Fulfillment, + PSync, PreProcessing, Session, Transaction, Upload, Void, }, router_request_types::{ + fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckTransactionData, + }, AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SubmitEvidenceRequestData, UploadFileRequestData, }, router_response_types::{ - AcceptDisputeResponse, DefendDisputeResponse, PaymentsResponseData, RefundsResponseData, - SubmitEvidenceResponse, UploadFileResponse, + fraud_check::FraudCheckResponseData, AcceptDisputeResponse, DefendDisputeResponse, + PaymentsResponseData, RefundsResponseData, SubmitEvidenceResponse, UploadFileResponse, }, }; +use hyperswitch_interfaces::api::ConnectorIntegration; pub(crate) type PaymentsSyncResponseRouterData<R> = ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>; @@ -55,3 +59,15 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { pub data: RouterData<Flow, Request, Response>, pub http_code: u16, } +pub type FrmFulfillmentRouterData = + RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; +pub type FrmCheckoutType = + dyn ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; +pub type FrmTransactionType = + dyn ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData>; +pub type FrmTransactionRouterData = + RouterData<Transaction, FraudCheckTransactionData, FraudCheckResponseData>; +pub type FrmFulfillmentType = + dyn ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; +pub type FrmCheckoutRouterData = + RouterData<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 60cb878d9a3..e8b88df4fa2 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -38,6 +38,10 @@ use common_utils::{ types::{AmountConvertor, MinorUnit}, }; use error_stack::{report, ResultExt}; +#[cfg(feature = "frm")] +use hyperswitch_domain_models::router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckTransactionData, +}; use hyperswitch_domain_models::{ address::{Address, AddressDetails, PhoneDetails}, mandates, @@ -69,6 +73,8 @@ use serde_json::Value; use time::PrimitiveDateTime; use unicode_normalization::UnicodeNormalization; +#[cfg(feature = "frm")] +use crate::types::FrmTransactionRouterData; use crate::{constants::UNSUPPORTED_ERROR_MESSAGE, types::RefreshTokenRouterData}; type Error = error_stack::Report<errors::ConnectorError>; @@ -2479,6 +2485,15 @@ macro_rules! capture_method_not_supported { .into()) }; } +#[macro_export] +macro_rules! get_formatted_date_time { + ($date_format:tt) => {{ + let format = time::macros::format_description!($date_format); + time::OffsetDateTime::now_utc() + .format(&format) + .change_context(ConnectorError::InvalidDateFormat) + }}; +} #[macro_export] macro_rules! unimplemented_payment_method { @@ -6073,6 +6088,69 @@ pub fn normalize_string(value: String) -> Result<String, regex::Error> { let normalized = regex.replace_all(&lowercase_value, "").to_string(); Ok(normalized) } +#[cfg(feature = "frm")] +pub trait FrmTransactionRouterDataRequest { + fn is_payment_successful(&self) -> Option<bool>; +} + +#[cfg(feature = "frm")] +impl FrmTransactionRouterDataRequest for FrmTransactionRouterData { + fn is_payment_successful(&self) -> Option<bool> { + match self.status { + AttemptStatus::AuthenticationFailed + | AttemptStatus::RouterDeclined + | AttemptStatus::AuthorizationFailed + | AttemptStatus::Voided + | AttemptStatus::CaptureFailed + | AttemptStatus::Failure + | AttemptStatus::AutoRefunded => Some(false), + + AttemptStatus::AuthenticationSuccessful + | AttemptStatus::PartialChargedAndChargeable + | AttemptStatus::Authorized + | AttemptStatus::Charged => Some(true), + + AttemptStatus::Started + | AttemptStatus::AuthenticationPending + | AttemptStatus::Authorizing + | AttemptStatus::CodInitiated + | AttemptStatus::VoidInitiated + | AttemptStatus::CaptureInitiated + | AttemptStatus::VoidFailed + | AttemptStatus::PartialCharged + | AttemptStatus::Unresolved + | AttemptStatus::Pending + | AttemptStatus::PaymentMethodAwaited + | AttemptStatus::ConfirmationAwaited + | AttemptStatus::DeviceDataCollectionPending => None, + } + } +} + +#[cfg(feature = "frm")] +pub trait FraudCheckCheckoutRequest { + fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; +} + +#[cfg(feature = "frm")] +impl FraudCheckCheckoutRequest for FraudCheckCheckoutData { + fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { + self.order_details + .clone() + .ok_or_else(missing_field_err("order_details")) + } +} + +#[cfg(feature = "frm")] +pub trait FraudCheckTransactionRequest { + fn get_currency(&self) -> Result<enums::Currency, Error>; +} +#[cfg(feature = "frm")] +impl FraudCheckTransactionRequest for FraudCheckTransactionData { + fn get_currency(&self) -> Result<enums::Currency, Error> { + self.currency.ok_or_else(missing_field_err("currency")) + } +} /// Custom deserializer for Option<Currency> that treats empty strings as None pub fn deserialize_optional_currency<'de, D>( diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e398800788c..46f63abf501 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -103,7 +103,6 @@ serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_path_to_error = "0.1.16" serde_qs = "0.12.0" -serde_repr = "0.1.19" serde_urlencoded = "0.7.1" serde_with = "3.7.0" sha1 = { version = "0.10.6" } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 0c4b4be1793..e78c64d6fe9 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -4,10 +4,7 @@ pub mod dummyconnector; pub mod ebanx; pub mod gpayments; pub mod netcetera; -pub mod nmi; -pub mod payone; pub mod plaid; -pub mod riskified; pub mod signifyd; pub mod stripe; pub mod threedsecureio; @@ -33,12 +30,13 @@ pub use hyperswitch_connectors::connectors::{ itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay, - nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, noon, - noon::Noon, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, - opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme, - paypal, paypal::Paypal, paystack, paystack::Paystack, payu, payu::Payu, placetopay, - placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, - rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, + nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, + nomupay::Nomupay, noon, noon::Noon, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, + opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, + payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paystack, + paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, + powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, + razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, trustpay, trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, @@ -51,6 +49,6 @@ pub use hyperswitch_connectors::connectors::{ pub use self::dummyconnector::DummyConnector; pub use self::{ adyenplatform::Adyenplatform, ebanx::Ebanx, gpayments::Gpayments, netcetera::Netcetera, - nmi::Nmi, payone::Payone, plaid::Plaid, riskified::Riskified, signifyd::Signifyd, - stripe::Stripe, threedsecureio::Threedsecureio, wellsfargopayout::Wellsfargopayout, wise::Wise, + plaid::Plaid, signifyd::Signifyd, stripe::Stripe, threedsecureio::Threedsecureio, + wellsfargopayout::Wellsfargopayout, wise::Wise, }; diff --git a/crates/router/src/connector/riskified/transformers/auth.rs b/crates/router/src/connector/riskified/transformers/auth.rs deleted file mode 100644 index 6968bb55a59..00000000000 --- a/crates/router/src/connector/riskified/transformers/auth.rs +++ /dev/null @@ -1,22 +0,0 @@ -use error_stack; -use masking::{ExposeInterface, Secret}; - -use crate::{core::errors, types}; - -pub struct RiskifiedAuthType { - pub secret_token: Secret<String>, - pub domain_name: String, -} - -impl TryFrom<&types::ConnectorAuthType> for RiskifiedAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - match auth_type { - types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - secret_token: api_key.to_owned(), - domain_name: key1.to_owned().expose(), - }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), - } - } -} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index afee6a42b14..cd2740d2803 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -225,9 +225,7 @@ default_imp_for_complete_authorize!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -265,10 +263,7 @@ default_imp_for_webhook_source_verification!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -308,10 +303,7 @@ default_imp_for_create_customer!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -352,9 +344,7 @@ default_imp_for_connector_redirect_response!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -377,10 +367,7 @@ default_imp_for_connector_request_id!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -423,10 +410,7 @@ default_imp_for_accept_dispute!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -488,10 +472,7 @@ default_imp_for_file_upload!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -530,10 +511,7 @@ default_imp_for_submit_evidence!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -572,10 +550,7 @@ default_imp_for_defend_dispute!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -630,9 +605,7 @@ default_imp_for_pre_processing_steps!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -654,13 +627,10 @@ impl<const T: u8> default_imp_for_post_processing_steps!( connector::Adyenplatform, - connector::Nmi, connector::Stripe, connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Payone, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -681,9 +651,7 @@ impl<const T: u8> Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( connector::Gpayments, connector::Netcetera, - connector::Nmi, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -721,10 +689,7 @@ default_imp_for_payouts_create!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -763,10 +728,7 @@ default_imp_for_payouts_retrieve!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -809,10 +771,7 @@ default_imp_for_payouts_eligibility!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -850,9 +809,7 @@ impl<const T: u8> default_imp_for_payouts_fulfill!( connector::Gpayments, connector::Netcetera, - connector::Nmi, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -890,10 +847,7 @@ default_imp_for_payouts_cancel!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -931,10 +885,7 @@ default_imp_for_payouts_quote!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -973,10 +924,7 @@ default_imp_for_payouts_recipient!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -1018,10 +966,7 @@ default_imp_for_payouts_recipient_account!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1060,10 +1005,7 @@ default_imp_for_approve!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1103,10 +1045,7 @@ default_imp_for_reject!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1131,9 +1070,7 @@ default_imp_for_fraud_check!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, - connector::Nmi, connector::Netcetera, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1175,8 +1112,6 @@ default_imp_for_frm_sale!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1218,8 +1153,6 @@ default_imp_for_frm_checkout!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1261,8 +1194,6 @@ default_imp_for_frm_transaction!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1304,8 +1235,6 @@ default_imp_for_frm_fulfillment!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1347,8 +1276,6 @@ default_imp_for_frm_record_return!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1388,10 +1315,7 @@ default_imp_for_incremental_authorization!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1429,10 +1353,7 @@ default_imp_for_revoking_mandates!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1528,10 +1449,7 @@ impl<const T: u8> default_imp_for_connector_authentication!( connector::Adyenplatform, connector::Ebanx, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Wellsfargopayout, @@ -1567,10 +1485,7 @@ default_imp_for_authorize_session_token!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1608,10 +1523,7 @@ default_imp_for_calculate_tax!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1649,10 +1561,7 @@ default_imp_for_session_update!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1690,10 +1599,7 @@ default_imp_for_post_session_tokens!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1731,10 +1637,7 @@ default_imp_for_update_metadata!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1774,10 +1677,7 @@ default_imp_for_uas_pre_authentication!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1815,10 +1715,7 @@ default_imp_for_uas_post_authentication!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1845,10 +1742,7 @@ default_imp_for_uas_authentication_confirmation!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1899,10 +1793,7 @@ default_imp_for_uas_authentication!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -2035,10 +1926,8 @@ default_imp_for_revenue_recovery! { connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, + connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -2080,10 +1969,7 @@ default_imp_for_billing_connector_payment_sync!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -2125,10 +2011,7 @@ default_imp_for_revenue_recovery_record_back!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs index 580ccb73f53..c6de30c8d0f 100644 --- a/crates/router/src/macros.rs +++ b/crates/router/src/macros.rs @@ -1,15 +1,5 @@ pub use common_utils::{collect_missing_value_keys, newtype}; -#[macro_export] -macro_rules! get_formatted_date_time { - ($date_format:tt) => {{ - let format = time::macros::format_description!($date_format); - time::OffsetDateTime::now_utc() - .format(&format) - .change_context($crate::core::errors::ConnectorError::InvalidDateFormat) - }}; -} - #[macro_export] macro_rules! get_payment_link_config_value_based_on_priority { ($config:expr, $business_config:expr, $field:ident, $default:expr) => {
2025-03-28T10:39:38Z
## Description <!-- Describe your changes in detail --> Moving connectors (NMI,Riskified,and payone) from `router` crate to `hyperswitch_connector` crate ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> # # NMI test ## Create payment processor NOTE: used 3ds enabled key ```json { "connector_type": "payment_processor", "connector_name": "nmi", "connector_account_details": { "api_key":"********************", "auth_type": "BodyKey", "key1": "***********************" }, "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" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" } ``` ## Create payment processor Response ```json { "connector_type": "payment_processor", "connector_name": "nmi", "connector_label": "nmi_US_default", "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "profile_id": "pro_5wu4McY9AIOVmllRswYz", "connector_account_details": { "auth_type": "BodyKey", "api_key": "***************************", "key1": "********************************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "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", "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": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, "metadata": { "city": "NY", "unit": "245" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` ## create payment ```json { "amount": 250, "currency": "USD", "confirm": true, "amount_to_capture": 250, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "nithin", "email": "[email protected]", "name": "John Doe", "phone": "9731918444", "phone_country_code": "+91", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "routing": { "type": "single", "data": "nmi" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4000000000002503", "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "999" } }, "billing": { "address": { "zip": "560095", "country": "IN", "first_name": "Sakil", "last_name": "Mostak" } } } ``` ## create payment response ```json { "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "merchant_id": "merchant_1743143179", "status": "requires_customer_action", "amount": 250, "net_amount": 250, "shipping_cost": null, "amount_capturable": 250, "amount_received": null, "connector": "nmi", "client_secret": "pay_9hrmW9oFfnKedAy0P3Mn_secret_gJqo6Tw0eee5XPrufvo1", "created": "2025-03-28T10:29:46.830Z", "currency": "USD", "customer_id": "johndoe", "customer": { "id": "johndoe", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+91" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_Qgf7HooZS0DBdeTuvyW2", "shipping": { "address": { "city": null, "country": "US", "line1": null, "line2": null, "line3": null, "zip": "94122", "state": null, "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": null, "country": "IN", "line1": null, "line2": null, "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_9hrmW9oFfnKedAy0P3Mn/merchant_1743143179/pay_9hrmW9oFfnKedAy0P3Mn_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "johndoe", "created_at": 1743157786, "expires": 1743161386, "secret": "epk_46f549a6894b47b5bb741de8aa1381b5" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "", "payment_link": null, "profile_id": "pro_5wu4McY9AIOVmllRswYz", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-28T10:44:46.830Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-28T10:29:48.266Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } ``` Open redirect url "http://localhost:8080/payments/redirect/pay_9hrmW9oFfnKedAy0P3Mn/merchant_1743143179/pay_9hrmW9oFfnKedAy0P3Mn_1" <img width="1680" alt="Screenshot 2025-03-28 at 4 01 28 PM" src="https://github.com/user-attachments/assets/075f5bd4-c04c-4927-83dd-744d64f8a59b" /> ## payment retrieve NOTE use `/payments/:id?force_sync=true` Response ```json { "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "merchant_id": "merchant_1743143179", "status": "succeeded", "amount": 250, "net_amount": 250, "shipping_cost": null, "amount_capturable": 0, "amount_received": 250, "connector": "nmi", "client_secret": "pay_9hrmW9oFfnKedAy0P3Mn_secret_gJqo6Tw0eee5XPrufvo1", "created": "2025-03-28T10:29:46.830Z", "currency": "USD", "customer_id": "johndoe", "customer": { "id": "johndoe", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+91" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_Qgf7HooZS0DBdeTuvyW2", "shipping": { "address": { "city": null, "country": "US", "line1": null, "line2": null, "line3": null, "zip": "94122", "state": null, "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": null, "country": "IN", "line1": null, "line2": null, "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "10550766500", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_9hrmW9oFfnKedAy0P3Mn_1", "payment_link": null, "profile_id": "pro_5wu4McY9AIOVmllRswYz", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-28T10:44:46.830Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-28T10:34:49.994Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } ``` ## refunds ```json "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "amount": 250, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Response ```json { "refund_id": "ref_rOGRIeo7mSWazFxB6TpF", "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "amount": 250, "currency": "USD", "status": "pending", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-03-28T10:36:26.792Z", "updated_at": "2025-03-28T10:36:29.898Z", "connector": "nmi", "profile_id": "pro_5wu4McY9AIOVmllRswYz", "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ## refund retrieve response ```json { "refund_id": "ref_rOGRIeo7mSWazFxB6TpF", "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "amount": 250, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-03-28T10:36:26.792Z", "updated_at": "2025-03-28T10:36:54.546Z", "connector": "nmi", "profile_id": "pro_5wu4McY9AIOVmllRswYz", "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` ********************************************** PAYONE ****************************** ## create connector ```json { "connector_type": "payout_processor", "connector_name": "payone", "connector_label": "adyen_payouts", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "*********************", "api_secret": "**********************", "key1": "Hyperswitch" }, "test_mode": true, "disabled": false, "metadata": { "city": "NY", "unit": "245", "endpoint_prefix": "" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "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": "credit", "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 } ] } ] } ``` ## create payouts ```json { "amount": 100, "currency": "EUR", "profile_id": {{profile_id}}, "customer": { "id": "new_id", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65" }, "connector": [ "payone" ], "description": "Its my first payout request", "payout_type": "card", "payout_method_data": { "card": { "card_number": "5137009801943438", "expiry_month": "03", "expiry_year": "2030", "card_holder_name": "John Doe" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "confirm": true, "auto_fulfill": true } ``` # RISKIFIED - Create a merchant with frm_routing_algorithm ```json "frm_routing_algorithm": { "type": "single", "data": "riskified" } ``` - create stripe MCA - create RISKIFIED MCA ```json { "connector_type": "payment_vas", "connector_name": "riskified", "connector_account_details": { "auth_type": "BodyKey", "api_key": "*************APIKEY", "key1": "www.juspay.com" }, "connector_webhook_details": { "merchant_secret": "**********************MERCHANT_SECRET", "additional_secret": null }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "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" }, "frm_configs": [ { "gateway": "stripe", "payment_methods": [ { "payment_method": "card", "flow" : "pre" } ] } ] } ``` - create a payment ```json { "amount": 1500000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1500000, "customer_id": "StripeCustomer2", "email": "[email protected]", "name": "Bob Smith", "phone": "999999999", "phone_country_code": "+91", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "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": "31 Sherwood Gardens", "line3": "31 Sherwood Gardens", "city": "London", "state": "Manchester", "zip": "E14 9wn", "country": "GB", "first_name": "Bob", "last_name": "Smith" }, "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" }, "order_details" : [{ "product_name" : "gillete creme", "quantity" : 2, "amount" : 600 }, { "product_name" : "gillete razor", "quantity" : 1, "amount" : 300 }], "frm_metadata": { "vendor_name": "srujan", "shipping_lines": [ ] } } ``` - payment message should contain `frm_message` from riskified ```json "frm_message": { "frm_name": "riskified", "frm_transaction_id": "pay_v2TLKee8Wlw84rC7IHsj_1", "frm_transaction_type": "pre_frm", "frm_status": "legit", "frm_score": null, "frm_reason": "Reviewed and approved by Riskified", "frm_error": null } ```
50cbe20ee1da0392f4f590bade9f866435356b87
[ "Cargo.lock", "crates/hyperswitch_connectors/Cargo.toml", "crates/hyperswitch_connectors/src/connectors.rs", "crates/router/src/connector/nmi.rs", "crates/router/src/connector/nmi/transformers.rs", "crates/router/src/connector/payone.rs", "crates/router/src/connector/payone/transformers.rs", "crates/router/src/connector/riskified.rs", "crates/router/src/connector/riskified/transformers.rs", "crates/router/src/connector/riskified/transformers/api.rs", "crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs", "crates/hyperswitch_connectors/src/default_implementations.rs", "crates/hyperswitch_connectors/src/default_implementations_v2.rs", "crates/hyperswitch_connectors/src/types.rs", "crates/hyperswitch_connectors/src/utils.rs", "crates/router/Cargo.toml", "crates/router/src/connector.rs", "crates/router/src/connector/riskified/transformers/auth.rs", "crates/router/src/core/payments/flows.rs", "crates/router/src/macros.rs", "crates/hyperswitch_connectors/src/connectors/nmi.rs", "crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs", "crates/hyperswitch_connectors/src/connectors/payone.rs", "crates/hyperswitch_connectors/src/connectors/payone/transformers.rs", "crates/hyperswitch_connectors/src/connectors/riskified.rs", "crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7664
Bug: Modify profile and merchant_connector_account routes to use `ApiKeyAuthWithMerchantIdFromRoute` auth Hotfix Description: Currently, the following routes use AdminApiAuthWithMerchantIdFromRoute for authentication: Profile Create, Retrieve, Update Merchant Connector Account Create, List, Retrieve, Update This has to be updated to a more appropriate auth layer: ApiKeyAuthWithMerchantIdFromRoute, which validates that the merchant_id in the API key matches the one in the route.
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 3cd959838a5..1c494542228 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -499,7 +499,7 @@ pub async fn connector_create( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, @@ -598,7 +598,7 @@ pub async fn connector_retrieve( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be ProfileConnectorRead, but since this API responds with @@ -716,7 +716,7 @@ pub async fn connector_list( merchant_id.to_owned(), |state, _auth, merchant_id, _| list_payment_connectors(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorRead, @@ -769,7 +769,7 @@ pub async fn connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::ProfileConnectorRead, @@ -830,7 +830,7 @@ pub async fn connector_update( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs index 1b98160546d..cd91275df71 100644 --- a/crates/router/src/routes/profiles.rs +++ b/crates/router/src/routes/profiles.rs @@ -29,7 +29,7 @@ pub async fn profile_create( create_profile(state, req, auth_data.merchant_account, auth_data.key_store) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountWrite, @@ -95,7 +95,7 @@ pub async fn profile_retrieve( profile_id, |state, auth_data, profile_id, _| retrieve_profile(state, profile_id, auth_data.key_store), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: permissions::Permission::ProfileAccountRead, @@ -158,7 +158,7 @@ pub async fn profile_update( json_payload.into_inner(), |state, auth_data, req, _| update_profile(state, &profile_id, auth_data.key_store, req), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), @@ -243,7 +243,7 @@ pub async fn profiles_list( merchant_id.clone(), |state, _auth, merchant_id, _| list_profile(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountRead, @@ -309,7 +309,7 @@ pub async fn profiles_list_at_profile_level( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileAccountRead, @@ -402,7 +402,7 @@ pub async fn payment_connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileConnectorRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 4eb91756661..7e3d6802b88 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -633,6 +633,137 @@ where } } +#[derive(Debug)] +pub struct ApiKeyAuthWithMerchantIdFromRoute(pub id_type::MerchantId); + +#[cfg(feature = "partial-auth")] +impl GetAuthType for ApiKeyAuthWithMerchantIdFromRoute { + fn get_auth_type(&self) -> detached::PayloadType { + detached::PayloadType::ApiKey + } +} + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuthWithMerchantIdFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let merchant_id_from_route = self.0.clone(); + 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 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_id = + get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? + .map(id_type::ProfileId::from_str) + .transpose() + .change_context(errors::ValidationError::IncorrectValueProvided { + field_name: "X-Profile-Id", + }) + .change_context(errors::ApiErrorResponse::Unauthorized)?; + + if merchant_id_from_route != stored_api_key.merchant_id { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Merchant ID from route and Merchant ID from api-key in header do not match", + ); + } + + 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 auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account, + key_store, + profile_id, + }; + Ok(( + auth.clone(), + AuthenticationType::ApiKey { + merchant_id: auth.merchant_account.get_id().clone(), + key_id: stored_api_key.key_id, + }, + )) + } +} + #[cfg(not(feature = "partial-auth"))] #[async_trait] impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I> diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index b6955c542a7..33f8907ce3f 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -310,7 +310,7 @@ Cypress.Commands.add( "businessProfileCreateCall", (businessProfileCreateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/profiles`; @@ -353,7 +353,7 @@ Cypress.Commands.add( ); Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); @@ -395,7 +395,7 @@ Cypress.Commands.add( "businessProfileUpdateCall", (businessProfileUpdateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId");
2025-03-28T09:12:40Z
## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7656](https://github.com/juspay/hyperswitch/pull/7656) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
df7daa611e069e027fbef90fd8d17e53a28d7580
[ "crates/router/src/routes/admin.rs", "crates/router/src/routes/profiles.rs", "crates/router/src/services/authentication.rs", "cypress-tests-v2/cypress/support/commands.js" ]
juspay/hyperswitch
juspay__hyperswitch-7661
Bug: feat(router): Support `card` in `payment_method_subtype` [V2] `payment_method_subtype` field needs to be made mandatory and `card` needs to be added as a supported enum variant. This is needed for parity with industry standard analytics hierarchy
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index de2cd1b0360..0b7da8463b9 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -15184,6 +15184,7 @@ "type": "object", "required": [ "payment_method_type", + "payment_method_subtype", "customer_id", "payment_method_data" ], @@ -15192,12 +15193,7 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], - "nullable": true + "$ref": "#/components/schemas/PaymentMethodType" }, "metadata": { "type": "object", @@ -16664,7 +16660,8 @@ "description": "Request for Payment Intent Confirm", "required": [ "payment_method_data", - "payment_method_type" + "payment_method_type", + "payment_method_subtype" ], "properties": { "return_url": { @@ -16680,12 +16677,7 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], - "nullable": true + "$ref": "#/components/schemas/PaymentMethodType" }, "shipping": { "allOf": [ @@ -17468,7 +17460,8 @@ "amount_details", "customer_id", "payment_method_data", - "payment_method_type" + "payment_method_type", + "payment_method_subtype" ], "properties": { "amount_details": { @@ -17660,12 +17653,7 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], - "nullable": true + "$ref": "#/components/schemas/PaymentMethodType" }, "customer_acceptance": { "allOf": [ diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 3590537a083..4313d224019 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -116,8 +116,8 @@ pub struct PaymentMethodCreate { pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. - #[schema(value_type = Option<PaymentMethodType>,example = "credit")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType,example = "google_pay")] + pub payment_method_subtype: api_enums::PaymentMethodType, /// 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. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] @@ -2806,8 +2806,8 @@ pub struct PaymentMethodSessionConfirmRequest { pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype - #[schema(value_type = PaymentMethodType, example = "credit")] - pub payment_method_subtype: Option<common_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType, example = "google_pay")] + pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment instrument data to be used for the payment #[schema(value_type = PaymentMethodDataRequest)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 3cfadb0a57c..a2d3090683f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5247,8 +5247,8 @@ pub struct PaymentsConfirmIntentRequest { pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided - #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType, example = "apple_pay")] + pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, @@ -5416,8 +5416,8 @@ pub struct PaymentsRequest { pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided - #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType, example = "apple_pay")] + pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] @@ -8506,7 +8506,7 @@ pub struct PaymentRevenueRecoveryMetadata { pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] - pub payment_method_subtype: Option<common_enums::PaymentMethodType>, + pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, @@ -8587,7 +8587,7 @@ pub struct PaymentsAttemptRecordRequest { /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index 5db5393644a..6f2d96a5838 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -11,6 +11,7 @@ license.workspace = true dummy_connector = [] openapi = [] payouts = [] +v2 = [] [dependencies] diesel = { version = "2.2.3", features = ["postgres", "128-column-tables"] } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 1697b1386c4..ca3968ed64d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1755,6 +1755,8 @@ pub enum PaymentMethodType { BcaBankTransfer, BniVa, BriVa, + #[cfg(feature = "v2")] + Card, CardRedirect, CimbVa, #[serde(rename = "classic")] @@ -1867,6 +1869,8 @@ impl PaymentMethodType { Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", + #[cfg(feature = "v2")] + Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 6ff3bad4add..2a130edbd84 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1815,6 +1815,8 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::CimbVa => Self::BankTransfer, PaymentMethodType::ClassicReward => Self::Reward, PaymentMethodType::Credit => Self::Card, + #[cfg(feature = "v2")] + PaymentMethodType::Card => Self::Card, PaymentMethodType::CryptoCurrency => Self::Crypto, PaymentMethodType::Dana => Self::Wallet, PaymentMethodType::DanamonVa => Self::BankTransfer, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 33b51ebdf9c..a3599fc1b47 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -91,7 +91,7 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, - pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, + pub payment_method_subtype: storage_enums::PaymentMethodType, pub routing_result: Option<serde_json::Value>, pub authentication_applied: Option<common_enums::AuthenticationType>, pub external_reference_id: Option<String>, @@ -322,7 +322,7 @@ pub struct PaymentAttemptNew { pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, - pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, + pub payment_method_subtype: storage_enums::PaymentMethodType, pub id: id_type::GlobalAttemptId, pub connector_token_details: Option<ConnectorTokenDetails>, pub card_discovery: Option<storage_enums::CardDiscovery>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4c07445f710..b89daa09698 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -878,7 +878,7 @@ diesel::table! { #[max_length = 128] connector_payment_id -> Nullable<Varchar>, #[max_length = 64] - payment_method_subtype -> Nullable<Varchar>, + payment_method_subtype -> Varchar, routing_result -> Nullable<Jsonb>, authentication_applied -> Nullable<AuthenticationType>, #[max_length = 128] diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index dc69c0a323a..2314d2bf4ca 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -63,7 +63,7 @@ impl FeatureMetadata { pub fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> { self.payment_revenue_recovery_metadata .as_ref() - .and_then(|val| val.payment_method_subtype) + .map(|rrm| rrm.payment_method_subtype) } pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> { @@ -168,7 +168,7 @@ pub struct PaymentRevenueRecoveryMetadata { ///Payment Method Type pub payment_method_type: common_enums::enums::PaymentMethod, /// PaymentMethod Subtype - pub payment_method_subtype: Option<common_enums::enums::PaymentMethodType>, + pub payment_method_subtype: common_enums::enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. pub connector: common_enums::connector_enums::Connector, } diff --git a/crates/euclid/Cargo.toml b/crates/euclid/Cargo.toml index 8f1320db234..a607531d87f 100644 --- a/crates/euclid/Cargo.toml +++ b/crates/euclid/Cargo.toml @@ -28,6 +28,7 @@ ast_parser = ["dep:nom"] valued_jit = [] dummy_connector = [] payouts = [] +v2 = ["common_enums/v2"] [dev-dependencies] criterion = "0.5" diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index ef7449e1c1b..2cf8301417c 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -27,6 +27,8 @@ pub use crate::enums::{PayoutBankTransferType, PayoutType, PayoutWalletType}; pub enum CardType { Credit, Debit, + #[cfg(feature = "v2")] + Card, } #[derive( diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index e58a6e28bdb..ace617fb365 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -16,6 +16,8 @@ impl From<enums::CardType> for global_enums::PaymentMethodType { match value { enums::CardType::Credit => Self::Credit, enums::CardType::Debit => Self::Debit, + #[cfg(feature = "v2")] + enums::CardType::Card => Self::Card, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index d85c23e2489..b4b512b5234 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -8,6 +8,8 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet match self.0 { global_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), global_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), + #[cfg(feature = "v2")] + global_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), global_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), global_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), global_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index 7550fc2677f..a9b23522516 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -163,6 +163,7 @@ impl ConnectorValidation for Adyen { let connector = self.id(); match pmt { Some(payment_method_type) => match payment_method_type { + #[cfg(feature = "v1")] PaymentMethodType::Affirm | PaymentMethodType::AfterpayClearpay | PaymentMethodType::ApplePay @@ -187,6 +188,32 @@ impl ConnectorValidation for Adyen { ) } }, + #[cfg(feature = "v2")] + PaymentMethodType::Affirm + | PaymentMethodType::AfterpayClearpay + | PaymentMethodType::ApplePay + | PaymentMethodType::Credit + | PaymentMethodType::Debit + | PaymentMethodType::Card + | PaymentMethodType::GooglePay + | PaymentMethodType::MobilePay + | PaymentMethodType::PayBright + | PaymentMethodType::Sepa + | PaymentMethodType::Vipps + | PaymentMethodType::Venmo + | PaymentMethodType::Paypal => match capture_method { + enums::CaptureMethod::Automatic + | enums::CaptureMethod::SequentialAutomatic + | enums::CaptureMethod::Manual + | enums::CaptureMethod::ManualMultiple => Ok(()), + enums::CaptureMethod::Scheduled => { + capture_method_not_supported!( + connector, + capture_method, + payment_method_type + ) + } + }, PaymentMethodType::Ach | PaymentMethodType::SamsungPay | PaymentMethodType::Paze diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index ba523fd6235..101a9b753ad 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -447,9 +447,8 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD let payment_method_details: ChargebeePaymentMethodDetails = serde_json::from_str(&item.content.transaction.payment_method_details) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - let payment_method_sub_type = Some(enums::PaymentMethodType::from( - payment_method_details.card.funding_type, - )); + let payment_method_sub_type = + enums::PaymentMethodType::from(payment_method_details.card.funding_type); Ok(Self { amount, currency, diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index bba7dd7e6ac..d2be42a1828 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -544,6 +544,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData ) => Ok(format!( "{endpoint}payments/v1/authorizations/{token}/order", )), + #[cfg(feature = "v1")] ( common_enums::PaymentExperience::DisplayQrCode | common_enums::PaymentExperience::DisplayWaitScreen @@ -656,6 +657,120 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData message: payment_method_type.to_string(), connector: "klarna", })), + #[cfg(feature = "v2")] + ( + common_enums::PaymentExperience::DisplayQrCode + | common_enums::PaymentExperience::DisplayWaitScreen + | common_enums::PaymentExperience::InvokePaymentApp + | common_enums::PaymentExperience::InvokeSdkClient + | common_enums::PaymentExperience::LinkWallet + | common_enums::PaymentExperience::OneClick + | common_enums::PaymentExperience::RedirectToUrl + | common_enums::PaymentExperience::CollectOtp, + common_enums::PaymentMethodType::Ach + | common_enums::PaymentMethodType::Affirm + | common_enums::PaymentMethodType::AfterpayClearpay + | common_enums::PaymentMethodType::Alfamart + | common_enums::PaymentMethodType::AliPay + | common_enums::PaymentMethodType::AliPayHk + | common_enums::PaymentMethodType::Alma + | common_enums::PaymentMethodType::AmazonPay + | common_enums::PaymentMethodType::ApplePay + | common_enums::PaymentMethodType::Atome + | common_enums::PaymentMethodType::Bacs + | common_enums::PaymentMethodType::BancontactCard + | common_enums::PaymentMethodType::Becs + | common_enums::PaymentMethodType::Benefit + | common_enums::PaymentMethodType::Bizum + | common_enums::PaymentMethodType::Blik + | common_enums::PaymentMethodType::Boleto + | common_enums::PaymentMethodType::BcaBankTransfer + | common_enums::PaymentMethodType::BniVa + | common_enums::PaymentMethodType::BriVa + | common_enums::PaymentMethodType::CardRedirect + | common_enums::PaymentMethodType::CimbVa + | common_enums::PaymentMethodType::ClassicReward + | common_enums::PaymentMethodType::Credit + | common_enums::PaymentMethodType::Card + | common_enums::PaymentMethodType::CryptoCurrency + | common_enums::PaymentMethodType::Cashapp + | common_enums::PaymentMethodType::Dana + | common_enums::PaymentMethodType::DanamonVa + | common_enums::PaymentMethodType::Debit + | common_enums::PaymentMethodType::DirectCarrierBilling + | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eft + | common_enums::PaymentMethodType::Eps + | common_enums::PaymentMethodType::Evoucher + | common_enums::PaymentMethodType::Giropay + | common_enums::PaymentMethodType::Givex + | common_enums::PaymentMethodType::GooglePay + | common_enums::PaymentMethodType::GoPay + | common_enums::PaymentMethodType::Gcash + | common_enums::PaymentMethodType::Ideal + | common_enums::PaymentMethodType::Interac + | common_enums::PaymentMethodType::Indomaret + | common_enums::PaymentMethodType::Klarna + | common_enums::PaymentMethodType::KakaoPay + | common_enums::PaymentMethodType::MandiriVa + | common_enums::PaymentMethodType::Knet + | common_enums::PaymentMethodType::MbWay + | common_enums::PaymentMethodType::MobilePay + | common_enums::PaymentMethodType::Momo + | common_enums::PaymentMethodType::MomoAtm + | common_enums::PaymentMethodType::Multibanco + | common_enums::PaymentMethodType::LocalBankRedirect + | common_enums::PaymentMethodType::OnlineBankingThailand + | common_enums::PaymentMethodType::OnlineBankingCzechRepublic + | common_enums::PaymentMethodType::OnlineBankingFinland + | common_enums::PaymentMethodType::OnlineBankingFpx + | common_enums::PaymentMethodType::OnlineBankingPoland + | common_enums::PaymentMethodType::OnlineBankingSlovakia + | common_enums::PaymentMethodType::Oxxo + | common_enums::PaymentMethodType::PagoEfectivo + | common_enums::PaymentMethodType::PermataBankTransfer + | common_enums::PaymentMethodType::OpenBankingUk + | common_enums::PaymentMethodType::PayBright + | common_enums::PaymentMethodType::Paypal + | common_enums::PaymentMethodType::Paze + | common_enums::PaymentMethodType::Pix + | common_enums::PaymentMethodType::PaySafeCard + | common_enums::PaymentMethodType::Przelewy24 + | common_enums::PaymentMethodType::Pse + | common_enums::PaymentMethodType::RedCompra + | common_enums::PaymentMethodType::RedPagos + | common_enums::PaymentMethodType::SamsungPay + | common_enums::PaymentMethodType::Sepa + | common_enums::PaymentMethodType::SepaBankTransfer + | common_enums::PaymentMethodType::Sofort + | common_enums::PaymentMethodType::Swish + | common_enums::PaymentMethodType::TouchNGo + | common_enums::PaymentMethodType::Trustly + | common_enums::PaymentMethodType::Twint + | common_enums::PaymentMethodType::UpiCollect + | common_enums::PaymentMethodType::UpiIntent + | common_enums::PaymentMethodType::Venmo + | common_enums::PaymentMethodType::Vipps + | common_enums::PaymentMethodType::Walley + | common_enums::PaymentMethodType::WeChatPay + | common_enums::PaymentMethodType::SevenEleven + | common_enums::PaymentMethodType::Lawson + | common_enums::PaymentMethodType::LocalBankTransfer + | common_enums::PaymentMethodType::InstantBankTransfer + | common_enums::PaymentMethodType::MiniStop + | common_enums::PaymentMethodType::FamilyMart + | common_enums::PaymentMethodType::Seicomart + | common_enums::PaymentMethodType::PayEasy + | common_enums::PaymentMethodType::Mifinity + | common_enums::PaymentMethodType::Fps + | common_enums::PaymentMethodType::DuitNow + | common_enums::PaymentMethodType::PromptPay + | common_enums::PaymentMethodType::VietQr + | common_enums::PaymentMethodType::OpenBankingPIS, + ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { + message: payment_method_type.to_string(), + connector: "klarna", + })), } } PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => { @@ -664,6 +779,120 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData common_enums::PaymentExperience::RedirectToUrl, common_enums::PaymentMethodType::Klarna, ) => Ok(format!("{endpoint}checkout/v3/orders",)), + #[cfg(feature = "v1")] + ( + common_enums::PaymentExperience::DisplayQrCode + | common_enums::PaymentExperience::DisplayWaitScreen + | common_enums::PaymentExperience::InvokePaymentApp + | common_enums::PaymentExperience::InvokeSdkClient + | common_enums::PaymentExperience::LinkWallet + | common_enums::PaymentExperience::OneClick + | common_enums::PaymentExperience::RedirectToUrl + | common_enums::PaymentExperience::CollectOtp, + common_enums::PaymentMethodType::Ach + | common_enums::PaymentMethodType::Affirm + | common_enums::PaymentMethodType::AfterpayClearpay + | common_enums::PaymentMethodType::Alfamart + | common_enums::PaymentMethodType::AliPay + | common_enums::PaymentMethodType::AliPayHk + | common_enums::PaymentMethodType::Alma + | common_enums::PaymentMethodType::AmazonPay + | common_enums::PaymentMethodType::ApplePay + | common_enums::PaymentMethodType::Atome + | common_enums::PaymentMethodType::Bacs + | common_enums::PaymentMethodType::BancontactCard + | common_enums::PaymentMethodType::Becs + | common_enums::PaymentMethodType::Benefit + | common_enums::PaymentMethodType::Bizum + | common_enums::PaymentMethodType::Blik + | common_enums::PaymentMethodType::Boleto + | common_enums::PaymentMethodType::BcaBankTransfer + | common_enums::PaymentMethodType::BniVa + | common_enums::PaymentMethodType::BriVa + | common_enums::PaymentMethodType::CardRedirect + | common_enums::PaymentMethodType::CimbVa + | common_enums::PaymentMethodType::ClassicReward + | common_enums::PaymentMethodType::Credit + | common_enums::PaymentMethodType::CryptoCurrency + | common_enums::PaymentMethodType::Cashapp + | common_enums::PaymentMethodType::Dana + | common_enums::PaymentMethodType::DanamonVa + | common_enums::PaymentMethodType::Debit + | common_enums::PaymentMethodType::DirectCarrierBilling + | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eft + | common_enums::PaymentMethodType::Eps + | common_enums::PaymentMethodType::Evoucher + | common_enums::PaymentMethodType::Giropay + | common_enums::PaymentMethodType::Givex + | common_enums::PaymentMethodType::GooglePay + | common_enums::PaymentMethodType::GoPay + | common_enums::PaymentMethodType::Gcash + | common_enums::PaymentMethodType::Ideal + | common_enums::PaymentMethodType::Interac + | common_enums::PaymentMethodType::Indomaret + | common_enums::PaymentMethodType::Klarna + | common_enums::PaymentMethodType::KakaoPay + | common_enums::PaymentMethodType::MandiriVa + | common_enums::PaymentMethodType::Knet + | common_enums::PaymentMethodType::MbWay + | common_enums::PaymentMethodType::MobilePay + | common_enums::PaymentMethodType::Momo + | common_enums::PaymentMethodType::MomoAtm + | common_enums::PaymentMethodType::Multibanco + | common_enums::PaymentMethodType::LocalBankRedirect + | common_enums::PaymentMethodType::OnlineBankingThailand + | common_enums::PaymentMethodType::OnlineBankingCzechRepublic + | common_enums::PaymentMethodType::OnlineBankingFinland + | common_enums::PaymentMethodType::OnlineBankingFpx + | common_enums::PaymentMethodType::OnlineBankingPoland + | common_enums::PaymentMethodType::OnlineBankingSlovakia + | common_enums::PaymentMethodType::Oxxo + | common_enums::PaymentMethodType::PagoEfectivo + | common_enums::PaymentMethodType::PermataBankTransfer + | common_enums::PaymentMethodType::OpenBankingUk + | common_enums::PaymentMethodType::PayBright + | common_enums::PaymentMethodType::Paypal + | common_enums::PaymentMethodType::Paze + | common_enums::PaymentMethodType::Pix + | common_enums::PaymentMethodType::PaySafeCard + | common_enums::PaymentMethodType::Przelewy24 + | common_enums::PaymentMethodType::Pse + | common_enums::PaymentMethodType::RedCompra + | common_enums::PaymentMethodType::RedPagos + | common_enums::PaymentMethodType::SamsungPay + | common_enums::PaymentMethodType::Sepa + | common_enums::PaymentMethodType::SepaBankTransfer + | common_enums::PaymentMethodType::Sofort + | common_enums::PaymentMethodType::Swish + | common_enums::PaymentMethodType::TouchNGo + | common_enums::PaymentMethodType::Trustly + | common_enums::PaymentMethodType::Twint + | common_enums::PaymentMethodType::UpiCollect + | common_enums::PaymentMethodType::UpiIntent + | common_enums::PaymentMethodType::Venmo + | common_enums::PaymentMethodType::Vipps + | common_enums::PaymentMethodType::Walley + | common_enums::PaymentMethodType::WeChatPay + | common_enums::PaymentMethodType::SevenEleven + | common_enums::PaymentMethodType::Lawson + | common_enums::PaymentMethodType::LocalBankTransfer + | common_enums::PaymentMethodType::InstantBankTransfer + | common_enums::PaymentMethodType::MiniStop + | common_enums::PaymentMethodType::FamilyMart + | common_enums::PaymentMethodType::Seicomart + | common_enums::PaymentMethodType::PayEasy + | common_enums::PaymentMethodType::Mifinity + | common_enums::PaymentMethodType::Fps + | common_enums::PaymentMethodType::DuitNow + | common_enums::PaymentMethodType::PromptPay + | common_enums::PaymentMethodType::VietQr + | common_enums::PaymentMethodType::OpenBankingPIS, + ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { + message: payment_method_type.to_string(), + connector: "klarna", + })), + #[cfg(feature = "v2")] ( common_enums::PaymentExperience::DisplayQrCode | common_enums::PaymentExperience::DisplayWaitScreen @@ -697,6 +926,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::CimbVa | common_enums::PaymentMethodType::ClassicReward | common_enums::PaymentMethodType::Credit + | common_enums::PaymentMethodType::Card | common_enums::PaymentMethodType::CryptoCurrency | common_enums::PaymentMethodType::Cashapp | common_enums::PaymentMethodType::Dana diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs index bc5d10620b7..fdee2022577 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs @@ -1117,11 +1117,20 @@ impl TryFrom<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for PaypalPayments )?; let payment_source = match payment_method_type { + #[cfg(feature = "v1")] enums::PaymentMethodType::Credit | enums::PaymentMethodType::Debit => Ok(Some( PaymentSourceItem::Card(CardRequest::CardVaultStruct(VaultStruct { vault_id: connector_mandate_id.into(), })), )), + #[cfg(feature = "v2")] + enums::PaymentMethodType::Credit + | enums::PaymentMethodType::Debit + | enums::PaymentMethodType::Card => Ok(Some(PaymentSourceItem::Card( + CardRequest::CardVaultStruct(VaultStruct { + vault_id: connector_mandate_id.into(), + }), + ))), enums::PaymentMethodType::Paypal => Ok(Some(PaymentSourceItem::Paypal( PaypalRedirectionRequest::PaypalVaultStruct(VaultStruct { vault_id: connector_mandate_id.into(), diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index dedba889c68..b0037ac45dc 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -288,7 +288,7 @@ impl AmountDetails { let order_tax_amount = match self.skip_external_tax_calculation { common_enums::TaxCalculationOverride::Skip => { self.tax_details.as_ref().and_then(|tax_details| { - tax_details.get_tax_amount(confirm_intent_request.payment_method_subtype) + tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype)) }) } common_enums::TaxCalculationOverride::Calculate => None, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index bff233c2588..d4d86641dc3 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -436,7 +436,7 @@ pub struct PaymentAttempt { /// The reference to the payment at the connector side pub connector_payment_id: Option<String>, /// The payment method subtype for the payment attempt. - pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, + pub payment_method_subtype: storage_enums::PaymentMethodType, /// The authentication type that was applied for the payment attempt. pub authentication_applied: Option<common_enums::AuthenticationType>, /// A reference to the payment at connector side. This is returned by the connector @@ -476,7 +476,7 @@ impl PaymentAttempt { #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { // TODO: check if we can fix this - self.payment_method_subtype + Some(self.payment_method_subtype) } #[cfg(feature = "v1")] @@ -660,7 +660,8 @@ impl PaymentAttempt { .unwrap_or(common_enums::PaymentMethod::Card), payment_method_id: None, connector_payment_id: None, - payment_method_subtype: payment_method_subtype_data, + payment_method_subtype: payment_method_subtype_data + .unwrap_or(common_enums::PaymentMethodType::Credit), authentication_applied: None, external_reference_id: None, payment_method_billing_address, diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 3acfdc28505..24f8a919ea8 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -33,7 +33,7 @@ pub struct RevenueRecoveryAttemptData { /// payment method of payment attempt. pub payment_method_type: common_enums::PaymentMethod, /// payment method sub type of the payment attempt. - pub payment_method_sub_type: Option<common_enums::PaymentMethodType>, + pub payment_method_sub_type: common_enums::PaymentMethodType, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. @@ -226,7 +226,7 @@ impl From<&BillingConnectorPaymentsSyncResponse> for RevenueRecoveryAttemptData transaction_created_at: data.transaction_created_at, status: data.status, payment_method_type: data.payment_method_type, - payment_method_sub_type: Some(data.payment_method_sub_type), + payment_method_sub_type: data.payment_method_sub_type, network_advice_code: None, network_decline_code: None, network_error_message: None, diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index ac14087c080..6e58f031718 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -9,7 +9,7 @@ license.workspace = true [features] dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector"] v1 = ["api_models/v1", "common_utils/v1", "common_types/v1"] -v2 = ["api_models/v2", "common_utils/v2", "common_types/v2"] +v2 = ["api_models/v2", "common_utils/v2", "common_types/v2", "common_enums/v2"] [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index abaa9df5633..64b79d1563e 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -24,6 +24,8 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), + #[cfg(feature = "v2")] + api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 14ff7284536..93e4f8e0408 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -133,6 +133,8 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), + #[cfg(feature = "v2")] + api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 548a24b8e32..0eae31ace87 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,7 +33,7 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] -v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","refunds_v2","scheduler/v2"] +v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","refunds_v2","scheduler/v2","euclid/v2"] v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1","scheduler/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 183ed6adde5..14dc0ec3625 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -691,6 +691,8 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { match value { enums::PaymentMethodType::Credit => Ok(Self::Card), enums::PaymentMethodType::Debit => Ok(Self::Card), + #[cfg(feature = "v2")] + enums::PaymentMethodType::Card => Ok(Self::Card), enums::PaymentMethodType::Klarna => Ok(Self::Klarna), enums::PaymentMethodType::Affirm => Ok(Self::Affirm), enums::PaymentMethodType::AfterpayClearpay => Ok(Self::AfterpayClearpay), diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index b8fe4e83625..52973805d34 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -713,7 +713,7 @@ pub async fn retrieve_payment_method_with_token( pub(crate) fn get_payment_method_create_request( payment_method_data: &api_models::payments::PaymentMethodData, payment_method_type: storage_enums::PaymentMethod, - payment_method_subtype: Option<storage_enums::PaymentMethodType>, + payment_method_subtype: storage_enums::PaymentMethodType, customer_id: id_type::GlobalCustomerId, billing_address: Option<&api_models::payments::Address>, payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>, @@ -977,7 +977,7 @@ pub async fn create_payment_method_core( None, network_tokenization_resp, Some(req.payment_method_type), - req.payment_method_subtype, + Some(req.payment_method_subtype), ) .await .attach_printable("Unable to create Payment method data")?; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 0173d36cc45..889525ec6d5 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -244,7 +244,7 @@ pub fn make_dsl_input( }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type), - payment_method_type: payments_dsl_input.payment_attempt.payment_method_subtype, + payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype), card_network: payments_dsl_input .payment_method_data .as_ref() diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index eb5b3d88173..20f502521fe 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -284,7 +284,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( session_token: None, enrolled_for_3ds: true, related_transaction_id: None, - payment_method_type: payment_data.payment_attempt.payment_method_subtype, + payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), router_return_url: Some(router_return_url), webhook_url, complete_authorize_url, @@ -607,7 +607,7 @@ pub async fn construct_router_data_for_psync<'a>( capture_method: Some(payment_intent.capture_method), connector_meta: attempt.connector_metadata.clone().expose_option(), sync_type: types::SyncRequestType::SinglePaymentSync, - payment_method_type: attempt.payment_method_subtype, + payment_method_type: Some(attempt.payment_method_subtype), currency: payment_intent.amount_details.currency, // TODO: Get the charges object from feature metadata split_payments: None, @@ -948,7 +948,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( email, customer_name: None, return_url: Some(router_return_url), - payment_method_type: payment_data.payment_attempt.payment_method_subtype, + payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), request_incremental_authorization: matches!( payment_data .payment_intent @@ -1666,7 +1666,7 @@ where created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), - payment_method_subtype: payment_attempt.payment_method_subtype, + payment_method_subtype: Some(payment_attempt.payment_method_subtype), next_action, connector_transaction_id: payment_attempt.connector_payment_id.clone(), connector_reference_id: None, @@ -1770,7 +1770,7 @@ where payment_method_subtype: self .payment_attempt .as_ref() - .and_then(|attempt| attempt.payment_method_subtype), + .map(|attempt| attempt.payment_method_subtype), connector_transaction_id: self .payment_attempt .as_ref() @@ -2897,7 +2897,7 @@ impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> )), created: pi.created_at, payment_method_type: pa.as_ref().and_then(|p| p.payment_method_type.into()), - payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype), + payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype.into()), connector: pa.as_ref().and_then(|p| p.connector.clone()), merchant_connector_id: pa.as_ref().and_then(|p| p.merchant_connector_id.clone()), customer: None, diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 1465629914d..dc2118efc28 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -401,7 +401,7 @@ impl Action { merchant_reference_id, amount: payment_attempt.get_total_amount(), currency: payment_intent.amount_details.currency, - payment_method_type: payment_attempt.payment_method_subtype, + payment_method_type: Some(payment_attempt.payment_method_subtype), attempt_status: payment_attempt.status, connector_transaction_id: payment_attempt .connector_payment_id diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 4c925b9d467..9c5030a30a0 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -69,15 +69,10 @@ impl PaymentMethodCreateExt for PaymentMethodCreate { impl PaymentMethodCreateExt for PaymentMethodCreate { fn validate(&self) -> RouterResult<()> { utils::when( - !self - .payment_method_subtype - .map(|sub| { - validate_payment_method_type_against_payment_method( - self.payment_method_type, - sub, - ) - }) - .unwrap_or(true), // If payment_method_subtype is None, we assume it to be valid + !validate_payment_method_type_against_payment_method( + self.payment_method_type, + self.payment_method_subtype, + ), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_type' provided".to_string() diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c11751c8324..6d529b12809 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -532,6 +532,8 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { Self::Card } + #[cfg(feature = "v2")] + api_enums::PaymentMethodType::Card => Self::Card, api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward => Self::Reward, api_enums::PaymentMethodType::Boleto diff --git a/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/down.sql b/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/down.sql new file mode 100644 index 00000000000..8022b979316 --- /dev/null +++ b/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype DROP NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/up.sql b/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/up.sql new file mode 100644 index 00000000000..36985b01119 --- /dev/null +++ b/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype SET NOT NULL; \ No newline at end of file
2025-03-28T07:23:53Z
## Description <!-- Describe your changes in detail --> - Made `payment_method_subtype` mandatory in API endpoints and `payment_attempt` table - Added `card` as an enum variant to `payment_method_subtype` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #7661 #
bd32dd4f0f259336f004a2358a7771652a3c6689
1 a. Payments Confirm: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195dc22c8487020a9f9ac8bdd908444/confirm-intent' \ --header 'x-client-secret: 12345_pay_0195dc22c8487020a9f9ac8bdd908444_secret_0195dc22c85a7fd1abafa610be7e4283' \ --header 'x-profile-id: pro_6OCXkR6tTttf6LSf4QgA' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_a04e14a10c8248e39702ce55495f6f37' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "card" }' ``` 1 b. Response: ```json { "id": "12345_pay_0195dc22c8487020a9f9ac8bdd908444", "status": "requires_capture", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 100, "amount_captured": 0 }, "customer_id": null, "connector": "stripe", "client_secret": "12345_pay_0195dc22c8487020a9f9ac8bdd908444_secret_0195dc22c85a7fd1abafa610be7e4283", "created": "2025-03-28T09:43:41.914Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "card", "connector_transaction_id": "pi_3R7ZSCD5R7gDAGff1GOVPQmk", "connector_reference_id": null, "merchant_connector_id": "mca_0ipbZpwoLJD7mvBnOfRc", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1R7ZSCD5R7gDAGff0PF9Bz36", "connector_token_request_reference_id": "W8rKh8W3jxvCYXJsgx" }, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` 2 a. MCA Create: ``` curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: cloth_seller_7TzDJFNeUNemd0txXfdx' \ --header 'x-profile-id: pro_6OCXkR6tTttf6LSf4QgA' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "REDACTED" }, "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtypes": [ { "payment_method_subtype": "card_redirect", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method_type": "card", "payment_method_subtypes": [ { "payment_method_subtype": "card", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_subtype": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, ... ] } ], "metadata": { "status_url": "https://2753-2401-4900-1cb8-2ff9-24dd-1ccf-ed12-b464.in.ngrok.io/webhooks/merchant_1678699058/globalpay", "account_name": "transaction_processing", "pricing_type": "fixed_price", "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" }, "frm_configs": null, "connector_webhook_details": { "merchant_secret": "" }, "profile_id": "pro_6OCXkR6tTttf6LSf4QgA" }' ``` 2 b. Response: ```json { "connector_type": "payment_processor", "connector_name": "stripe", "connector_label": "stripe_business", "id": "mca_0ipbZpwoLJD7mvBnOfRc", "profile_id": "pro_6OCXkR6tTttf6LSf4QgA", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "REDACTED" }, "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtypes": [ { "payment_method_subtype": "card_redirect", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method_type": "card", "payment_method_subtypes": [ { "payment_method_subtype": "card", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_subtype": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, ... ], "connector_webhook_details": { "merchant_secret": "", "additional_secret": null }, "metadata": { "status_url": "https://2753-2401-4900-1cb8-2ff9-24dd-1ccf-ed12-b464.in.ngrok.io/webhooks/merchant_1678699058/globalpay", "account_name": "transaction_processing", "acquirer_bin": "438309", "pricing_type": "fixed_price", "acquirer_merchant_id": "00002000000" }, "disabled": false, "frm_configs": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null, "feature_metadata": null } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payment_methods.rs", "crates/api_models/src/payments.rs", "crates/common_enums/Cargo.toml", "crates/common_enums/src/enums.rs", "crates/common_enums/src/transformers.rs", "crates/diesel_models/src/payment_attempt.rs", "crates/diesel_models/src/schema_v2.rs", "crates/diesel_models/src/types.rs", "crates/euclid/Cargo.toml", "crates/euclid/src/frontend/dir/enums.rs", "crates/euclid/src/frontend/dir/lowering.rs", "crates/euclid/src/frontend/dir/transformers.rs", "crates/hyperswitch_connectors/src/connectors/adyen.rs", "crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs", "crates/hyperswitch_connectors/src/connectors/klarna.rs", "crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs", "crates/hyperswitch_domain_models/src/revenue_recovery.rs", "crates/kgraph_utils/Cargo.toml", "crates/kgraph_utils/src/mca.rs", "crates/kgraph_utils/src/transformers.rs", "crates/router/Cargo.toml", "crates/router/src/connector/stripe/transformers.rs", "crates/router/src/core/payment_methods.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/core/revenue_recovery/types.rs", "crates/router/src/types/api/payment_methods.rs", "crates/router/src/types/transformers.rs", "v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/down.sql", "v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7658
Bug: Modify profile and merchant_connector_account routes to use `ApiKeyAuthWithMerchantIdFromRoute` auth ### Description: Currently, the following routes use `AdminApiAuthWithMerchantIdFromRoute` for authentication: - Profile Create, Retrieve, Update - Merchant Connector Account Create, List, Retrieve, Update This has to be updated to a more appropriate auth layer: `ApiKeyAuthWithMerchantIdFromRoute`, which validates that the `merchant_id` in the API key matches the one in the route.
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 3cd959838a5..1c494542228 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -499,7 +499,7 @@ pub async fn connector_create( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, @@ -598,7 +598,7 @@ pub async fn connector_retrieve( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be ProfileConnectorRead, but since this API responds with @@ -716,7 +716,7 @@ pub async fn connector_list( merchant_id.to_owned(), |state, _auth, merchant_id, _| list_payment_connectors(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorRead, @@ -769,7 +769,7 @@ pub async fn connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::ProfileConnectorRead, @@ -830,7 +830,7 @@ pub async fn connector_update( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs index 1b98160546d..cd91275df71 100644 --- a/crates/router/src/routes/profiles.rs +++ b/crates/router/src/routes/profiles.rs @@ -29,7 +29,7 @@ pub async fn profile_create( create_profile(state, req, auth_data.merchant_account, auth_data.key_store) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountWrite, @@ -95,7 +95,7 @@ pub async fn profile_retrieve( profile_id, |state, auth_data, profile_id, _| retrieve_profile(state, profile_id, auth_data.key_store), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: permissions::Permission::ProfileAccountRead, @@ -158,7 +158,7 @@ pub async fn profile_update( json_payload.into_inner(), |state, auth_data, req, _| update_profile(state, &profile_id, auth_data.key_store, req), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), @@ -243,7 +243,7 @@ pub async fn profiles_list( merchant_id.clone(), |state, _auth, merchant_id, _| list_profile(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountRead, @@ -309,7 +309,7 @@ pub async fn profiles_list_at_profile_level( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileAccountRead, @@ -402,7 +402,7 @@ pub async fn payment_connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileConnectorRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 4eb91756661..7e3d6802b88 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -633,6 +633,137 @@ where } } +#[derive(Debug)] +pub struct ApiKeyAuthWithMerchantIdFromRoute(pub id_type::MerchantId); + +#[cfg(feature = "partial-auth")] +impl GetAuthType for ApiKeyAuthWithMerchantIdFromRoute { + fn get_auth_type(&self) -> detached::PayloadType { + detached::PayloadType::ApiKey + } +} + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuthWithMerchantIdFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let merchant_id_from_route = self.0.clone(); + 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 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_id = + get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? + .map(id_type::ProfileId::from_str) + .transpose() + .change_context(errors::ValidationError::IncorrectValueProvided { + field_name: "X-Profile-Id", + }) + .change_context(errors::ApiErrorResponse::Unauthorized)?; + + if merchant_id_from_route != stored_api_key.merchant_id { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Merchant ID from route and Merchant ID from api-key in header do not match", + ); + } + + 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 auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account, + key_store, + profile_id, + }; + Ok(( + auth.clone(), + AuthenticationType::ApiKey { + merchant_id: auth.merchant_account.get_id().clone(), + key_id: stored_api_key.key_id, + }, + )) + } +} + #[cfg(not(feature = "partial-auth"))] #[async_trait] impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I> diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index b6955c542a7..33f8907ce3f 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -310,7 +310,7 @@ Cypress.Commands.add( "businessProfileCreateCall", (businessProfileCreateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/profiles`; @@ -353,7 +353,7 @@ Cypress.Commands.add( ); Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); @@ -395,7 +395,7 @@ Cypress.Commands.add( "businessProfileUpdateCall", (businessProfileUpdateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId");
2025-03-27T11:52:47Z
## Description <!-- Describe your changes in detail --> Currently, the following routes use `AdminApiAuthWithMerchantIdFromRoute` for authentication: - Profile Create, Retrieve, Update - Merchant Connector Account Create, List, Retrieve, Update This is being updated to a more appropriate auth layer: `ApiKeyAuthWithMerchantIdFromRoute`, which validates that the `merchant_id` in the API key matches the one in the route. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> These routes are profile and merchant-specific and can be accessed using the merchant's API key, # ### Business Profile Create: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' \ --data '{ "profile_name": "final-test" }' ``` ### Business Profile Retrieve: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile/pro_DaWH06Gvj0uyHu5TIzo9' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' ``` ### Business Profile Update: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile/pro_r4qhkx1sVFsohrVEKuu2' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' \ --data '{ "profile_name": "test-profile-auth2" }' ``` ### Business Profile List: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' ``` ### Merchant Connector Account Create ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' \ --data '{ "connector_type": "payment_processor", "profile_id": "pro_diCodYSThA3xAuDZ2rKV", "connector_name": "paypal_test", "connector_label": "paypal_test_default4", "disabled": false, "test_mode": true, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": {}, "connector_account_details": { "api_key": "test_key", "auth_type": "HeaderKey" }, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": null }' ``` ### Merchant Connector Account Retrieve ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors/mca_zAKHkuRqGOnduBqTHzlO' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ``` ### Merchant Connector Account Update ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors/mca_zAKHkuRqGOnduBqTHzlO' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' \ --data '{ "connector_type": "payment_processor", "connector_label": "paypal_test_default2", "disabled": false, "test_mode": true, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": {}, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": null }' ``` ### Merchant Connector Account List: ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ``` ### Merchant Connector Account Profile List: ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/profile/connectors' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ```
f3d6b15a2ade7dd98fec59777301f44d166f3be3
Folowing are the endpoints which are changed: ### Business Profile Create: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' \ --data '{ "profile_name": "final-test" }' ``` ### Business Profile Retrieve: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile/pro_DaWH06Gvj0uyHu5TIzo9' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' ``` ### Business Profile Update: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile/pro_r4qhkx1sVFsohrVEKuu2' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' \ --data '{ "profile_name": "test-profile-auth2" }' ``` ### Business Profile List: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' ``` ### Merchant Connector Account Create ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' \ --data '{ "connector_type": "payment_processor", "profile_id": "pro_diCodYSThA3xAuDZ2rKV", "connector_name": "paypal_test", "connector_label": "paypal_test_default4", "disabled": false, "test_mode": true, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": {}, "connector_account_details": { "api_key": "test_key", "auth_type": "HeaderKey" }, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": null }' ``` ### Merchant Connector Account Retrieve ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors/mca_zAKHkuRqGOnduBqTHzlO' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ``` ### Merchant Connector Account Update ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors/mca_zAKHkuRqGOnduBqTHzlO' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' \ --data '{ "connector_type": "payment_processor", "connector_label": "paypal_test_default2", "disabled": false, "test_mode": true, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": {}, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": null }' ``` ### Merchant Connector Account List: ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ``` ### Merchant Connector Account Profile List: ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/profile/connectors' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ```
[ "crates/router/src/routes/admin.rs", "crates/router/src/routes/profiles.rs", "crates/router/src/services/authentication.rs", "cypress-tests-v2/cypress/support/commands.js" ]
juspay/hyperswitch
juspay__hyperswitch-7646
Bug: feat: remove client_secret from payment_intents and update related code Change how client secret is made in Create Payment Intent Old `{Payment_id}_secret_{Secret}` `eg : pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo` New `cs_{Secret}` `eg: cs_0195d2be95ba7ef1a05066e163295562`
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index de2cd1b0360..27936b2917c 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -17102,7 +17102,7 @@ "client_secret": { "type": "string", "description": "It's a token used for client side verification.", - "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo" + "example": "cs_0195b34da95d75239c6a4bf514458896" }, "profile_id": { "type": "string", @@ -17699,7 +17699,6 @@ "status", "amount", "customer_id", - "client_secret", "created" ], "properties": { @@ -17729,10 +17728,6 @@ "example": "stripe", "nullable": true }, - "client_secret": { - "type": "string", - "description": "It's a token used for client side verification." - }, "created": { "type": "string", "format": "date-time", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 3cfadb0a57c..1a07a18f336 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -480,8 +480,8 @@ pub struct PaymentsIntentResponse { pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. - #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] - pub client_secret: common_utils::types::ClientSecret, + #[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")] + pub client_secret: Option<Secret<String>>, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] @@ -5576,10 +5576,6 @@ pub struct PaymentsResponse { #[schema(example = "stripe")] pub connector: Option<String>, - /// It's a token used for client side verification. - #[schema(value_type = String)] - pub client_secret: common_utils::types::ClientSecret, - /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] 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 5de836cd486..22ac0d4c0a4 100644 --- a/crates/common_utils/src/id_type/global_id/payment.rs +++ b/crates/common_utils/src/id_type/global_id/payment.rs @@ -28,11 +28,6 @@ impl GlobalPaymentId { 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()) - } - /// Generate the id for revenue recovery Execute PT workflow pub fn get_execute_revenue_recovery_id( &self, diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 11c9b17fae6..b9d245d48ce 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -686,261 +686,6 @@ where } } -#[cfg(feature = "v2")] -pub use client_secret_type::ClientSecret; -#[cfg(feature = "v2")] -mod client_secret_type { - use std::fmt; - - use masking::PeekInterface; - use router_env::logger; - - use super::*; - use crate::id_type; - - /// A domain type that can be used to represent a client secret - /// Client secret is generated for a payment and is used to authenticate the client side api calls - #[derive(Debug, PartialEq, Clone, AsExpression)] - #[diesel(sql_type = sql_types::Text)] - pub struct ClientSecret { - /// The payment id of the payment - pub payment_id: id_type::GlobalPaymentId, - /// The secret string - pub secret: masking::Secret<String>, - } - - impl ClientSecret { - pub(crate) fn get_string_repr(&self) -> String { - format!( - "{}_secret_{}", - self.payment_id.get_string_repr(), - 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 FromStr for ClientSecret { - type Err = ParsingError; - - fn from_str(str_value: &str) -> Result<Self, Self::Err> { - let (payment_id, secret) = - str_value - .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()), - }) - } - } - - impl<'de> Deserialize<'de> for ClientSecret { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - struct ClientSecretVisitor; - - impl Visitor<'_> for ClientSecretVisitor { - type Value = ClientSecret; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("a string in the format '{payment_id}_secret_{secret}'") - } - - fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E> - where - E: serde::de::Error, - { - let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| { - E::invalid_value( - serde::de::Unexpected::Str(value), - &"a string with '_secret_'", - ) - })?; - - let payment_id = - id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) - .map_err(serde::de::Error::custom)?; - - Ok(ClientSecret { - payment_id, - secret: masking::Secret::new(secret.to_owned()), - }) - } - } - - deserializer.deserialize_str(ClientSecretVisitor) - } - } - - impl Serialize for ClientSecret { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: serde::ser::Serializer, - { - serializer.serialize_str(self.get_string_repr().as_str()) - } - } - - impl ToSql<sql_types::Text, diesel::pg::Pg> for ClientSecret - where - String: ToSql<sql_types::Text, diesel::pg::Pg>, - { - fn to_sql<'b>( - &'b self, - out: &mut Output<'b, '_, diesel::pg::Pg>, - ) -> diesel::serialize::Result { - let string_repr = self.get_string_repr(); - <String as ToSql<sql_types::Text, diesel::pg::Pg>>::to_sql( - &string_repr, - &mut out.reborrow(), - ) - } - } - - impl<DB> FromSql<sql_types::Text, DB> for ClientSecret - where - DB: Backend, - String: FromSql<sql_types::Text, DB>, - { - fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { - let string_repr = String::from_sql(value)?; - 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()), - }) - } - } - - impl<DB> Queryable<sql_types::Text, DB> for ClientSecret - where - DB: Backend, - Self: FromSql<sql_types::Text, DB>, - { - type Row = Self; - - fn build(row: Self::Row) -> deserialize::Result<Self> { - Ok(row) - } - } - crate::impl_serializable_secret_id_type!(ClientSecret); - #[cfg(test)] - mod client_secret_tests { - #![allow(clippy::expect_used)] - #![allow(clippy::unwrap_used)] - - use serde_json; - - use super::*; - use crate::id_type::GlobalPaymentId; - - #[test] - fn test_serialize_client_secret() { - let global_payment_id = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - let secret = "fc34taHLw1ekPgNh92qr".to_string(); - - let expected_client_secret_string = format!("\"{global_payment_id}_secret_{secret}\""); - - let client_secret1 = ClientSecret { - payment_id: GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id)).unwrap(), - secret: masking::Secret::new(secret), - }; - - let parsed_client_secret = - serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1"); - - assert_eq!(expected_client_secret_string, parsed_client_secret); - } - - #[test] - fn test_deserialize_client_secret() { - // This is a valid global id - let global_payment_id_str = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - let secret = "fc34taHLw1ekPgNh92qr".to_string(); - - let valid_payment_global_id = - GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id_str)) - .expect("Failed to create valid global payment id"); - - // This is an invalid global id because of the cell id being in invalid length - let invalid_global_payment_id = "123_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - - // Create a client secret string which is valid - let valid_client_secret = format!(r#""{global_payment_id_str}_secret_{secret}""#); - - dbg!(&valid_client_secret); - - // Create a client secret string which is invalid - let invalid_client_secret_because_of_invalid_payment_id = - format!(r#""{invalid_global_payment_id}_secret_{secret}""#); - - // Create a client secret string which is invalid because of invalid secret - let invalid_client_secret_because_of_invalid_secret = - format!(r#""{invalid_global_payment_id}""#); - - let valid_client_secret = serde_json::from_str::<ClientSecret>(&valid_client_secret) - .expect("Failed to deserialize client_secret_str1"); - - let invalid_deser1 = serde_json::from_str::<ClientSecret>( - &invalid_client_secret_because_of_invalid_payment_id, - ); - - dbg!(&invalid_deser1); - - let invalid_deser2 = serde_json::from_str::<ClientSecret>( - &invalid_client_secret_because_of_invalid_secret, - ); - - dbg!(&invalid_deser2); - - assert_eq!(valid_client_secret.payment_id, valid_payment_global_id); - - assert_eq!(valid_client_secret.secret.peek(), &secret); - - assert_eq!( - invalid_deser1.err().unwrap().to_string(), - "Incorrect value provided for field: payment_id at line 1 column 70" - ); - - assert_eq!( - invalid_deser2.err().unwrap().to_string(), - "invalid value: string \"123_pay_1a961ed9093c48b09781bf8ab17ba6bd\", expected a string with '_secret_' at line 1 column 42" - ); - } - } -} - /// A type representing a range of time for filtering, including a mandatory start time and an optional end time. #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 6753afc2d99..5034873e7ac 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -33,7 +33,6 @@ pub struct PaymentIntent { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, @@ -290,7 +289,6 @@ pub struct PaymentIntentNew { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4c07445f710..9b16f56f350 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -921,8 +921,6 @@ diesel::table! { modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, - #[max_length = 128] - client_secret -> Varchar, #[max_length = 64] active_attempt_id -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index dedba889c68..7f757c64a72 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -403,8 +403,6 @@ pub struct PaymentIntent { #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, 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_id: Option<id_type::GlobalAttemptId>, /// The order details for the payment. @@ -526,22 +524,6 @@ impl PaymentIntent { .unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default())) } - /// Check if the client secret is associated with the payment and if it has been expired - pub fn validate_client_secret( - &self, - client_secret: &common_utils::types::ClientSecret, - ) -> Result<(), errors::api_error_response::ApiErrorResponse> { - common_utils::fp_utils::when(self.client_secret != *client_secret, || { - Err(errors::api_error_response::ApiErrorResponse::ClientSecretInvalid) - })?; - - common_utils::fp_utils::when(self.session_expiry < common_utils::date_time::now(), || { - Err(errors::api_error_response::ApiErrorResponse::ClientSecretExpired) - })?; - - Ok(()) - } - pub async fn create_domain_model_from_request( payment_id: &id_type::GlobalPaymentId, merchant_account: &merchant_account::MerchantAccount, @@ -566,7 +548,6 @@ impl PaymentIntent { .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() @@ -589,7 +570,6 @@ impl PaymentIntent { modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: request.setup_future_usage.unwrap_or_default(), - client_secret, active_attempt_id: None, order_details, allowed_payment_method_types, @@ -704,7 +684,6 @@ pub struct HeaderPayload { pub locale: Option<String>, pub x_app_id: Option<String>, pub x_redirect_uri: Option<String>, - pub client_secret: Option<common_utils::types::ClientSecret>, } impl HeaderPayload { @@ -725,6 +704,7 @@ where pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub sessions_token: Vec<SessionToken>, + pub client_secret: Option<Secret<String>>, } // TODO: Check if this can be merged with existing payment data diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 13452649447..9b429f462e4 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1561,7 +1561,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at, last_synced, setup_future_usage, - client_secret, active_attempt_id, order_details, allowed_payment_method_types, @@ -1611,7 +1610,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at, last_synced, setup_future_usage: Some(setup_future_usage), - client_secret, active_attempt_id, order_details: order_details.map(|order_details| { order_details @@ -1760,7 +1758,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(), - client_secret: storage_model.client_secret, active_attempt_id: storage_model.active_attempt_id, order_details: storage_model.order_details.map(|order_details| { order_details @@ -1836,7 +1833,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at: self.modified_at, last_synced: self.last_synced, setup_future_usage: Some(self.setup_future_usage), - client_secret: self.client_secret, active_attempt_id: self.active_attempt_id, order_details: self.order_details, allowed_payment_method_types: self diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index cd68709afa4..e13bf290bec 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2041,9 +2041,6 @@ pub(crate) async fn payments_create_and_confirm_intent( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; - // Adding client secret to ensure client secret validation passes during confirm intent step - header_payload.client_secret = Some(create_intent_response.client_secret.clone()); - let payload = payments_api::PaymentsConfirmIntentRequest::from(&request); let confirm_intent_response = decide_authorize_or_setup_intent_flow( @@ -8013,6 +8010,8 @@ impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; fn get_payment_intent(&self) -> &storage::PaymentIntent; + #[cfg(feature = "v2")] + fn get_client_secret(&self) -> &Option<Secret<String>>; fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>; fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>; fn get_address(&self) -> &PaymentAddress; @@ -8054,6 +8053,8 @@ pub trait OperationSessionGetters<F> { pub trait OperationSessionSetters<F> { // Setter functions for PaymentData fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent); + #[cfg(feature = "v2")] + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>); fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt); fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>); fn set_email_if_not_present(&mut self, email: pii::Email); @@ -8361,6 +8362,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { todo!() } + fn get_client_secret(&self) -> &Option<Secret<String>> { + &self.client_secret + } + fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -8493,7 +8498,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + self.client_secret = client_secret; + } fn set_payment_attempt(&mut self, _payment_attempt: storage::PaymentAttempt) { todo!() } @@ -8577,6 +8584,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent @@ -8709,7 +8719,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } @@ -8795,7 +8807,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { todo!() } - + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -8926,7 +8940,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = Some(payment_attempt); } @@ -9012,7 +9028,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } - + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -9145,7 +9163,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a701d16fe17..a4a3f7c7572 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3587,30 +3587,6 @@ pub fn authenticate_client_secret( } } -#[cfg(feature = "v2")] -// A function to manually authenticate the client secret with intent fulfillment time -pub fn authenticate_client_secret( - request_client_secret: Option<&common_utils::types::ClientSecret>, - payment_intent: &PaymentIntent, -) -> Result<(), errors::ApiErrorResponse> { - match (request_client_secret, &payment_intent.client_secret) { - (Some(req_cs), pi_cs) => { - if req_cs != pi_cs { - Err(errors::ApiErrorResponse::ClientSecretInvalid) - } else { - let current_timestamp = common_utils::date_time::now(); - - let session_expiry = payment_intent.session_expiry; - - fp_utils::when(current_timestamp > session_expiry, || { - Err(errors::ApiErrorResponse::ClientSecretExpired) - }) - } - } - _ => Ok(()), - } -} - pub(crate) fn validate_payment_status_against_allowed_statuses( intent_status: storage_enums::IntentStatus, allowed_statuses: &[storage_enums::IntentStatus], diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 11e5093cf00..a997aab457d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -169,11 +169,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir // TODO (#7195): Add platform merchant account validation once publishable key auth is solved self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; let cell_id = state.conf.cell_information.id.clone(); diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index 755c4e153ce..92572602adb 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, Encode, ValueExt}, - types::keymanager::ToEncryptable, + types::{authentication, keymanager::ToEncryptable}, }; use error_stack::ResultExt; use masking::PeekInterface; @@ -158,9 +158,19 @@ impl<F: Send + Clone + Sync> }) .attach_printable("failed while inserting new payment intent")?; + let client_secret = helpers::create_client_secret( + state, + merchant_account.get_id(), + authentication::ResourceId::Payment(payment_id.clone()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create client secret")?; + let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: Some(client_secret.secret), sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs index 05f939ee31b..2e00b19c757 100644 --- a/crates/router/src/core/payments/operations/payment_get_intent.rs +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -106,6 +106,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + // todo : add a way to fetch client secret if required + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs index 4e62899546b..d90dba639b1 100644 --- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -74,7 +74,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved - helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?; let mut payment_attempt = db diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs index 79348e6e235..8b8bbae292e 100644 --- a/crates/router/src/core/payments/operations/payment_session_intent.rs +++ b/crates/router/src/core/payments/operations/payment_session_intent.rs @@ -138,15 +138,10 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; - let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 455f2884324..49de2c77ec8 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -83,6 +83,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq payment_intent.client_secret.as_ref(), &payment_intent, )?; + payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 9d09d56515c..f74a433037d 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -112,7 +112,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> ], "update", )?; - helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; payment_intent.order_details = request diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index 9b89ead615f..a1af12e9fc6 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -291,6 +291,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index df100d2e9b6..94c4341dee7 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -36,16 +36,6 @@ pub async fn list_payment_methods( validate_payment_status_for_payment_method_list(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header") - .change_context(errors::ApiErrorResponse::MissingRequiredField { - field_name: "client_secret header", - })?; - - payment_intent.validate_client_secret(client_secret)?; - let payment_connector_accounts = db .list_enabled_connector_accounts_by_profile_id( key_manager_state, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index eb5b3d88173..652811e5a8f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1523,6 +1523,7 @@ where _merchant_account: &domain::MerchantAccount, ) -> RouterResponse<Self> { let payment_intent = payment_data.get_payment_intent(); + let client_secret = payment_data.get_client_secret(); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { id: payment_intent.id.clone(), @@ -1531,7 +1532,7 @@ where amount_details: api_models::payments::AmountDetailsResponse::foreign_from( payment_intent.amount_details.clone(), ), - client_secret: payment_intent.client_secret.clone(), + client_secret: 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, @@ -1662,7 +1663,6 @@ where amount, customer_id: payment_intent.customer_id.clone(), connector: Some(connector), - client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), @@ -1760,7 +1760,6 @@ where .cloned() .map(From::from), shipping: self.payment_address.get_shipping().cloned().map(From::from), - client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: self diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7e3d6802b88..fb694d3f23c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -2101,23 +2101,38 @@ where 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()) + match (&self.0, &db_client_secret.resource_id) { + ( + common_utils::types::authentication::ResourceId::Payment(self_id), + common_utils::types::authentication::ResourceId::Payment(db_id), + ) => { + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - 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::Customer(self_id), + common_utils::types::authentication::ResourceId::Customer(db_id), + ) => { + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - common_utils::types::authentication::ResourceId::PaymentMethodSession( - global_payment_method_session_id, + + ( + common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id), + common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id), ) => { - if global_payment_method_session_id.get_string_repr() != self.0.to_str() { - return Err(errors::ApiErrorResponse::Unauthorized.into()); - } + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - }; + + _ => { + return Err(errors::ApiErrorResponse::Unauthorized.into()); + } + } let (merchant_account, key_store) = state .store() diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c11751c8324..4a8be05711f 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1652,14 +1652,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP let x_redirect_uri = get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); - // TODO: combine publishable key and client secret when we unify the auth - let client_secret = get_header_value_by_key(X_CLIENT_SECRET.into(), headers)? - .map(common_utils::types::ClientSecret::from_str) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "Invalid data received in client_secret header".into(), - })?; - Ok(Self { payment_confirm_source, // client_source, @@ -1671,7 +1663,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP locale, x_app_id, x_redirect_uri, - client_secret, }) } } diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql new file mode 100644 index 00000000000..215c3bf4125 --- /dev/null +++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent +ADD COLUMN client_secret VARCHAR(128); \ No newline at end of file diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql new file mode 100644 index 00000000000..7463ea0cbc7 --- /dev/null +++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent DROP COLUMN client_secret; \ No newline at end of file
2025-03-26T14:11:03Z
Your PR Description ## Description 1. This commit changes how the client secret is generated 2. Change how client secret is made in Create Payment Intent Old `{Payment_id}_secret_{Secret}` `eg : pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo` New `cs_{Secret}` `eg: cs_0195d2be95ba7ef1a05066e163295562` 3. Client secret validation in the root level #7487 ``` &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), ``` 3. And removes client secret from PaymentIntent, PaymentIntentNew, HeaderResponse 4. update authentication logic for global_payment_id in V2ClientAuth ## Motivation and Context #
f532b70af9c8acddfd00752d7a3893ac68e3c1eb
For `/v2/payments/create-intent` Request ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_REbCm9NzneE8vUBmgWWZ' \ --header 'Authorization: ••••••' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` Response ``` { "id": "12345_pay_0195d5b7ff767ac094321057ddd9f2eb", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "cs_0195d5b7ffaf700397ea3e418d0835f6", "profile_id": "pro_EhW92OOmycGn3j0clrbm", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "manual", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": null, "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-03-27T04:04:20.409Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` For `/v2/payments/:id/payment-methods` Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d65b6a2c7931ad28b04dba1be6c9/payment-methods' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_XTzqP0yNw5ndliWtB9MJ' \ --header 'Authorization: publishable-key=pk_dev_266ddc923fa940c8a97240b9e690756e,client-secret=cs_0195d65b6a7b7072acf186a4529ae9ad ' ``` Response ``` { "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtype": "card_redirect", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "credit", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "debit", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "google_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "apple_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "we_chat_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "ali_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "paypal", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "mb_way", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "klarna", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "affirm", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "afterpay_clearpay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "walley", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "giropay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "ideal", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "eps", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "bancontact_card", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "przelewy24", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "sofort", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "blik", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "trustly", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_finland", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_poland", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "ach", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "sepa", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "bacs", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "ach", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "sepa", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "bacs", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "becs", "required_fields": null, "surcharge_details": null } ], "customer_payment_methods": null } ``` For `/v2/payments/:id/confirm-intent` Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d65b6a2c7931ad28b04dba1be6c9/confirm-intent' \ --header 'x-profile-id: pro_XTzqP0yNw5ndliWtB9MJ' \ --header 'Authorization: publishable-key=pk_dev_266ddc923fa940c8a97240b9e690756e,client-secret=cs_0195d65b6a7b7072acf186a4529ae9ad ' \ --header 'Content-Type: application/json' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "26", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" } ``` Response ``` { "id": "12345_pay_0195d65b6a2c7931ad28b04dba1be6c9", "status": "failed", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "stripe", "client_secret": null, "created": "2025-03-27T06:47:50.083Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": null, "connector_reference_id": null, "merchant_connector_id": "mca_qB5no08zJFDBYPZBZdFR", "browser_info": null, "error": { "code": "No error code", "message": "No error message", "unified_code": null, "unified_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payments.rs", "crates/common_utils/src/id_type/global_id/payment.rs", "crates/common_utils/src/types.rs", "crates/diesel_models/src/payment_intent.rs", "crates/diesel_models/src/schema_v2.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_intent.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_confirm_intent.rs", "crates/router/src/core/payments/operations/payment_create_intent.rs", "crates/router/src/core/payments/operations/payment_get_intent.rs", "crates/router/src/core/payments/operations/payment_post_session_tokens.rs", "crates/router/src/core/payments/operations/payment_session_intent.rs", "crates/router/src/core/payments/operations/payment_start.rs", "crates/router/src/core/payments/operations/payment_update.rs", "crates/router/src/core/payments/operations/payment_update_intent.rs", "crates/router/src/core/payments/payment_methods.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/services/authentication.rs", "crates/router/src/types/transformers.rs", "v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql", "v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7650
Bug: refactor(payments): update authentication logic for global_payment_id in V2ClientAuth https://github.com/juspay/hyperswitch-cloud/issues/8862 ## Verify Confirm a Payment ### Using `x-client-secret` as `client_secret` ```curl curl --location 'https://integ.hyperswitch.io/api/v2/payments/12345_pay_0195acbb210178a0bfa801e9ad6ae338/confirm-intent' \ --header '<<Authorization Header>>' \ --header 'x-profile-id: pro_hIm1Djam2eJdIogn0la6' \ --header 'Content-Type: application/json' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" }' ``` ```json { "error": { "type": "invalid_request", "message": "Missing required param: Authorization", "code": "IR_04" } } ``` ### Using `Authorization` as `client-secret={{client_secret}}` ```json { "error": { "type": "invalid_request", "message": "API key not provided or invalid API key used", "code": "IR_01" } } ``` ### Using `Authorization` as `publishable-key={{publishable_key}},client-secret={{client_secret}}` ```json { "error": { "type": "invalid_request", "message": "API key not provided or invalid API key used", "code": "IR_01" } } ``` ## Summary Confirming Payments needed `x-client-secret: client-secret` previously, so now it should work with `Authorization: publishable-key={{publishable_key}},client-secret={{client_secret}}`. But doesn't work with any of the above cases.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index de2cd1b0360..27936b2917c 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -17102,7 +17102,7 @@ "client_secret": { "type": "string", "description": "It's a token used for client side verification.", - "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo" + "example": "cs_0195b34da95d75239c6a4bf514458896" }, "profile_id": { "type": "string", @@ -17699,7 +17699,6 @@ "status", "amount", "customer_id", - "client_secret", "created" ], "properties": { @@ -17729,10 +17728,6 @@ "example": "stripe", "nullable": true }, - "client_secret": { - "type": "string", - "description": "It's a token used for client side verification." - }, "created": { "type": "string", "format": "date-time", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 3cfadb0a57c..1a07a18f336 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -480,8 +480,8 @@ pub struct PaymentsIntentResponse { pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. - #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] - pub client_secret: common_utils::types::ClientSecret, + #[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")] + pub client_secret: Option<Secret<String>>, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] @@ -5576,10 +5576,6 @@ pub struct PaymentsResponse { #[schema(example = "stripe")] pub connector: Option<String>, - /// It's a token used for client side verification. - #[schema(value_type = String)] - pub client_secret: common_utils::types::ClientSecret, - /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] 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 5de836cd486..22ac0d4c0a4 100644 --- a/crates/common_utils/src/id_type/global_id/payment.rs +++ b/crates/common_utils/src/id_type/global_id/payment.rs @@ -28,11 +28,6 @@ impl GlobalPaymentId { 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()) - } - /// Generate the id for revenue recovery Execute PT workflow pub fn get_execute_revenue_recovery_id( &self, diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 11c9b17fae6..b9d245d48ce 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -686,261 +686,6 @@ where } } -#[cfg(feature = "v2")] -pub use client_secret_type::ClientSecret; -#[cfg(feature = "v2")] -mod client_secret_type { - use std::fmt; - - use masking::PeekInterface; - use router_env::logger; - - use super::*; - use crate::id_type; - - /// A domain type that can be used to represent a client secret - /// Client secret is generated for a payment and is used to authenticate the client side api calls - #[derive(Debug, PartialEq, Clone, AsExpression)] - #[diesel(sql_type = sql_types::Text)] - pub struct ClientSecret { - /// The payment id of the payment - pub payment_id: id_type::GlobalPaymentId, - /// The secret string - pub secret: masking::Secret<String>, - } - - impl ClientSecret { - pub(crate) fn get_string_repr(&self) -> String { - format!( - "{}_secret_{}", - self.payment_id.get_string_repr(), - 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 FromStr for ClientSecret { - type Err = ParsingError; - - fn from_str(str_value: &str) -> Result<Self, Self::Err> { - let (payment_id, secret) = - str_value - .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()), - }) - } - } - - impl<'de> Deserialize<'de> for ClientSecret { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - struct ClientSecretVisitor; - - impl Visitor<'_> for ClientSecretVisitor { - type Value = ClientSecret; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("a string in the format '{payment_id}_secret_{secret}'") - } - - fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E> - where - E: serde::de::Error, - { - let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| { - E::invalid_value( - serde::de::Unexpected::Str(value), - &"a string with '_secret_'", - ) - })?; - - let payment_id = - id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) - .map_err(serde::de::Error::custom)?; - - Ok(ClientSecret { - payment_id, - secret: masking::Secret::new(secret.to_owned()), - }) - } - } - - deserializer.deserialize_str(ClientSecretVisitor) - } - } - - impl Serialize for ClientSecret { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: serde::ser::Serializer, - { - serializer.serialize_str(self.get_string_repr().as_str()) - } - } - - impl ToSql<sql_types::Text, diesel::pg::Pg> for ClientSecret - where - String: ToSql<sql_types::Text, diesel::pg::Pg>, - { - fn to_sql<'b>( - &'b self, - out: &mut Output<'b, '_, diesel::pg::Pg>, - ) -> diesel::serialize::Result { - let string_repr = self.get_string_repr(); - <String as ToSql<sql_types::Text, diesel::pg::Pg>>::to_sql( - &string_repr, - &mut out.reborrow(), - ) - } - } - - impl<DB> FromSql<sql_types::Text, DB> for ClientSecret - where - DB: Backend, - String: FromSql<sql_types::Text, DB>, - { - fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { - let string_repr = String::from_sql(value)?; - 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()), - }) - } - } - - impl<DB> Queryable<sql_types::Text, DB> for ClientSecret - where - DB: Backend, - Self: FromSql<sql_types::Text, DB>, - { - type Row = Self; - - fn build(row: Self::Row) -> deserialize::Result<Self> { - Ok(row) - } - } - crate::impl_serializable_secret_id_type!(ClientSecret); - #[cfg(test)] - mod client_secret_tests { - #![allow(clippy::expect_used)] - #![allow(clippy::unwrap_used)] - - use serde_json; - - use super::*; - use crate::id_type::GlobalPaymentId; - - #[test] - fn test_serialize_client_secret() { - let global_payment_id = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - let secret = "fc34taHLw1ekPgNh92qr".to_string(); - - let expected_client_secret_string = format!("\"{global_payment_id}_secret_{secret}\""); - - let client_secret1 = ClientSecret { - payment_id: GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id)).unwrap(), - secret: masking::Secret::new(secret), - }; - - let parsed_client_secret = - serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1"); - - assert_eq!(expected_client_secret_string, parsed_client_secret); - } - - #[test] - fn test_deserialize_client_secret() { - // This is a valid global id - let global_payment_id_str = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - let secret = "fc34taHLw1ekPgNh92qr".to_string(); - - let valid_payment_global_id = - GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id_str)) - .expect("Failed to create valid global payment id"); - - // This is an invalid global id because of the cell id being in invalid length - let invalid_global_payment_id = "123_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - - // Create a client secret string which is valid - let valid_client_secret = format!(r#""{global_payment_id_str}_secret_{secret}""#); - - dbg!(&valid_client_secret); - - // Create a client secret string which is invalid - let invalid_client_secret_because_of_invalid_payment_id = - format!(r#""{invalid_global_payment_id}_secret_{secret}""#); - - // Create a client secret string which is invalid because of invalid secret - let invalid_client_secret_because_of_invalid_secret = - format!(r#""{invalid_global_payment_id}""#); - - let valid_client_secret = serde_json::from_str::<ClientSecret>(&valid_client_secret) - .expect("Failed to deserialize client_secret_str1"); - - let invalid_deser1 = serde_json::from_str::<ClientSecret>( - &invalid_client_secret_because_of_invalid_payment_id, - ); - - dbg!(&invalid_deser1); - - let invalid_deser2 = serde_json::from_str::<ClientSecret>( - &invalid_client_secret_because_of_invalid_secret, - ); - - dbg!(&invalid_deser2); - - assert_eq!(valid_client_secret.payment_id, valid_payment_global_id); - - assert_eq!(valid_client_secret.secret.peek(), &secret); - - assert_eq!( - invalid_deser1.err().unwrap().to_string(), - "Incorrect value provided for field: payment_id at line 1 column 70" - ); - - assert_eq!( - invalid_deser2.err().unwrap().to_string(), - "invalid value: string \"123_pay_1a961ed9093c48b09781bf8ab17ba6bd\", expected a string with '_secret_' at line 1 column 42" - ); - } - } -} - /// A type representing a range of time for filtering, including a mandatory start time and an optional end time. #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 6753afc2d99..5034873e7ac 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -33,7 +33,6 @@ pub struct PaymentIntent { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, @@ -290,7 +289,6 @@ pub struct PaymentIntentNew { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4c07445f710..9b16f56f350 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -921,8 +921,6 @@ diesel::table! { modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, - #[max_length = 128] - client_secret -> Varchar, #[max_length = 64] active_attempt_id -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index dedba889c68..7f757c64a72 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -403,8 +403,6 @@ pub struct PaymentIntent { #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, 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_id: Option<id_type::GlobalAttemptId>, /// The order details for the payment. @@ -526,22 +524,6 @@ impl PaymentIntent { .unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default())) } - /// Check if the client secret is associated with the payment and if it has been expired - pub fn validate_client_secret( - &self, - client_secret: &common_utils::types::ClientSecret, - ) -> Result<(), errors::api_error_response::ApiErrorResponse> { - common_utils::fp_utils::when(self.client_secret != *client_secret, || { - Err(errors::api_error_response::ApiErrorResponse::ClientSecretInvalid) - })?; - - common_utils::fp_utils::when(self.session_expiry < common_utils::date_time::now(), || { - Err(errors::api_error_response::ApiErrorResponse::ClientSecretExpired) - })?; - - Ok(()) - } - pub async fn create_domain_model_from_request( payment_id: &id_type::GlobalPaymentId, merchant_account: &merchant_account::MerchantAccount, @@ -566,7 +548,6 @@ impl PaymentIntent { .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() @@ -589,7 +570,6 @@ impl PaymentIntent { modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: request.setup_future_usage.unwrap_or_default(), - client_secret, active_attempt_id: None, order_details, allowed_payment_method_types, @@ -704,7 +684,6 @@ pub struct HeaderPayload { pub locale: Option<String>, pub x_app_id: Option<String>, pub x_redirect_uri: Option<String>, - pub client_secret: Option<common_utils::types::ClientSecret>, } impl HeaderPayload { @@ -725,6 +704,7 @@ where pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub sessions_token: Vec<SessionToken>, + pub client_secret: Option<Secret<String>>, } // TODO: Check if this can be merged with existing payment data diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 13452649447..9b429f462e4 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1561,7 +1561,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at, last_synced, setup_future_usage, - client_secret, active_attempt_id, order_details, allowed_payment_method_types, @@ -1611,7 +1610,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at, last_synced, setup_future_usage: Some(setup_future_usage), - client_secret, active_attempt_id, order_details: order_details.map(|order_details| { order_details @@ -1760,7 +1758,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(), - client_secret: storage_model.client_secret, active_attempt_id: storage_model.active_attempt_id, order_details: storage_model.order_details.map(|order_details| { order_details @@ -1836,7 +1833,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at: self.modified_at, last_synced: self.last_synced, setup_future_usage: Some(self.setup_future_usage), - client_secret: self.client_secret, active_attempt_id: self.active_attempt_id, order_details: self.order_details, allowed_payment_method_types: self diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index cd68709afa4..e13bf290bec 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2041,9 +2041,6 @@ pub(crate) async fn payments_create_and_confirm_intent( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; - // Adding client secret to ensure client secret validation passes during confirm intent step - header_payload.client_secret = Some(create_intent_response.client_secret.clone()); - let payload = payments_api::PaymentsConfirmIntentRequest::from(&request); let confirm_intent_response = decide_authorize_or_setup_intent_flow( @@ -8013,6 +8010,8 @@ impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; fn get_payment_intent(&self) -> &storage::PaymentIntent; + #[cfg(feature = "v2")] + fn get_client_secret(&self) -> &Option<Secret<String>>; fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>; fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>; fn get_address(&self) -> &PaymentAddress; @@ -8054,6 +8053,8 @@ pub trait OperationSessionGetters<F> { pub trait OperationSessionSetters<F> { // Setter functions for PaymentData fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent); + #[cfg(feature = "v2")] + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>); fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt); fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>); fn set_email_if_not_present(&mut self, email: pii::Email); @@ -8361,6 +8362,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { todo!() } + fn get_client_secret(&self) -> &Option<Secret<String>> { + &self.client_secret + } + fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -8493,7 +8498,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + self.client_secret = client_secret; + } fn set_payment_attempt(&mut self, _payment_attempt: storage::PaymentAttempt) { todo!() } @@ -8577,6 +8584,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent @@ -8709,7 +8719,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } @@ -8795,7 +8807,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { todo!() } - + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -8926,7 +8940,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = Some(payment_attempt); } @@ -9012,7 +9028,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } - + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -9145,7 +9163,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a701d16fe17..a4a3f7c7572 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3587,30 +3587,6 @@ pub fn authenticate_client_secret( } } -#[cfg(feature = "v2")] -// A function to manually authenticate the client secret with intent fulfillment time -pub fn authenticate_client_secret( - request_client_secret: Option<&common_utils::types::ClientSecret>, - payment_intent: &PaymentIntent, -) -> Result<(), errors::ApiErrorResponse> { - match (request_client_secret, &payment_intent.client_secret) { - (Some(req_cs), pi_cs) => { - if req_cs != pi_cs { - Err(errors::ApiErrorResponse::ClientSecretInvalid) - } else { - let current_timestamp = common_utils::date_time::now(); - - let session_expiry = payment_intent.session_expiry; - - fp_utils::when(current_timestamp > session_expiry, || { - Err(errors::ApiErrorResponse::ClientSecretExpired) - }) - } - } - _ => Ok(()), - } -} - pub(crate) fn validate_payment_status_against_allowed_statuses( intent_status: storage_enums::IntentStatus, allowed_statuses: &[storage_enums::IntentStatus], diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 11e5093cf00..a997aab457d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -169,11 +169,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir // TODO (#7195): Add platform merchant account validation once publishable key auth is solved self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; let cell_id = state.conf.cell_information.id.clone(); diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index 755c4e153ce..92572602adb 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, Encode, ValueExt}, - types::keymanager::ToEncryptable, + types::{authentication, keymanager::ToEncryptable}, }; use error_stack::ResultExt; use masking::PeekInterface; @@ -158,9 +158,19 @@ impl<F: Send + Clone + Sync> }) .attach_printable("failed while inserting new payment intent")?; + let client_secret = helpers::create_client_secret( + state, + merchant_account.get_id(), + authentication::ResourceId::Payment(payment_id.clone()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create client secret")?; + let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: Some(client_secret.secret), sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs index 05f939ee31b..2e00b19c757 100644 --- a/crates/router/src/core/payments/operations/payment_get_intent.rs +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -106,6 +106,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + // todo : add a way to fetch client secret if required + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs index 4e62899546b..d90dba639b1 100644 --- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -74,7 +74,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved - helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?; let mut payment_attempt = db diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs index 79348e6e235..8b8bbae292e 100644 --- a/crates/router/src/core/payments/operations/payment_session_intent.rs +++ b/crates/router/src/core/payments/operations/payment_session_intent.rs @@ -138,15 +138,10 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; - let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 455f2884324..49de2c77ec8 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -83,6 +83,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq payment_intent.client_secret.as_ref(), &payment_intent, )?; + payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 9d09d56515c..f74a433037d 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -112,7 +112,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> ], "update", )?; - helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; payment_intent.order_details = request diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index 9b89ead615f..a1af12e9fc6 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -291,6 +291,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index df100d2e9b6..94c4341dee7 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -36,16 +36,6 @@ pub async fn list_payment_methods( validate_payment_status_for_payment_method_list(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header") - .change_context(errors::ApiErrorResponse::MissingRequiredField { - field_name: "client_secret header", - })?; - - payment_intent.validate_client_secret(client_secret)?; - let payment_connector_accounts = db .list_enabled_connector_accounts_by_profile_id( key_manager_state, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index eb5b3d88173..652811e5a8f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1523,6 +1523,7 @@ where _merchant_account: &domain::MerchantAccount, ) -> RouterResponse<Self> { let payment_intent = payment_data.get_payment_intent(); + let client_secret = payment_data.get_client_secret(); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { id: payment_intent.id.clone(), @@ -1531,7 +1532,7 @@ where amount_details: api_models::payments::AmountDetailsResponse::foreign_from( payment_intent.amount_details.clone(), ), - client_secret: payment_intent.client_secret.clone(), + client_secret: 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, @@ -1662,7 +1663,6 @@ where amount, customer_id: payment_intent.customer_id.clone(), connector: Some(connector), - client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), @@ -1760,7 +1760,6 @@ where .cloned() .map(From::from), shipping: self.payment_address.get_shipping().cloned().map(From::from), - client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: self diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7e3d6802b88..fb694d3f23c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -2101,23 +2101,38 @@ where 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()) + match (&self.0, &db_client_secret.resource_id) { + ( + common_utils::types::authentication::ResourceId::Payment(self_id), + common_utils::types::authentication::ResourceId::Payment(db_id), + ) => { + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - 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::Customer(self_id), + common_utils::types::authentication::ResourceId::Customer(db_id), + ) => { + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - common_utils::types::authentication::ResourceId::PaymentMethodSession( - global_payment_method_session_id, + + ( + common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id), + common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id), ) => { - if global_payment_method_session_id.get_string_repr() != self.0.to_str() { - return Err(errors::ApiErrorResponse::Unauthorized.into()); - } + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - }; + + _ => { + return Err(errors::ApiErrorResponse::Unauthorized.into()); + } + } let (merchant_account, key_store) = state .store() diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c11751c8324..4a8be05711f 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1652,14 +1652,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP let x_redirect_uri = get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); - // TODO: combine publishable key and client secret when we unify the auth - let client_secret = get_header_value_by_key(X_CLIENT_SECRET.into(), headers)? - .map(common_utils::types::ClientSecret::from_str) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "Invalid data received in client_secret header".into(), - })?; - Ok(Self { payment_confirm_source, // client_source, @@ -1671,7 +1663,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP locale, x_app_id, x_redirect_uri, - client_secret, }) } } diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql new file mode 100644 index 00000000000..215c3bf4125 --- /dev/null +++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent +ADD COLUMN client_secret VARCHAR(128); \ No newline at end of file diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql new file mode 100644 index 00000000000..7463ea0cbc7 --- /dev/null +++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent DROP COLUMN client_secret; \ No newline at end of file
2025-03-26T14:11:03Z
Your PR Description ## Description 1. This commit changes how the client secret is generated 2. Change how client secret is made in Create Payment Intent Old `{Payment_id}_secret_{Secret}` `eg : pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo` New `cs_{Secret}` `eg: cs_0195d2be95ba7ef1a05066e163295562` 3. Client secret validation in the root level #7487 ``` &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), ``` 3. And removes client secret from PaymentIntent, PaymentIntentNew, HeaderResponse 4. update authentication logic for global_payment_id in V2ClientAuth ## Motivation and Context #
f532b70af9c8acddfd00752d7a3893ac68e3c1eb
For `/v2/payments/create-intent` Request ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_REbCm9NzneE8vUBmgWWZ' \ --header 'Authorization: ••••••' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` Response ``` { "id": "12345_pay_0195d5b7ff767ac094321057ddd9f2eb", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "cs_0195d5b7ffaf700397ea3e418d0835f6", "profile_id": "pro_EhW92OOmycGn3j0clrbm", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "manual", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": null, "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-03-27T04:04:20.409Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` For `/v2/payments/:id/payment-methods` Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d65b6a2c7931ad28b04dba1be6c9/payment-methods' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_XTzqP0yNw5ndliWtB9MJ' \ --header 'Authorization: publishable-key=pk_dev_266ddc923fa940c8a97240b9e690756e,client-secret=cs_0195d65b6a7b7072acf186a4529ae9ad ' ``` Response ``` { "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtype": "card_redirect", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "credit", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "debit", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "google_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "apple_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "we_chat_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "ali_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "paypal", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "mb_way", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "klarna", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "affirm", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "afterpay_clearpay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "walley", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "giropay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "ideal", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "eps", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "bancontact_card", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "przelewy24", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "sofort", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "blik", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "trustly", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_finland", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_poland", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "ach", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "sepa", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "bacs", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "ach", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "sepa", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "bacs", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "becs", "required_fields": null, "surcharge_details": null } ], "customer_payment_methods": null } ``` For `/v2/payments/:id/confirm-intent` Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d65b6a2c7931ad28b04dba1be6c9/confirm-intent' \ --header 'x-profile-id: pro_XTzqP0yNw5ndliWtB9MJ' \ --header 'Authorization: publishable-key=pk_dev_266ddc923fa940c8a97240b9e690756e,client-secret=cs_0195d65b6a7b7072acf186a4529ae9ad ' \ --header 'Content-Type: application/json' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "26", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" } ``` Response ``` { "id": "12345_pay_0195d65b6a2c7931ad28b04dba1be6c9", "status": "failed", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "stripe", "client_secret": null, "created": "2025-03-27T06:47:50.083Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": null, "connector_reference_id": null, "merchant_connector_id": "mca_qB5no08zJFDBYPZBZdFR", "browser_info": null, "error": { "code": "No error code", "message": "No error message", "unified_code": null, "unified_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payments.rs", "crates/common_utils/src/id_type/global_id/payment.rs", "crates/common_utils/src/types.rs", "crates/diesel_models/src/payment_intent.rs", "crates/diesel_models/src/schema_v2.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_intent.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_confirm_intent.rs", "crates/router/src/core/payments/operations/payment_create_intent.rs", "crates/router/src/core/payments/operations/payment_get_intent.rs", "crates/router/src/core/payments/operations/payment_post_session_tokens.rs", "crates/router/src/core/payments/operations/payment_session_intent.rs", "crates/router/src/core/payments/operations/payment_start.rs", "crates/router/src/core/payments/operations/payment_update.rs", "crates/router/src/core/payments/operations/payment_update_intent.rs", "crates/router/src/core/payments/payment_methods.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/services/authentication.rs", "crates/router/src/types/transformers.rs", "v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql", "v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7643
Bug: [Docker] Change user to non-privileged one before running binary We should not be running binary at highest privileges. It is better to not use `app:app` instead.
diff --git a/Dockerfile b/Dockerfile index 4914e6ad235..b2ad0809978 100644 --- a/Dockerfile +++ b/Dockerfile @@ -72,6 +72,10 @@ RUN mkdir -p ${BIN_DIR} COPY --from=builder /router/target/release/${BINARY} ${BIN_DIR}/${BINARY} +# Create the 'app' user and group +RUN useradd --user-group --system --no-create-home --no-log-init app +USER app:app + WORKDIR ${BIN_DIR} CMD ./${BINARY}
2025-03-26T10:33:34Z
## Description <!-- Describe your changes in detail --> This PR modifies the `Dockerfile` to specify the user at runner stage. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> From the security perspective, it is better to be a `user` rather than being a `root`. Closes https://github.com/juspay/hyperswitch/issues/7643 #
4a4284a6961b1c1b32bbff1c2f1cbdd0c60fbf71
build succeeded (tested by making a debug build): ![image](https://github.com/user-attachments/assets/3c27cbe1-56fa-48b9-a4bb-4a5ebb59563c) ```sh podman build \ --load \ --file Dockerfile \ --build-arg "BINARY=router" \ --tag hyperswitch-router \ . ```
[ "Dockerfile" ]
juspay/hyperswitch
juspay__hyperswitch-7633
Bug: ProdIntent Changes ProdIntent changes for providing context of product_type and also converting it into merchant-scope from user scope.
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index fa550d671fb..8e734d31b53 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -1,4 +1,4 @@ -use common_enums::CountryAlpha2; +use common_enums::{CountryAlpha2, MerchantProductType}; use common_utils::{id_type, pii}; use masking::Secret; use strum::EnumString; @@ -103,6 +103,8 @@ pub struct ProdIntent { pub poc_contact: Option<String>, pub comments: Option<String>, pub is_completed: bool, + #[serde(default)] + pub product_type: MerchantProductType, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs index d9c83312d6b..e5b3ef733c6 100644 --- a/crates/common_enums/src/enums/accounts.rs +++ b/crates/common_enums/src/enums/accounts.rs @@ -1,6 +1,7 @@ use serde; use utoipa::ToSchema; #[derive( + Copy, Default, Clone, Debug, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b9ebdf13028..91b20621da8 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2974,7 +2974,7 @@ pub async fn list_merchants_for_user_in_org( .map(|merchant_account| user_api::UserMerchantAccountResponse { merchant_name: merchant_account.merchant_name.clone(), merchant_id: merchant_account.get_id().to_owned(), - product_type: merchant_account.product_type.clone(), + product_type: merchant_account.product_type, version: merchant_account.version, }) .collect::<Vec<_>>(), diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index d79d155cba9..a4068fc4fad 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -38,7 +38,6 @@ pub async fn set_metadata( Ok(ApplicationResponse::StatusOk) } -#[cfg(feature = "v1")] pub async fn get_multiple_metadata( state: SessionState, user: UserFromToken, @@ -462,7 +461,7 @@ async fn insert_metadata( pii::Email::from_str(inner_poc_email) .change_context(UserErrors::EmailParsingError)?; } - let mut metadata = utils::insert_user_scoped_metadata_to_db( + let mut metadata = utils::insert_merchant_scoped_metadata_to_db( state, user.user_id.clone(), user.merchant_id.clone(), @@ -473,7 +472,7 @@ async fn insert_metadata( .await; if utils::is_update_required(&metadata) { - metadata = utils::update_user_scoped_metadata( + metadata = utils::update_merchant_scoped_metadata( state, user.user_id.clone(), user.merchant_id.clone(), @@ -500,7 +499,6 @@ async fn insert_metadata( EntityType::Merchant, ) .await?; - let email_contents = email_types::BizEmailProd::new( state, data, @@ -662,7 +660,6 @@ async fn fetch_metadata( Ok(dashboard_metadata) } -#[cfg(feature = "v1")] pub async fn backfill_metadata( state: &SessionState, user: &UserFromToken, @@ -705,6 +702,11 @@ pub async fn backfill_metadata( return Ok(None); }; + #[cfg(feature = "v1")] + let processor_name = mca.connector_name.clone(); + + #[cfg(feature = "v2")] + let processor_name = mca.connector_name.to_string().clone(); Some( insert_metadata( state, @@ -712,13 +714,14 @@ pub async fn backfill_metadata( DBEnum::StripeConnected, types::MetaData::StripeConnected(api::ProcessorConnected { processor_id: mca.get_id(), - processor_name: mca.connector_name, + processor_name, }), ) .await, ) .transpose() } + DBEnum::PaypalConnected => { let mca = if let Some(paypal_connected) = get_merchant_connector_account_by_name( state, @@ -745,6 +748,11 @@ pub async fn backfill_metadata( return Ok(None); }; + #[cfg(feature = "v1")] + let processor_name = mca.connector_name.clone(); + + #[cfg(feature = "v2")] + let processor_name = mca.connector_name.to_string().clone(); Some( insert_metadata( state, @@ -752,7 +760,7 @@ pub async fn backfill_metadata( DBEnum::PaypalConnected, types::MetaData::PaypalConnected(api::ProcessorConnected { processor_id: mca.get_id(), - processor_name: mca.connector_name, + processor_name, }), ) .await, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 2200567ddf9..1879d19de04 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2136,6 +2136,12 @@ impl User { ), ); + route = route.service( + web::resource("/data") + .route(web::get().to(user::get_multiple_dashboard_metadata)) + .route(web::post().to(user::set_dashboard_metadata)), + ); + route } } diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 1af22d0338a..d075048ddb6 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -197,7 +197,6 @@ pub async fn set_dashboard_metadata( .await } -#[cfg(feature = "v1")] pub async fn get_multiple_dashboard_metadata( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html index 3645c953a02..2c973f2d622 100644 --- a/crates/router/src/services/email/assets/bizemailprod.html +++ b/crates/router/src/services/email/assets/bizemailprod.html @@ -104,6 +104,10 @@ <strong>Business Website:</strong> {business_website} </li> + <li> + <strong>Product Type:</strong> + {product_type} + </li> </ol> </td> </tr> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 5f611bc1b3a..d663f72cec7 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,5 +1,5 @@ use api_models::user::dashboard_metadata::ProdIntent; -use common_enums::EntityType; +use common_enums::{EntityType, MerchantProductType}; use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; @@ -64,6 +64,7 @@ pub enum EmailBody { legal_business_name: String, business_location: String, business_website: String, + product_type: MerchantProductType, }, ReconActivation { user_name: String, @@ -199,6 +200,7 @@ pub mod html { legal_business_name, business_location, business_website, + product_type, } => { format!( include_str!("assets/bizemailprod.html"), @@ -207,6 +209,7 @@ pub mod html { business_location = business_location, business_website = business_website, username = user_name, + product_type = product_type ) } EmailBody::ProFeatureRequest { @@ -558,6 +561,7 @@ pub struct BizEmailProd { pub settings: std::sync::Arc<configs::Settings>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, + pub product_type: MerchantProductType, } impl BizEmailProd { @@ -582,6 +586,7 @@ impl BizEmailProd { business_website: data.business_website.unwrap_or_default(), theme_id, theme_config, + product_type: data.product_type, }) } } @@ -595,6 +600,7 @@ impl EmailData for BizEmailProd { legal_business_name: self.legal_business_name.clone(), business_location: self.business_location.clone(), business_website: self.business_website.clone(), + product_type: self.product_type, }); Ok(EmailContents { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 4854d1b4786..8bf177035ef 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -417,7 +417,7 @@ impl NewUserMerchant { } pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> { - self.product_type.clone() + self.product_type } pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { @@ -703,11 +703,18 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { } else { id_type::MerchantId::new_from_unix_timestamp() }; + let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, - company_name: Some(UserCompanyName::new(value.1.company_name.clone())?), - product_type: value.1.product_type.clone(), - new_organization: NewUserOrganization::from(value), + company_name: Some(UserCompanyName::new( + user_merchant_create.company_name.clone(), + )?), + product_type: user_merchant_create.product_type, + new_organization: NewUserOrganization::from(( + user_from_storage, + user_merchant_create, + user_from_token, + )), }) } } diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index c19b52b6f86..a91a3fe917b 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -218,10 +218,9 @@ pub fn separate_metadata_type_based_on_scope( | DBEnum::SetupWoocomWebhook | DBEnum::OnboardingSurvey | DBEnum::IsMultipleConfiguration - | DBEnum::ReconStatus => merchant_scoped.push(key), - DBEnum::Feedback | DBEnum::ProdIntent | DBEnum::IsChangePasswordRequired => { - user_scoped.push(key) - } + | DBEnum::ReconStatus + | DBEnum::ProdIntent => merchant_scoped.push(key), + DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key), } } (merchant_scoped, user_scoped)
2025-03-26T09:04:30Z
## Description <!-- Describe your changes in detail --> This PR introduces support for associating ProdIntent with specific product_types and transitions the feature from being user-scoped to merchant-scoped, enabling more flexible usage across different products. ## Changes Introduced ### 1. New V2 Routes for Dashboard Metadata - Added v2 routes to support `ProdIntent` creation and retrieval with respect to `product_type`. ### 2. Product-Type Context for ProdIntent - While inserting the `ProdIntent` into the `dashboard_metadata` table (for both **v1** and **v2** schemas), the `product_type` is now included in the metadata. ### 3. Merchant-Scoped ProdIntent - **Before:** `ProdIntent` was **user-scoped**, allowing a single request per user. - **Now:** It is **merchant-scoped**, allowing a user to raise separate `ProdIntent` requests for different merchant accounts for each product by the same user. ### 4. Enhanced Email Body - The email body sent for `ProdIntent` now includes the `product_type` context, helping understand for which product the prod intent was raised. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Enable requesting for Production Access for every product type merchant account. #
961c875ecc225c924160448f01bf38a8e5a4ca03
Hit the curl: - Dashboard Metadata - ProdIntent (POST): ```bash curl --location 'http://localhost:8080/user/data' \ --header 'accept: */*' \ --header 'accept-language: en-US,en;q=0.9' \ --header 'api-key: hyperswitch' \ --header 'content-type: application/json' \ --header 'origin: https://app.hyperswitch.io' \ --header 'priority: u=1, i' \ --header 'referer: https://app.hyperswitch.io/dashboard/home' \ --header 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'sec-fetch-dest: empty' \ --header 'sec-fetch-mode: cors' \ --header 'sec-fetch-site: same-origin' \ --header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \ --header 'x-merchant-id: merchant_1715600622' \ --header 'x-profile-id: pro_CqAdpUQBUUam1n0g56mB' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWExMGExMTYtZDc1Ny00MjBlLTkzNWQtZWRlZmQ5ZmQ3NTFmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQzMDUxMDM3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MzIyMzg0Mywib3JnX2lkIjoib3JnX1h5ZmR4eUttS1RGTEtuNTJ1clBVIiwicHJvZmlsZV9pZCI6InByb190Y3NsZWJDNDhmN1pkNG9mVlRqWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.NuvkkzrYPcba0JKUUrlM39NfyD2rHZ_jHIkHgPyM39s' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMzcwZWUwYWUtZDI0ZS00ODJhLTlmNDktZDYzYmZkNGE0ZjVhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF9qdmMzb1dXRmxkb0xHNG1GbFc0UCIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDMxMDQxMzcsIm9yZ19pZCI6Im9yZ19hU3NCOWozTWVJcWxVS0YwbDJxRCIsInByb2ZpbGVfaWQiOiJwcm9fcGdrWUkzcnl6TlU2NlBLa3A4ZjciLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.oRERTxTsgrZWNXwSJ5w8CvDHOW1qB2GV3wBQ5Mv-BC8' \ --data-raw '{ "ProdIntent": { "poc_email": "[email protected]", "is_completed": true, "legal_business_name": "blueberry", "business_location": "IN", "business_website": "https://google.com", "poc_name": "berry", "comments": "tx123", "product_type": "orchestration" } }' ``` Dashboard Metadata table should get inserted/updated with the record along with the product_type in the json body. Sample entry to table: <img width="1211" alt="image" src="https://github.com/user-attachments/assets/3312b990-6fcf-4a13-af95-cb63d4e5bb4c" /> Also, product_type should also be sent in the email body to the configured recepient email-id. ![WhatsApp Image 2025-03-28 at 12 58 24 AM](https://github.com/user-attachments/assets/e6082260-70f6-43f0-b71a-7e1b83b50da5) - Dashboard Metadata - ProdIntent (GET): ```bash curl --location 'http://localhost:8080/user/data?keys=ProdIntent' \ --header 'X-Merchant-Id: ddcd_oBuAVsHl0XMLag9JsHCV' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2RlMDFhYWYtOWVkMi00YTY5LTg3YWItNWU1YmI2ZWFiNGQ5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQyMjEyMzQxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Mjk4MDgyOCwib3JnX2lkIjoib3JnX3pMQmRNTnpLaDZrNmhiT2tockdJIiwicHJvZmlsZV9pZCI6InByb19LWnhHZ21rUHFkMldQdXBFa2psWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.aD185AZEOcIjHnLnZZ9GJ2ujSHIdRPbPtrYhzNo0V4M' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'Referer: https://integ.hyperswitch.io/dashboard/v2/recon' \ --header 'sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"' \ --header 'X-Profile-Id: pro_UaxaxwTw4A0a9D0QNBrf' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: hyperswitch' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' ``` Expected Output: ```json [ { "ProdIntent": { "legal_business_name": "blueberry", "business_label": null, "business_location": "IN", "display_name": null, "poc_email": "[email protected]", "business_type": null, "business_identifier": null, "business_website": "https://google.com", "poc_name": "berry", "poc_contact": null, "comments": "tx123", "is_completed": true, "product_type": "orchestration" } } ] ``` Similarly v2 routes: `http://localhost:8080/v2/user/data` (POST) `http://localhost:8080/v2/user/data?keys=ProdIntent` (GET)
[ "crates/api_models/src/user/dashboard_metadata.rs", "crates/common_enums/src/enums/accounts.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user/dashboard_metadata.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/user.rs", "crates/router/src/services/email/assets/bizemailprod.html", "crates/router/src/services/email/types.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/utils/user/dashboard_metadata.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7644
Bug: update(ci): update S3 Source File Name in Postman Collection Runner Workflow The S3 source file name in the Postman Collection Runner workflow needs to be updated due to changes in the Connector Auth File. This modification ensures that the correct file is referenced in CI/CD workflows, maintaining authentication integrity.
2025-03-26T08:11:52Z
## Description <!-- Describe your changes in detail --> The S3 Source File Name in Postman Collection Runner Workflow has been changed because the Connector Auth File has been updated. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The connector auth file has been updated, so updating the S3 source file name is required. ## How can we test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Stripe Test cases on Jenkins should pass.
617adfa33fd543131b5c4d8983319bfdcaa6c425
[]
juspay/hyperswitch
juspay__hyperswitch-7630
Bug: [FEATURE] Add Facilitapay connector Facilitapay connector is yet another payment processor. Docs: https://sandbox-portal.facilitapay.com/#/docs
diff --git a/config/config.example.toml b/config/config.example.toml index c373cabac05..7ca8c322c3b 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -208,6 +208,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" @@ -330,6 +331,7 @@ cards = [ "datatrans", "deutschebank", "digitalvirgo", + "facilitapay", "globalpay", "globepay", "gocardless", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 594c3aea763..cd567d04c97 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -53,6 +53,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 1d52421f77b..3aa95a95420 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -57,6 +57,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.convergepay.com/VirtualMerchant/" +facilitapay.base_url = "https://api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com" fiuu.base_url = "https://pay.merchant.razer.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8f1b86fc3b0..4383a426f61 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -57,6 +57,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" diff --git a/config/development.toml b/config/development.toml index a61785cd821..35989e4a02f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -167,6 +167,7 @@ cards = [ "dummyconnector", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", @@ -282,6 +283,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 0676ffa5e28..50835c6b12e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -140,6 +140,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" @@ -255,6 +256,7 @@ cards = [ "dummyconnector", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index b45b3a69799..f53f6d1c49b 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -80,6 +80,7 @@ pub enum RoutableConnectors { Dlocal, Ebanx, Elavon, + // Facilitapay, Fiserv, Fiservemea, Fiuu, @@ -223,6 +224,7 @@ pub enum Connector { Dlocal, Ebanx, Elavon, + // Facilitapay, Fiserv, Fiservemea, Fiuu, @@ -377,13 +379,14 @@ impl Connector { | Self::Cashtocode | Self::Chargebee | Self::Coinbase - |Self::Coingate + | Self::Coingate | Self::Cryptopay | Self::Deutschebank | Self::Digitalvirgo | Self::Dlocal | Self::Ebanx | Self::Elavon + // | Self::Facilitapay | Self::Fiserv | Self::Fiservemea | Self::Fiuu @@ -532,6 +535,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Dlocal => Self::Dlocal, RoutableConnectors::Ebanx => Self::Ebanx, RoutableConnectors::Elavon => Self::Elavon, + // RoutableConnectors::Facilitapay => Self::Facilitapay, RoutableConnectors::Fiserv => Self::Fiserv, RoutableConnectors::Fiservemea => Self::Fiservemea, RoutableConnectors::Fiuu => Self::Fiuu, @@ -640,6 +644,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Dlocal => Ok(Self::Dlocal), Connector::Ebanx => Ok(Self::Ebanx), Connector::Elavon => Ok(Self::Elavon), + // Connector::Facilitapay => Ok(Self::Facilitapay), Connector::Fiserv => Ok(Self::Fiserv), Connector::Fiservemea => Ok(Self::Fiservemea), Connector::Fiuu => Ok(Self::Fiuu), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 878d6e420c4..2e6e6bf91fc 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -191,6 +191,7 @@ pub struct ConnectorConfig { pub dlocal: Option<ConnectorTomlConfig>, pub ebanx_payout: Option<ConnectorTomlConfig>, pub elavon: Option<ConnectorTomlConfig>, + // pub facilitapay: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, pub fiservemea: Option<ConnectorTomlConfig>, pub fiuu: Option<ConnectorTomlConfig>, @@ -365,6 +366,7 @@ impl ConnectorConfig { Connector::Dlocal => Ok(connector_data.dlocal), Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Elavon => Ok(connector_data.elavon), + // Connector::Facilitapay => Ok(connector_data.facilitapay), Connector::Fiserv => Ok(connector_data.fiserv), Connector::Fiservemea => Ok(connector_data.fiservemea), Connector::Fiuu => Ok(connector_data.fiuu), diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 57fed695df9..93db897bfaf 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -24,6 +24,7 @@ pub mod deutschebank; pub mod digitalvirgo; pub mod dlocal; pub mod elavon; +pub mod facilitapay; pub mod fiserv; pub mod fiservemea; pub mod fiuu; @@ -90,14 +91,14 @@ pub use self::{ checkout::Checkout, coinbase::Coinbase, coingate::Coingate, cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, cybersource::Cybersource, datatrans::Datatrans, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, elavon::Elavon, - fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, getnet::Getnet, - globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, helcim::Helcim, hipay::Hipay, - iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, - juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, - moneris::Moneris, multisafepay::Multisafepay, nexinets::Nexinets, nexixpay::Nexixpay, - nomupay::Nomupay, noon::Noon, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, - opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, paypal::Paypal, - paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, + facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, + getnet::Getnet, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, + helcim::Helcim, hipay::Hipay, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, + jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, + mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay, + nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, noon::Noon, novalnet::Novalnet, + nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, + paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs new file mode 100644 index 00000000000..3c6d54eedb6 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs @@ -0,0 +1,575 @@ +pub mod transformers; + +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as facilitapay; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Facilitapay { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Facilitapay { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Facilitapay {} +impl api::PaymentSession for Facilitapay {} +impl api::ConnectorAccessToken for Facilitapay {} +impl api::MandateSetup for Facilitapay {} +impl api::PaymentAuthorize for Facilitapay {} +impl api::PaymentSync for Facilitapay {} +impl api::PaymentCapture for Facilitapay {} +impl api::PaymentVoid for Facilitapay {} +impl api::Refund for Facilitapay {} +impl api::RefundExecute for Facilitapay {} +impl api::RefundSync for Facilitapay {} +impl api::PaymentToken for Facilitapay {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Facilitapay +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Facilitapay +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Facilitapay { + fn id(&self) -> &'static str { + "facilitapay" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + // TODO! Check connector documentation, on which unit they are processing the currency. + // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, + // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.facilitapay.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = facilitapay::FacilitapayAuthType::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: facilitapay::FacilitapayErrorResponse = res + .response + .parse_struct("FacilitapayErrorResponse") + .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, + issuer_error_code: None, + issuer_error_message: None, + }) + } +} + +impl ConnectorValidation for Facilitapay { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Facilitapay { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Facilitapay {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Facilitapay +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = facilitapay::FacilitapayRouterData::from((amount, req)); + let connector_req = + facilitapay::FacilitapayPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: facilitapay::FacilitapayPaymentsResponse = res + .response + .parse_struct("Facilitapay PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: facilitapay::FacilitapayPaymentsResponse = res + .response + .parse_struct("facilitapay PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: facilitapay::FacilitapayPaymentsResponse = res + .response + .parse_struct("Facilitapay PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Facilitapay {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = facilitapay::FacilitapayRouterData::from((refund_amount, req)); + let connector_req = + facilitapay::FacilitapayRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + let response: facilitapay::RefundResponse = res + .response + .parse_struct("facilitapay RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + let response: facilitapay::RefundResponse = res + .response + .parse_struct("facilitapay RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl webhooks::IncomingWebhook for Facilitapay { + fn get_webhook_object_reference_id( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorSpecifications for Facilitapay {} diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs new file mode 100644 index 00000000000..81c2f752d3b --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs @@ -0,0 +1,228 @@ +use common_enums::enums; +use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData, +}; + +//TODO: Fill the struct with respective fields +pub struct FacilitapayRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for FacilitapayRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct FacilitapayPaymentsRequest { + amount: StringMinorUnit, + card: FacilitapayCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct FacilitapayCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&FacilitapayRouterData<&PaymentsAuthorizeRouterData>> for FacilitapayPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &FacilitapayRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = FacilitapayCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct FacilitapayAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for FacilitapayAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum FacilitapayPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<FacilitapayPaymentStatus> for common_enums::AttemptStatus { + fn from(item: FacilitapayPaymentStatus) -> Self { + match item { + FacilitapayPaymentStatus::Succeeded => Self::Charged, + FacilitapayPaymentStatus::Failed => Self::Failure, + FacilitapayPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct FacilitapayPaymentsResponse { + status: FacilitapayPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct FacilitapayRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&FacilitapayRouterData<&RefundsRouterData<F>>> for FacilitapayRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &FacilitapayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct FacilitapayErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 734780a3a6d..3ef5cac04ee 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -148,6 +148,7 @@ default_imp_for_authorize_session_token!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -246,6 +247,7 @@ default_imp_for_calculate_tax!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -344,6 +346,7 @@ default_imp_for_session_update!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -443,7 +446,7 @@ default_imp_for_post_session_tokens!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, - connectors::Square, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -460,6 +463,7 @@ default_imp_for_post_session_tokens!( connectors::Recurly, connectors::Redsys, connectors::Shift4, + connectors::Square, connectors::Stax, connectors::Stripebilling, connectors::Taxjar, @@ -537,6 +541,7 @@ default_imp_for_complete_authorize!( connectors::Datatrans, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -625,6 +630,7 @@ default_imp_for_incremental_authorization!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -725,6 +731,7 @@ default_imp_for_create_customer!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -819,6 +826,7 @@ default_imp_for_connector_redirect_response!( connectors::Deutschebank, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -904,6 +912,7 @@ default_imp_for_pre_processing_steps!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -996,6 +1005,7 @@ default_imp_for_post_processing_steps!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1097,6 +1107,7 @@ default_imp_for_approve!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1198,6 +1209,7 @@ default_imp_for_reject!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1299,6 +1311,7 @@ default_imp_for_webhook_source_verification!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1398,6 +1411,7 @@ default_imp_for_accept_dispute!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1497,6 +1511,7 @@ default_imp_for_submit_evidence!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1596,6 +1611,7 @@ default_imp_for_defend_dispute!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1704,6 +1720,7 @@ default_imp_for_file_upload!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1796,6 +1813,7 @@ default_imp_for_payouts!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1895,6 +1913,7 @@ default_imp_for_payouts_create!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1996,6 +2015,7 @@ default_imp_for_payouts_retrieve!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2096,6 +2116,7 @@ default_imp_for_payouts_eligibility!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2196,6 +2217,7 @@ default_imp_for_payouts_fulfill!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2296,6 +2318,7 @@ default_imp_for_payouts_cancel!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2398,6 +2421,7 @@ default_imp_for_payouts_quote!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2500,6 +2524,7 @@ default_imp_for_payouts_recipient!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2602,6 +2627,7 @@ default_imp_for_payouts_recipient_account!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2704,6 +2730,7 @@ default_imp_for_frm_sale!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2807,6 +2834,7 @@ default_imp_for_frm_checkout!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2910,6 +2938,7 @@ default_imp_for_frm_transaction!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3013,6 +3042,7 @@ default_imp_for_frm_fulfillment!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3116,6 +3146,7 @@ default_imp_for_frm_record_return!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3214,6 +3245,7 @@ default_imp_for_revoking_mandates!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3314,6 +3346,7 @@ default_imp_for_uas_pre_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3412,6 +3445,7 @@ default_imp_for_uas_post_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3511,6 +3545,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3602,6 +3637,7 @@ default_imp_for_connector_request_id!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3695,6 +3731,7 @@ default_imp_for_fraud_check!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3820,6 +3857,7 @@ default_imp_for_connector_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3919,6 +3957,7 @@ default_imp_for_uas_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4018,6 +4057,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4119,6 +4159,7 @@ default_imp_for_additional_revenue_recovery_call!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4213,6 +4254,7 @@ default_imp_for_revenue_recovery!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 864f9e44986..46ac9073f73 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -237,6 +237,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -339,6 +340,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -436,6 +438,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -538,6 +541,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -639,6 +643,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -741,6 +746,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -853,6 +859,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -957,6 +964,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1061,6 +1069,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1165,6 +1174,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1269,6 +1279,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1373,6 +1384,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1477,6 +1489,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1581,6 +1594,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1685,6 +1699,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1787,6 +1802,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1891,6 +1907,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1995,6 +2012,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2099,6 +2117,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2203,6 +2222,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2307,6 +2327,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2408,6 +2429,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2494,6 +2516,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2596,6 +2619,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_domain_models/src/configs.rs b/crates/hyperswitch_domain_models/src/configs.rs index 811db2cbec6..5256e1a8245 100644 --- a/crates/hyperswitch_domain_models/src/configs.rs +++ b/crates/hyperswitch_domain_models/src/configs.rs @@ -39,6 +39,7 @@ pub struct Connectors { pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, + pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 3d8ca2345c4..0c4b4be1793 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -25,25 +25,26 @@ pub use hyperswitch_connectors::connectors::{ coinbase::Coinbase, coingate, coingate::Coingate, cryptopay, cryptopay::Cryptopay, ctp_mastercard, ctp_mastercard::CtpMastercard, cybersource, cybersource::Cybersource, datatrans, datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, - digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, elavon, elavon::Elavon, fiserv, - fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, forte, forte::Forte, - getnet, getnet::Getnet, globalpay, globalpay::Globalpay, globepay, globepay::Globepay, - gocardless, gocardless::Gocardless, helcim, helcim::Helcim, hipay, hipay::Hipay, iatapay, - iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, - jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, klarna, - klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, - moneris::Moneris, multisafepay, multisafepay::Multisafepay, nexinets, nexinets::Nexinets, - nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, noon, noon::Noon, novalnet, - novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, - paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme, paypal, paypal::Paypal, - paystack, paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, - powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, - razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, shift4, shift4::Shift4, square, - square::Square, stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, - taxjar::Taxjar, thunes, thunes::Thunes, trustpay, trustpay::Trustpay, tsys, tsys::Tsys, - unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, - volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, worldline, worldline::Worldline, - worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, + digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, elavon, elavon::Elavon, facilitapay, + facilitapay::Facilitapay, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, + fiuu::Fiuu, forte, forte::Forte, getnet, getnet::Getnet, globalpay, globalpay::Globalpay, + globepay, globepay::Globepay, gocardless, gocardless::Gocardless, helcim, helcim::Helcim, + hipay, hipay::Hipay, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, + itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, + juspaythreedsserver::Juspaythreedsserver, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, + mollie, mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay, + nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, noon, + noon::Noon, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, + opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme, + paypal, paypal::Paypal, paystack, paystack::Paystack, payu, payu::Payu, placetopay, + placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, + rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, + shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, stripebilling, + stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, trustpay, + trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, + unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo, + wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit, + xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; #[cfg(feature = "dummy_connector")] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 5056660b6bd..11251cedc4e 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1369,6 +1369,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { elavon::transformers::ElavonAuthType::try_from(self.auth_type)?; Ok(()) } + // api_enums::Connector::Facilitapay => { + // facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; + // Ok(()) + // } api_enums::Connector::Fiserv => { fiserv::transformers::FiservAuthType::try_from(self.auth_type)?; fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 3801240864b..4f83abb9c12 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -1963,7 +1963,7 @@ fn handle_post_capture_response( )), _ => { logger::error!( - "Error in post capture_router_data response: {:?}, Current Status: {:?}. Proceeding without updating.", + "Error in post capture_router_data response: {:?}, Current Status: {:?}. Proceeding without updating.", post_capture_router_data.response, post_capture_router_data.status, ); diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 0a7a1f01b44..2b0625319c0 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -391,6 +391,9 @@ impl ConnectorData { enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } + // enums::Connector::Facilitapay => { + // Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay))) + // } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index ac8ac703f59..847298db98c 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -242,6 +242,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Elavon => Self::Elavon, + // api_enums::Connector::Facilitapay => Self::Facilitapay, api_enums::Connector::Fiserv => Self::Fiserv, api_enums::Connector::Fiservemea => Self::Fiservemea, api_enums::Connector::Fiuu => Self::Fiuu, diff --git a/crates/router/tests/connectors/facilitapay.rs b/crates/router/tests/connectors/facilitapay.rs new file mode 100644 index 00000000000..717eeb916f1 --- /dev/null +++ b/crates/router/tests/connectors/facilitapay.rs @@ -0,0 +1,421 @@ +use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; +use masking::Secret; +use router::types::{self, api, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct FacilitapayTest; +impl ConnectorActions for FacilitapayTest {} +impl utils::Connector for FacilitapayTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Facilitapay; + utils::construct_connector_data_old( + Box::new(Facilitapay::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .facilitapay + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "facilitapay".to_string() + } +} + +static CONNECTOR: FacilitapayTest = FacilitapayTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 1efefa90bec..018e4220d09 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -34,6 +34,7 @@ mod dlocal; mod dummyconnector; mod ebanx; mod elavon; +mod facilitapay; mod fiserv; mod fiservemea; mod fiuu; @@ -91,7 +92,6 @@ mod taxjar; mod trustpay; mod tsys; mod unified_authentication_service; - mod utils; mod volt; mod wellsfargo; diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 5ce2561af27..c12563303c5 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -41,6 +41,7 @@ pub struct ConnectorAuthentication { pub dummyconnector: Option<HeaderKey>, pub ebanx: Option<HeaderKey>, pub elavon: Option<HeaderKey>, + pub facilitapay: Option<BodyKey>, pub fiserv: Option<SignatureKey>, pub fiservemea: Option<HeaderKey>, pub fiuu: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index a468b970666..eac7fb71212 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -106,6 +106,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" @@ -220,6 +221,7 @@ cards = [ "dummyconnector", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 0473e6780dc..75de021f04d 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim hipay iatapay inespay itaubank jpmorgan juspaythreedsserver klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon facilitapay fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim hipay iatapay inespay itaubank jpmorgan juspaythreedsserver klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2025-03-25T16:11:16Z
## Description <!-- Describe your changes in detail --> This PR introduces template code for new connector named `Facilitapay`. Docs: https://sandbox-portal.facilitapay.com/#/docs ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> New connector -- Facilitapay Closes #7630 #
60d5c779e9ace4cb95bdbe9a2c9277c41ce96573
```sh just clippy cargo +nightly fmt --all cargo c ``` Hyperswitch code base should compile.
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/common_enums/src/connector_enums.rs", "crates/connector_configs/src/connector.rs", "crates/hyperswitch_connectors/src/connectors.rs", "crates/hyperswitch_connectors/src/connectors/facilitapay.rs", "crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs", "crates/hyperswitch_connectors/src/default_implementations.rs", "crates/hyperswitch_connectors/src/default_implementations_v2.rs", "crates/hyperswitch_domain_models/src/configs.rs", "crates/router/src/connector.rs", "crates/router/src/core/admin.rs", "crates/router/src/core/payments/flows.rs", "crates/router/src/types/api.rs", "crates/router/src/types/transformers.rs", "crates/router/tests/connectors/facilitapay.rs", "crates/router/tests/connectors/main.rs", "crates/test_utils/src/connector_auth.rs", "loadtest/config/development.toml", "scripts/add_connector.sh" ]
juspay/hyperswitch
juspay__hyperswitch-7620
Bug: feat(cypress): `connectorUpdateCall` fails due to fixtures overwrite The `connectorUpdateCall` fails in the Cypress Tests for connectors for which a certain metadata field is `required` (for e.g., `Braintree`) because the `cypress-tests/cypress/fixtures/update-connector-body.json` overwrites the Request Body.
2025-03-25T10:14:57Z
## Description <!-- Describe your changes in detail --> The Connector Update Body is being overwritten, which included the metadata as well. Due to this, if there were any required metadata fields of a connector, then the Connector Update Test would fail. For example, `Braintree` connector has a required metadata field, and while testing the Connector Update, just because it was being overwritten by the `update-connector-body.json` fixture, the test fails as shown in the following screenshot. <img width="2117" alt="image" src="https://github.com/user-attachments/assets/bf8b384a-92be-4f86-bf09-48fd52f01db4" /> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> While adding the Card test Flows for the `Braintree` connector, the Connector Update Test Failed. #
00e056800cb2c75c4dfbed6a4451658fda9c4a86
Running the `0000-CoreFlows.cy.js` for `Braintree` connector <img width="2116" alt="image" src="https://github.com/user-attachments/assets/7b505791-4da3-4fae-a94c-142dcfc69b53" /> <img width="752" alt="image" src="https://github.com/user-attachments/assets/f9fc5350-4bf9-4b2e-a5da-a62264f5c1b1" />
[]
juspay/hyperswitch
juspay__hyperswitch-7621
Bug: [FEATURE]: Add refunds create core flow for v2 apis. Implement refunds create core flow for v2 apis.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 3125f3ac29c..10682866ab7 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -20357,82 +20357,6 @@ } } }, - "RefundRequest": { - "type": "object", - "required": [ - "payment_id" - ], - "properties": { - "payment_id": { - "type": "string", - "description": "The payment id against which refund is to be initiated", - "example": "pay_mbabizu24mvu3mela5njyhpit4", - "maxLength": 30, - "minLength": 30 - }, - "refund_id": { - "type": "string", - "description": "Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id.", - "example": "ref_mbabizu24mvu3mela5njyhpit4", - "nullable": true, - "maxLength": 30, - "minLength": 30 - }, - "merchant_id": { - "type": "string", - "description": "The identifier for the Merchant Account", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", - "nullable": true, - "maxLength": 255 - }, - "amount": { - "type": "integer", - "format": "int64", - "description": "Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount", - "example": 6540, - "nullable": true, - "minimum": 100 - }, - "reason": { - "type": "string", - "description": "Reason for the refund. Often useful for displaying to users and your customer support executive. In case the payment went through Stripe, this field needs to be passed with one of these enums: `duplicate`, `fraudulent`, or `requested_by_customer`", - "example": "Customer returned the product", - "nullable": true, - "maxLength": 255 - }, - "refund_type": { - "allOf": [ - { - "$ref": "#/components/schemas/RefundType" - } - ], - "default": "Instant", - "nullable": true - }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true - }, - "merchant_connector_details": { - "allOf": [ - { - "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" - } - ], - "nullable": true - }, - "split_refunds": { - "allOf": [ - { - "$ref": "#/components/schemas/SplitRefund" - } - ], - "nullable": true - } - }, - "additionalProperties": false - }, "RefundResponse": { "type": "object", "required": [ @@ -20535,7 +20459,7 @@ }, "RefundType": { "type": "string", - "description": "To indicate whether to refund needs to be instant or scheduled", + "description": "To indicate whether the refund needs to be instant or scheduled", "enum": [ "scheduled", "instant" @@ -20562,7 +20486,8 @@ "RefundsCreateRequest": { "type": "object", "required": [ - "payment_id" + "payment_id", + "merchant_reference_id" ], "properties": { "payment_id": { @@ -20574,11 +20499,17 @@ }, "merchant_reference_id": { "type": "string", - "description": "Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment.", + "description": "Unique Identifier for the Refund given by the Merchant.", "example": "ref_mbabizu24mvu3mela5njyhpit4", + "maxLength": 64, + "minLength": 1 + }, + "merchant_id": { + "type": "string", + "description": "The identifier for the Merchant Account", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", "nullable": true, - "maxLength": 30, - "minLength": 30 + "maxLength": 255 }, "amount": { "type": "integer", diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index f89558e6267..327406c198c 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -17,9 +17,10 @@ olap = [] openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"] recon = [] v1 = ["common_utils/v1"] -v2 = ["common_types/v2", "common_utils/v2", "customer_v2"] +v2 = ["common_types/v2", "common_utils/v2", "customer_v2", "refunds_v2"] customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2"] +refunds_v2 = [] dynamic_routing = [] control_center_theme = ["dep:actix-web", "dep:actix-multipart"] revenue_recovery = [] diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rs index e87ae154471..888918d836e 100644 --- a/crates/api_models/src/events/refund.rs +++ b/crates/api_models/src/events/refund.rs @@ -1,9 +1,13 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; +#[cfg(feature = "v1")] +use crate::refunds::RefundRequest; +#[cfg(feature = "v2")] +use crate::refunds::RefundsCreateRequest; use crate::refunds::{ RefundAggregateResponse, RefundListFilters, RefundListMetaData, RefundListRequest, - RefundListResponse, RefundManualUpdateRequest, RefundRequest, RefundResponse, - RefundUpdateRequest, RefundsRetrieveRequest, + RefundListResponse, RefundManualUpdateRequest, RefundResponse, RefundUpdateRequest, + RefundsRetrieveRequest, }; #[cfg(feature = "v1")] @@ -19,6 +23,13 @@ impl ApiEventMetric for RefundRequest { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for RefundsCreateRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + None + } +} + #[cfg(feature = "v1")] impl ApiEventMetric for RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index ece1edb72bd..e9a7a77592d 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -12,6 +12,7 @@ use crate::{ enums, }; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundRequest { @@ -61,7 +62,7 @@ pub struct RefundRequest { pub split_refunds: Option<common_types::refunds::SplitRefund>, } -#[cfg(feature = "v2")] +#[cfg(all(feature = "v2", feature = "refunds_v2"))] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundsCreateRequest { @@ -74,14 +75,18 @@ pub struct RefundsCreateRequest { )] pub payment_id: common_utils::id_type::GlobalPaymentId, - /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. + /// Unique Identifier for the Refund given by the Merchant. #[schema( - max_length = 30, - min_length = 30, + max_length = 64, + min_length = 1, example = "ref_mbabizu24mvu3mela5njyhpit4", - value_type = Option<String>, + value_type = String, )] - pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>, + pub merchant_reference_id: common_utils::id_type::RefundReferenceId, + + /// The identifier for the Merchant Account + #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] + pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] @@ -153,6 +158,7 @@ pub struct RefundManualUpdateRequest { pub error_message: Option<String>, } +#[cfg(feature = "v1")] /// To indicate whether to refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, @@ -164,6 +170,18 @@ pub enum RefundType { Instant, } +#[cfg(feature = "v2")] +/// To indicate whether the refund needs to be instant or scheduled +#[derive( + Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, +)] +#[serde(rename_all = "snake_case")] +pub enum RefundType { + Scheduled, + #[default] + Instant, +} + #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 4b24cf281cb..0dbf026263f 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1204,6 +1204,14 @@ impl ConnectorTransactionId { } } + /// Implementation for extracting hashed data + pub fn extract_hashed_data(&self) -> Option<String> { + match self { + Self::TxnId(_) => None, + Self::HashedData(src) => Some(src.clone()), + } + } + /// Implementation for retrieving pub fn get_txn_id<'a>( &'a self, diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index cfcbc2bd199..2543ab41461 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -161,6 +161,29 @@ impl PaymentAttempt { .ok_or(report!(DatabaseError::NotFound)) } + #[cfg(feature = "v2")] + pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id( + conn: &PgPooledConn, + payment_id: &common_utils::id_type::GlobalPaymentId, + ) -> StorageResult<Self> { + // perform ordering on the application level instead of database level + generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( + conn, + dsl::payment_id.eq(payment_id.to_owned()).and( + dsl::status + .eq(enums::AttemptStatus::Charged) + .or(dsl::status.eq(enums::AttemptStatus::PartialCharged)), + ), + Some(1), + None, + Some(dsl::modified_at.desc()), + ) + .await? + .into_iter() + .nth(0) + .ok_or(report!(DatabaseError::NotFound)) + } + #[cfg(feature = "v1")] pub async fn find_by_merchant_id_connector_txn_id( conn: &PgPooledConn, diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs index adae21c413f..cf42134cab0 100644 --- a/crates/diesel_models/src/query/refund.rs +++ b/crates/diesel_models/src/query/refund.rs @@ -170,4 +170,26 @@ impl Refund { ) .await } + + pub async fn find_by_merchant_id_connector_transaction_id( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + connector_transaction_id: &str, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::< + <Self as HasTable>::Table, + _, + <<Self as HasTable>::Table as Table>::PrimaryKey, + _, + >( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())), + None, + None, + None, + ) + .await + } } diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index 6a40baba9dd..e197bc3c211 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -11,7 +11,6 @@ use crate::enums as storage_enums; use crate::schema::refund; #[cfg(all(feature = "v2", feature = "refunds_v2"))] use crate::schema_v2::refund; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive( Clone, @@ -702,8 +701,65 @@ impl RefundUpdate { ..source } } + + pub fn build_error_update_for_unified_error_and_message( + unified_error_object: (String, String), + refund_error_message: Option<String>, + refund_error_code: Option<String>, + storage_scheme: &storage_enums::MerchantStorageScheme, + ) -> Self { + let (unified_code, unified_message) = unified_error_object; + + Self::ErrorUpdate { + refund_status: Some(storage_enums::RefundStatus::Failure), + refund_error_message, + refund_error_code, + updated_by: storage_scheme.to_string(), + connector_refund_id: None, + processor_refund_data: None, + unified_code: Some(unified_code), + unified_message: Some(unified_message), + } + } + + pub fn build_error_update_for_integrity_check_failure( + integrity_check_failed_fields: String, + connector_refund_id: Option<ConnectorTransactionId>, + storage_scheme: &storage_enums::MerchantStorageScheme, + ) -> Self { + Self::ErrorUpdate { + refund_status: Some(storage_enums::RefundStatus::ManualReview), + refund_error_message: Some(format!( + "Integrity Check Failed! as data mismatched for fields {}", + integrity_check_failed_fields + )), + refund_error_code: Some("IE".to_string()), + updated_by: storage_scheme.to_string(), + connector_refund_id: connector_refund_id.clone(), + processor_refund_data: connector_refund_id.and_then(|x| x.extract_hashed_data()), + unified_code: None, + unified_message: None, + } + } + + pub fn build_refund_update( + connector_refund_id: ConnectorTransactionId, + refund_status: storage_enums::RefundStatus, + storage_scheme: &storage_enums::MerchantStorageScheme, + ) -> Self { + Self::Update { + connector_refund_id: connector_refund_id.clone(), + refund_status, + sent_to_gateway: true, + refund_error_message: None, + refund_arn: "".to_string(), + updated_by: storage_scheme.to_string(), + processor_refund_data: connector_refund_id.extract_hashed_data(), + } + } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, @@ -713,6 +769,16 @@ pub struct RefundCoreWorkflow { pub processor_transaction_data: Option<String>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] +pub struct RefundCoreWorkflow { + pub refund_id: common_utils::id_type::GlobalRefundId, + pub connector_transaction_id: ConnectorTransactionId, + pub merchant_id: common_utils::id_type::MerchantId, + pub payment_id: common_utils::id_type::GlobalPaymentId, + pub processor_transaction_data: Option<String>, +} + #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 90ba708c109..8179fd66581 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -674,6 +674,29 @@ impl PaymentIntent { pub fn get_feature_metadata(&self) -> Option<FeatureMetadata> { self.feature_metadata.clone() } + + pub fn get_optional_customer_id( + &self, + ) -> CustomResult<Option<id_type::CustomerId>, common_utils::errors::ValidationError> { + self.customer_id + .as_ref() + .map(|customer_id| id_type::CustomerId::try_from(customer_id.clone())) + .transpose() + } + + pub fn get_optional_connector_metadata( + &self, + ) -> CustomResult< + Option<api_models::payments::ConnectorMetadata>, + common_utils::errors::ParsingError, + > { + self.connector_metadata + .clone() + .map(|cm| { + cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") + }) + .transpose() + } } #[cfg(feature = "v1")] diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 494950d42c4..69e5064e6e1 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -117,6 +117,15 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; + #[cfg(feature = "v2")] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_id: &id_type::GlobalPaymentId, + storage_scheme: storage_enums::MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, Self::Error>; + #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, @@ -1014,7 +1023,7 @@ impl PaymentAttempt { } pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { - todo!(); + self.amount_details.surcharge_amount } } diff --git a/crates/openapi/Cargo.toml b/crates/openapi/Cargo.toml index 7e7e5a6fb3c..33c48e2f0ae 100644 --- a/crates/openapi/Cargo.toml +++ b/crates/openapi/Cargo.toml @@ -17,7 +17,7 @@ common_types = { version = "0.1.0", path = "../common_types" } router_env = { version = "0.1.0", path = "../router_env" } [features] -v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2"] +v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2", "api_models/refunds_v2"] v1 = ["api_models/v1", "common_utils/v1"] [lints] diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index d2404e1069d..2629b1b8b7d 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -186,7 +186,6 @@ Never share your secret api keys. Keep them guarded and secure. common_types::refunds::SplitRefund, common_types::payments::ConnectorChargeResponseData, common_types::payments::StripeChargeResponseData, - api_models::refunds::RefundRequest, api_models::refunds::RefundsCreateRequest, api_models::refunds::RefundErrorDetails, api_models::refunds::RefundType, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 0eae31ace87..7dfb87c3669 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -39,7 +39,7 @@ customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswit payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery","hyperswitch_connectors/revenue_recovery"] -refunds_v2 = ["diesel_models/refunds_v2", "storage_impl/refunds_v2"] +refunds_v2 = ["api_models/refunds_v2", "diesel_models/refunds_v2", "storage_impl/refunds_v2"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request. diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 83c1058b426..e96aa339e9e 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -42,6 +42,9 @@ pub mod poll; pub mod recon; #[cfg(feature = "v1")] pub mod refunds; +#[cfg(feature = "v2")] +pub mod refunds_v2; + pub mod routing; pub mod surcharge_decision_config; #[cfg(feature = "olap")] diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 6e576509a18..649e9ea57a0 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1,6 +1,3 @@ -pub mod transformers; -pub mod validator; - #[cfg(feature = "olap")] use std::collections::HashMap; @@ -27,7 +24,10 @@ use crate::{ errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}, payments::{self, access_token, helpers}, refunds::transformers::SplitRefundInput, - utils as core_utils, + utils::{ + self as core_utils, refunds_transformers as transformers, + refunds_validator as validator, + }, }, db, logger, routes::{metrics, SessionState}, diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs new file mode 100644 index 00000000000..7186bb76bff --- /dev/null +++ b/crates/router/src/core/refunds_v2.rs @@ -0,0 +1,840 @@ +use std::str::FromStr; + +use api_models::{enums::Connector, refunds::RefundErrorDetails}; +use common_utils::{id_type, types as common_utils_types}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData}; +use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; +use router_env::{instrument, tracing}; + +use crate::{ + consts, + core::{ + errors::{self, ConnectorErrorExt, StorageErrorExt}, + payments::{self, access_token, helpers}, + utils::{self as core_utils, refunds_validator}, + }, + db, logger, + routes::{metrics, SessionState}, + services, + types::{ + self, + api::{self, refunds}, + domain, + storage::{self, enums}, + transformers::{ForeignFrom, ForeignTryFrom}, + }, + utils, +}; + +#[instrument(skip_all)] +pub async fn refund_create_core( + state: SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + req: refunds::RefundsCreateRequest, +) -> errors::RouterResponse<refunds::RefundResponse> { + let db = &*state.store; + let (payment_intent, payment_attempt, amount); + + payment_intent = db + .find_payment_intent_by_id( + &(&state).into(), + &req.payment_id, + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + utils::when( + !(payment_intent.status == enums::IntentStatus::Succeeded + || payment_intent.status == enums::IntentStatus::PartiallyCaptured), + || { + Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { + current_flow: "refund".into(), + field_name: "status".into(), + current_value: payment_intent.status.to_string(), + states: "succeeded, partially_captured".to_string() + }) + .attach_printable("unable to refund for a unsuccessful payment intent")) + }, + )?; + + let captured_amount = payment_intent + .amount_captured + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("amount captured is none in a successful payment")?; + + // Amount is not passed in request refer from payment intent. + amount = req.amount.unwrap_or(captured_amount); + + utils::when(amount <= common_utils_types::MinorUnit::new(0), || { + Err(report!(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "amount".to_string(), + expected_format: "positive integer".to_string() + }) + .attach_printable("amount less than or equal to zero")) + })?; + + payment_attempt = db + .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &(&state).into(), + &key_store, + &req.payment_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; + + let global_refund_id = id_type::GlobalRefundId::generate(&state.conf.cell_information.id); + + tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr()); + + Box::pin(validate_and_create_refund( + &state, + &merchant_account, + &key_store, + &payment_attempt, + &payment_intent, + amount, + req, + global_refund_id, + )) + .await + .map(services::ApplicationResponse::Json) +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +pub async fn trigger_refund_to_gateway( + state: &SessionState, + refund: &storage::Refund, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, +) -> errors::RouterResult<storage::Refund> { + let db = &*state.store; + + let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?; + + let storage_scheme = merchant_account.storage_scheme; + + let mca = db + .find_merchant_connector_account_by_id(&state.into(), &mca_id, key_store) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant connector account")?; + + metrics::REFUND_COUNT.add( + 1, + router_env::metric_attributes!(("connector", mca_id.get_string_repr().to_string())), + ); + + let connector_enum = mca.connector_name; + + let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_enum.to_string(), + api::GetToken::Connector, + Some(mca_id.clone()), + )?; + + refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; + + let mut router_data = core_utils::construct_refund_router_data( + state, + connector_enum, + merchant_account, + key_store, + payment_intent, + payment_attempt, + refund, + &mca, + ) + .await?; + + let add_access_token_result = + access_token::add_access_token(state, &connector, merchant_account, &router_data, None) + .await?; + + logger::debug!(refund_router_data=?router_data); + + access_token::update_router_data_with_access_token_result( + &add_access_token_result, + &mut router_data, + &payments::CallConnectorAction::Trigger, + ); + + let connector_response = + call_connector_service(state, &connector, add_access_token_result, router_data).await; + + let refund_update = get_refund_update_object( + state, + &connector, + &storage_scheme, + merchant_account, + &connector_response, + ) + .await; + + let response = match refund_update { + Some(refund_update) => state + .store + .update_refund( + refund.to_owned(), + refund_update, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Failed while updating refund: refund_id: {}", + refund.id.get_string_repr() + ) + })?, + None => refund.to_owned(), + }; + // Implement outgoing webhooks here + connector_response.to_refund_failed_response()?; + Ok(response) +} + +async fn call_connector_service( + state: &SessionState, + connector: &api::ConnectorData, + add_access_token_result: types::AddAccessTokenResult, + router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, +) -> Result< + RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + error_stack::Report<errors::ConnectorError>, +> { + if !(add_access_token_result.connector_supports_access_token + && router_data.access_token.is_none()) + { + let connector_integration: services::BoxedRefundConnectorIntegrationInterface< + api::Execute, + types::RefundsData, + types::RefundsResponseData, + > = connector.connector.get_connector_integration(); + services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + } else { + Ok(router_data) + } +} + +async fn get_refund_update_object( + state: &SessionState, + connector: &api::ConnectorData, + storage_scheme: &enums::MerchantStorageScheme, + merchant_account: &domain::MerchantAccount, + router_data_response: &Result< + RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + error_stack::Report<errors::ConnectorError>, + >, +) -> Option<storage::RefundUpdate> { + match router_data_response { + // This error is related to connector implementation i.e if no implementation for refunds for that specific connector in HS or the connector does not support refund itself. + Err(err) => get_connector_implementation_error_refund_update(err, *storage_scheme), + Ok(response) => { + let response = perform_integrity_check(response.clone()); + match response.response.clone() { + Err(err) => Some( + get_connector_error_refund_update(state, err, connector, storage_scheme).await, + ), + Ok(refund_response_data) => Some(get_refund_update_for_refund_response_data( + response, + connector, + refund_response_data, + storage_scheme, + merchant_account, + )), + } + } + } +} + +fn get_connector_implementation_error_refund_update( + error: &error_stack::Report<errors::ConnectorError>, + storage_scheme: enums::MerchantStorageScheme, +) -> Option<storage::RefundUpdate> { + Option::<storage::RefundUpdate>::foreign_from((error.current_context(), storage_scheme)) +} + +async fn get_connector_error_refund_update( + state: &SessionState, + err: ErrorResponse, + connector: &api::ConnectorData, + storage_scheme: &enums::MerchantStorageScheme, +) -> storage::RefundUpdate { + let unified_error_object = get_unified_error_and_message(state, &err, connector).await; + + storage::RefundUpdate::build_error_update_for_unified_error_and_message( + unified_error_object, + err.reason.or(Some(err.message)), + Some(err.code), + storage_scheme, + ) +} + +async fn get_unified_error_and_message( + state: &SessionState, + err: &ErrorResponse, + connector: &api::ConnectorData, +) -> (String, String) { + let option_gsm = helpers::get_gsm_record( + state, + Some(err.code.clone()), + Some(err.message.clone()), + connector.connector_name.to_string(), + consts::REFUND_FLOW_STR.to_string(), + ) + .await; + // Note: Some connectors do not have a separate list of refund errors + // In such cases, the error codes and messages are stored under "Authorize" flow in GSM table + // So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow" + let option_gsm = if option_gsm.is_none() { + helpers::get_gsm_record( + state, + Some(err.code.clone()), + Some(err.message.clone()), + connector.connector_name.to_string(), + consts::AUTHORIZE_FLOW_STR.to_string(), + ) + .await + } else { + option_gsm + }; + + let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()); + let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message); + + match gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) { + Some((code, message)) => (code.to_owned(), message.to_owned()), + None => ( + consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), + consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), + ), + } +} + +pub fn get_refund_update_for_refund_response_data( + router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + connector: &api::ConnectorData, + refund_response_data: types::RefundsResponseData, + storage_scheme: &enums::MerchantStorageScheme, + merchant_account: &domain::MerchantAccount, +) -> storage::RefundUpdate { + // match on connector integrity checks + match router_data.integrity_check.clone() { + Err(err) => { + let connector_refund_id = err + .connector_transaction_id + .map(common_utils_types::ConnectorTransactionId::from); + + metrics::INTEGRITY_CHECK_FAILED.add( + 1, + router_env::metric_attributes!( + ("connector", connector.connector_name.to_string()), + ("merchant_id", merchant_account.get_id().clone()), + ), + ); + + storage::RefundUpdate::build_error_update_for_integrity_check_failure( + err.field_names, + connector_refund_id, + storage_scheme, + ) + } + Ok(()) => { + if refund_response_data.refund_status == diesel_models::enums::RefundStatus::Success { + metrics::SUCCESSFUL_REFUND.add( + 1, + router_env::metric_attributes!(( + "connector", + connector.connector_name.to_string(), + )), + ) + } + + let connector_refund_id = common_utils_types::ConnectorTransactionId::from( + refund_response_data.connector_refund_id, + ); + + storage::RefundUpdate::build_refund_update( + connector_refund_id, + refund_response_data.refund_status, + storage_scheme, + ) + } + } +} + +pub fn perform_integrity_check( + mut router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, +) -> RouterData<api::Execute, types::RefundsData, types::RefundsResponseData> { + // Initiating Integrity check + let integrity_result = check_refund_integrity(&router_data.request, &router_data.response); + router_data.integrity_check = integrity_result; + router_data +} + +impl ForeignFrom<(&errors::ConnectorError, enums::MerchantStorageScheme)> + for Option<storage::RefundUpdate> +{ + fn foreign_from( + (from, storage_scheme): (&errors::ConnectorError, enums::MerchantStorageScheme), + ) -> Self { + match from { + errors::ConnectorError::NotImplemented(message) => { + Some(storage::RefundUpdate::ErrorUpdate { + refund_status: Some(enums::RefundStatus::Failure), + refund_error_message: Some( + errors::ConnectorError::NotImplemented(message.to_owned()).to_string(), + ), + refund_error_code: Some("NOT_IMPLEMENTED".to_string()), + updated_by: storage_scheme.to_string(), + connector_refund_id: None, + processor_refund_data: None, + unified_code: None, + unified_message: None, + }) + } + errors::ConnectorError::NotSupported { message, connector } => { + Some(storage::RefundUpdate::ErrorUpdate { + refund_status: Some(enums::RefundStatus::Failure), + refund_error_message: Some(format!( + "{message} is not supported by {connector}" + )), + refund_error_code: Some("NOT_SUPPORTED".to_string()), + updated_by: storage_scheme.to_string(), + connector_refund_id: None, + processor_refund_data: None, + unified_code: None, + unified_message: None, + }) + } + _ => None, + } + } +} + +pub fn check_refund_integrity<T, Request>( + request: &Request, + refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>, +) -> Result<(), common_utils::errors::IntegrityCheckError> +where + T: FlowIntegrity, + Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, +{ + let connector_refund_id = refund_response_data + .as_ref() + .map(|resp_data| resp_data.connector_refund_id.clone()) + .ok(); + + request.check_integrity(request, connector_refund_id.to_owned()) +} + +// ********************************************** VALIDATIONS ********************************************** + +#[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] +pub async fn validate_and_create_refund( + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, + refund_amount: common_utils_types::MinorUnit, + req: refunds::RefundsCreateRequest, + global_refund_id: id_type::GlobalRefundId, +) -> errors::RouterResult<refunds::RefundResponse> { + let db = &*state.store; + + let refund_type = req.refund_type.unwrap_or_default(); + + let merchant_reference_id = req.merchant_reference_id; + + let predicate = req + .merchant_id + .as_ref() + .map(|merchant_id| merchant_id != merchant_account.get_id()); + + utils::when(predicate.unwrap_or(false), || { + Err(report!(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "merchant_id".to_string(), + expected_format: "merchant_id from merchant account".to_string() + }) + .attach_printable("invalid merchant_id in request")) + })?; + + let connector_payment_id = payment_attempt.clone().connector_payment_id.ok_or_else(|| { + report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.") + })?; + + let all_refunds = db + .find_refund_by_merchant_id_connector_transaction_id( + merchant_account.get_id(), + &connector_payment_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; + + let currency = payment_intent.amount_details.currency; + + refunds_validator::validate_payment_order_age( + &payment_intent.created_at, + state.conf.refund.max_age, + ) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "created_at".to_string(), + expected_format: format!( + "created_at not older than {} days", + state.conf.refund.max_age, + ), + })?; + + let total_amount_captured = payment_intent + .amount_captured + .unwrap_or(payment_attempt.get_total_amount()); + + refunds_validator::validate_refund_amount( + total_amount_captured.get_amount_as_i64(), + &all_refunds, + refund_amount.get_amount_as_i64(), + ) + .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?; + + refunds_validator::validate_maximum_refund_against_payment_attempt( + &all_refunds, + state.conf.refund.max_attempts, + ) + .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; + + let connector = payment_attempt + .connector + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("No connector populated in payment attempt")?; + let (connector_transaction_id, processor_transaction_data) = + common_utils_types::ConnectorTransactionId::form_id_and_data(connector_payment_id); + let refund_create_req = storage::RefundNew { + id: global_refund_id, + merchant_reference_id: merchant_reference_id.clone(), + external_reference_id: Some(merchant_reference_id.get_string_repr().to_string()), + payment_id: req.payment_id, + merchant_id: merchant_account.get_id().clone(), + connector_transaction_id, + connector, + refund_type: enums::RefundType::foreign_from(req.refund_type.unwrap_or_default()), + total_amount: payment_attempt.get_total_amount(), + refund_amount, + currency, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + refund_status: enums::RefundStatus::Pending, + metadata: req.metadata, + description: req.reason.clone(), + attempt_id: payment_attempt.id.clone(), + refund_reason: req.reason, + profile_id: Some(payment_intent.profile_id.clone()), + connector_id: payment_attempt.merchant_connector_id.clone(), + charges: None, + split_refunds: None, + connector_refund_id: None, + sent_to_gateway: Default::default(), + refund_arn: None, + updated_by: Default::default(), + organization_id: merchant_account.organization_id.clone(), + processor_transaction_data, + processor_refund_data: None, + }; + + let refund = match db + .insert_refund(refund_create_req, merchant_account.storage_scheme) + .await + { + Ok(refund) => { + Box::pin(schedule_refund_execution( + state, + refund.clone(), + refund_type, + merchant_account, + key_store, + payment_attempt, + payment_intent, + )) + .await? + } + Err(err) => { + if err.current_context().is_db_unique_violation() { + Err(errors::ApiErrorResponse::DuplicateRefundRequest)? + } else { + Err(err) + .change_context(errors::ApiErrorResponse::RefundFailed { data: None }) + .attach_printable("Failed to insert refund")? + } + } + }; + + let unified_translated_message = + match (refund.unified_code.clone(), refund.unified_message.clone()) { + (Some(unified_code), Some(unified_message)) => helpers::get_unified_translation( + state, + unified_code, + unified_message.clone(), + state.locale.to_string(), + ) + .await + .or(Some(unified_message)), + _ => refund.unified_message, + }; + + let refund = storage::Refund { + unified_message: unified_translated_message, + ..refund + }; + + api::RefundResponse::foreign_try_from(refund) +} + +impl ForeignTryFrom<storage::Refund> for api::RefundResponse { + type Error = error_stack::Report<errors::ApiErrorResponse>; + fn foreign_try_from(refund: storage::Refund) -> Result<Self, Self::Error> { + let refund = refund; + + let profile_id = refund + .profile_id + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Profile id not found")?; + + let merchant_connector_id = refund + .connector_id + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector id not found")?; + + let connector_name = refund.connector; + let connector = Connector::from_str(&connector_name) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector_name:?}") + })?; + + Ok(Self { + payment_id: refund.payment_id, + id: refund.id.clone(), + amount: refund.refund_amount, + currency: refund.currency, + reason: refund.refund_reason, + status: refunds::RefundStatus::foreign_from(refund.refund_status), + profile_id, + metadata: refund.metadata, + created_at: refund.created_at, + updated_at: refund.modified_at, + connector, + merchant_connector_id, + merchant_reference_id: Some(refund.merchant_reference_id), + error_details: Some(RefundErrorDetails { + code: refund.refund_error_code.unwrap_or_default(), + message: refund.refund_error_message.unwrap_or_default(), + }), + connector_refund_reference_id: None, + }) + } +} + +// ********************************************** PROCESS TRACKER ********************************************** + +#[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] +pub async fn schedule_refund_execution( + state: &SessionState, + refund: storage::Refund, + refund_type: api_models::refunds::RefundType, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, +) -> errors::RouterResult<storage::Refund> { + let db = &*state.store; + let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; + let task = "EXECUTE_REFUND"; + let task_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); + + let refund_process = db + .find_process_by_id(&task_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to find the process id")?; + + let result = match refund.refund_status { + enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => { + match (refund.sent_to_gateway, refund_process) { + (false, None) => { + // Execute the refund task based on refund_type + match refund_type { + api_models::refunds::RefundType::Scheduled => { + add_refund_execute_task(db, &refund, runner) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.id.get_string_repr()))?; + + Ok(refund) + } + api_models::refunds::RefundType::Instant => { + let update_refund = Box::pin(trigger_refund_to_gateway( + state, + &refund, + merchant_account, + key_store, + payment_attempt, + payment_intent, + )) + .await; + + match update_refund { + Ok(updated_refund_data) => { + add_refund_sync_task(db, &updated_refund_data, runner) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| format!( + "Failed while pushing refund sync task in scheduler: refund_id: {}", + refund.id.get_string_repr() + ))?; + Ok(updated_refund_data) + } + Err(err) => Err(err), + } + } + } + } + _ => { + // Sync the refund for status check + //[#300]: return refund status response + match refund_type { + api_models::refunds::RefundType::Scheduled => { + add_refund_sync_task(db, &refund, runner) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr()))?; + Ok(refund) + } + api_models::refunds::RefundType::Instant => { + // [#255]: This is not possible in schedule_refund_execution as it will always be scheduled + // sync_refund_with_gateway(data, &refund).await + Ok(refund) + } + } + } + } + } + // [#255]: This is not allowed to be otherwise or all + _ => Ok(refund), + }?; + Ok(result) +} + +#[instrument] +pub fn refund_to_refund_core_workflow_model( + refund: &storage::Refund, +) -> storage::RefundCoreWorkflow { + storage::RefundCoreWorkflow { + refund_id: refund.id.clone(), + connector_transaction_id: refund.connector_transaction_id.clone(), + merchant_id: refund.merchant_id.clone(), + payment_id: refund.payment_id.clone(), + processor_transaction_data: refund.processor_transaction_data.clone(), + } +} + +#[instrument(skip_all)] +pub async fn add_refund_execute_task( + db: &dyn db::StorageInterface, + refund: &storage::Refund, + runner: storage::ProcessTrackerRunner, +) -> errors::RouterResult<storage::ProcessTracker> { + let task = "EXECUTE_REFUND"; + let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); + let tag = ["REFUND"]; + let schedule_time = common_utils::date_time::now(); + let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + refund_workflow_tracking_data, + None, + schedule_time, + common_types::consts::API_VERSION, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct refund execute process tracker task")?; + + let response = db + .insert_process(process_tracker_entry) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) + .attach_printable_lazy(|| { + format!( + "Failed while inserting task in process_tracker: refund_id: {}", + refund.id.get_string_repr() + ) + })?; + Ok(response) +} + +#[instrument(skip_all)] +pub async fn add_refund_sync_task( + db: &dyn db::StorageInterface, + refund: &storage::Refund, + runner: storage::ProcessTrackerRunner, +) -> errors::RouterResult<storage::ProcessTracker> { + let task = "SYNC_REFUND"; + let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); + let schedule_time = common_utils::date_time::now(); + let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); + let tag = ["REFUND"]; + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + refund_workflow_tracking_data, + None, + schedule_time, + common_types::consts::API_VERSION, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct refund sync process tracker task")?; + + let response = db + .insert_process(process_tracker_entry) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) + .attach_printable_lazy(|| { + format!( + "Failed while inserting task in process_tracker: refund_id: {}", + refund.id.get_string_repr() + ) + })?; + metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund"))); + + Ok(response) +} diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 87dce4ade0b..35901ed8ac3 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1,6 +1,9 @@ +pub mod refunds_transformers; +pub mod refunds_validator; + use std::{collections::HashSet, marker::PhantomData, str::FromStr}; -use api_models::enums::{DisputeStage, DisputeStatus}; +use api_models::enums::{Connector, DisputeStage, DisputeStatus}; #[cfg(feature = "payouts")] use api_models::payouts::PayoutVendorAccountDetails; use common_enums::{IntentStatus, RequestIncrementalAuthorization}; @@ -16,6 +19,8 @@ use hyperswitch_domain_models::{ merchant_connector_account::MerchantConnectorAccount, payment_address::PaymentAddress, router_data::ErrorResponse, router_request_types, types::OrderDetailsWithAmount, }; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use masking::ExposeOptionInterface; #[cfg(feature = "payouts")] use masking::{ExposeInterface, PeekInterface}; use maud::{html, PreEscaped}; @@ -232,18 +237,155 @@ pub async fn construct_payout_router_data<'a, F>( #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_refund_router_data<'a, F>( - _state: &'a SessionState, - _connector_id: &str, - _merchant_account: &domain::MerchantAccount, - _key_store: &domain::MerchantKeyStore, - _money: (MinorUnit, enums::Currency), - _payment_intent: &'a storage::PaymentIntent, - _payment_attempt: &storage::PaymentAttempt, - _refund: &'a storage::Refund, - _creds_identifier: Option<String>, - _split_refunds: Option<router_request_types::SplitRefundsRequest>, + state: &'a SessionState, + connector_enum: Connector, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_intent: &'a storage::PaymentIntent, + payment_attempt: &storage::PaymentAttempt, + refund: &'a storage::Refund, + merchant_connector_account: &MerchantConnectorAccount, ) -> RouterResult<types::RefundsRouterData<F>> { - todo!() + let auth_type = merchant_connector_account + .get_connector_account_details() + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + let status = payment_attempt.status; + + let payment_amount = payment_attempt.get_total_amount(); + let currency = payment_intent.amount_details.currency; + + let payment_method_type = payment_attempt.payment_method_type; + + let merchant_connector_account_id = &merchant_connector_account.id; + + let webhook_url = Some(helpers::create_webhook_url( + &state.base_url.clone(), + merchant_account.get_id(), + merchant_connector_account_id.get_string_repr(), + )); + + let supported_connector = &state + .conf + .multiple_api_version_supported_connectors + .supported_connectors; + + let connector_api_version = if supported_connector.contains(&connector_enum) { + state + .store + .find_config_by_key(&format!("connector_api_version_{connector_enum}")) + .await + .map(|value| value.config) + .ok() + } else { + None + }; + + let browser_info = payment_attempt + .browser_info + .clone() + .map(types::BrowserInformation::from); + + let connector_refund_id = refund.get_optional_connector_refund_id().cloned(); + let capture_method = payment_intent.capture_method; + + let customer_id = payment_intent + .get_optional_customer_id() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get optional customer id")?; + + let braintree_metadata = payment_intent + .get_optional_connector_metadata() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed parsing ConnectorMetadata")? + .and_then(|cm| cm.braintree); + + let merchant_account_id = braintree_metadata + .as_ref() + .and_then(|braintree| braintree.merchant_account_id.clone()); + + let merchant_config_currency = + braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); + + let router_data = types::RouterData { + flow: PhantomData, + merchant_id: merchant_account.get_id().clone(), + customer_id, + tenant_id: state.tenant.tenant_id.clone(), + connector: connector_enum.to_string(), + payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), + attempt_id: payment_attempt.id.get_string_repr().to_string().clone(), + status, + payment_method: payment_method_type, + connector_auth_type: auth_type, + description: None, + // Does refund need shipping/billing address ? + address: PaymentAddress::default(), + auth_type: payment_attempt.authentication_type, + connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), + amount_captured: payment_intent + .amount_captured + .map(|amt| amt.get_amount_as_i64()), + payment_method_status: None, + minor_amount_captured: payment_intent.amount_captured, + request: types::RefundsData { + refund_id: refund.id.get_string_repr().to_string(), + connector_transaction_id: refund.get_connector_transaction_id().clone(), + refund_amount: refund.refund_amount.get_amount_as_i64(), + minor_refund_amount: refund.refund_amount, + currency, + payment_amount: payment_amount.get_amount_as_i64(), + minor_payment_amount: payment_amount, + webhook_url, + connector_metadata: payment_attempt.connector_metadata.clone().expose_option(), + reason: refund.refund_reason.clone(), + connector_refund_id: connector_refund_id.clone(), + browser_info, + split_refunds: None, + integrity_object: None, + refund_status: refund.refund_status, + merchant_account_id, + merchant_config_currency, + refund_connector_metadata: refund.metadata.clone(), + capture_method: Some(capture_method), + }, + + response: Ok(types::RefundsResponseData { + connector_refund_id: connector_refund_id.unwrap_or_default(), + refund_status: refund.refund_status, + }), + access_token: None, + session_token: None, + reference_id: None, + payment_method_token: None, + connector_customer: None, + recurring_mandate_payment_data: None, + preprocessing_id: None, + connector_request_reference_id: refund.id.get_string_repr().to_string().clone(), + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + test_mode: None, + payment_method_balance: None, + connector_api_version, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + frm_metadata: None, + refund_id: Some(refund.id.get_string_repr().to_string().clone()), + dispute_id: None, + connector_response: None, + integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, + connector_mandate_request_reference_id: None, + authentication_id: None, + psd2_sca_exemption_type: None, + }; + + Ok(router_data) } #[cfg(feature = "v1")] @@ -309,7 +451,7 @@ pub async fn construct_refund_router_data<'a, F>( .conf .multiple_api_version_supported_connectors .supported_connectors; - let connector_enum = api_models::enums::Connector::from_str(connector_id) + let connector_enum = Connector::from_str(connector_id) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", @@ -485,7 +627,7 @@ pub fn validate_uuid(uuid: String, key: &str) -> Result<String, errors::ApiError #[cfg(feature = "v1")] pub fn get_split_refunds( - split_refund_input: super::refunds::transformers::SplitRefundInput, + split_refund_input: refunds_transformers::SplitRefundInput, ) -> RouterResult<Option<router_request_types::SplitRefundsRequest>> { match split_refund_input.split_payment_request.as_ref() { Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(stripe_payment)) => { @@ -515,7 +657,7 @@ pub fn get_split_refunds( }; if let Some(charge_id) = charge_id_option { - let options = super::refunds::validator::validate_stripe_charge_refund( + let options = refunds_validator::validate_stripe_charge_refund( charge_type_option, &split_refund_input.refund_request, )?; @@ -543,7 +685,7 @@ pub fn get_split_refunds( split_refund_request, )) = split_refund_input.refund_request.clone() { - super::refunds::validator::validate_adyen_charge_refund( + refunds_validator::validate_adyen_charge_refund( adyen_split_payment_response, &split_refund_request, )?; @@ -573,7 +715,7 @@ pub fn get_split_refunds( split_refund_request, )), ) => { - let user_id = super::refunds::validator::validate_xendit_charge_refund( + let user_id = refunds_validator::validate_xendit_charge_refund( xendit_split_payment_response, split_refund_request, )?; @@ -1472,7 +1614,7 @@ pub async fn validate_and_get_business_profile( } fn connector_needs_business_sub_label(connector_name: &str) -> bool { - let connectors_list = [api_models::enums::Connector::Cybersource]; + let connectors_list = [Connector::Cybersource]; connectors_list .map(|connector| connector.to_string()) .contains(&connector_name.to_string()) diff --git a/crates/router/src/core/refunds/transformers.rs b/crates/router/src/core/utils/refunds_transformers.rs similarity index 100% rename from crates/router/src/core/refunds/transformers.rs rename to crates/router/src/core/utils/refunds_transformers.rs diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/utils/refunds_validator.rs similarity index 90% rename from crates/router/src/core/refunds/validator.rs rename to crates/router/src/core/utils/refunds_validator.rs index 573543dfbf7..5f982388264 100644 --- a/crates/router/src/core/refunds/validator.rs +++ b/crates/router/src/core/utils/refunds_validator.rs @@ -110,6 +110,7 @@ pub fn validate_refund_list(limit: Option<i64>) -> CustomResult<i64, errors::Api } } +#[cfg(feature = "v1")] pub fn validate_for_valid_refunds( payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, connector: api_models::enums::Connector, @@ -146,6 +147,38 @@ pub fn validate_for_valid_refunds( } } +#[cfg(feature = "v2")] +pub fn validate_for_valid_refunds( + payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + connector: api_models::enums::Connector, +) -> RouterResult<()> { + let payment_method_type = payment_attempt.payment_method_type; + + match payment_method_type { + diesel_models::enums::PaymentMethod::PayLater + | diesel_models::enums::PaymentMethod::Wallet => { + let payment_method_subtype = payment_attempt.payment_method_subtype; + + utils::when( + matches!( + (connector, payment_method_subtype), + ( + api_models::enums::Connector::Braintree, + diesel_models::enums::PaymentMethodType::Paypal, + ) + ), + || { + Err(errors::ApiErrorResponse::RefundNotPossible { + connector: connector.to_string(), + } + .into()) + }, + ) + } + _ => Ok(()), + } +} + pub fn validate_stripe_charge_refund( charge_type_option: Option<api_enums::PaymentChargeType>, split_refund_request: &Option<common_types::refunds::SplitRefund>, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 866df70e69b..304428ca141 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1721,6 +1721,24 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(feature = "v2")] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + payment_id: &id_type::GlobalPaymentId, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { + self.diesel_store + .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + key_manager_state, + merchant_key_store, + payment_id, + storage_scheme, + ) + .await + } + #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, @@ -2759,7 +2777,6 @@ impl RefundInterface for KafkaStore { Ok(refund) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &id_type::MerchantId, diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 211f8ddbc48..fbbe0a6d159 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -57,7 +57,6 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -632,6 +631,24 @@ mod storage { } } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn find_refund_by_merchant_id_connector_transaction_id( + &self, + merchant_id: &common_utils::id_type::MerchantId, + connector_transaction_id: &str, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage_types::Refund::find_by_merchant_id_connector_transaction_id( + &conn, + merchant_id, + connector_transaction_id, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn update_refund( @@ -1092,7 +1109,6 @@ impl RefundInterface for MockDb { Ok(refund) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index dc7cb1233fa..2b499c882c8 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -154,7 +154,9 @@ pub fn mk_app( #[cfg(all(feature = "v2", feature = "oltp"))] { - server_app = server_app.service(routes::PaymentMethodSession::server(state.clone())); + server_app = server_app + .service(routes::PaymentMethodSession::server(state.clone())) + .service(routes::Refunds::server(state.clone())); } #[cfg(feature = "v1")] diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 34feb63ea78..03a5589f770 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -44,7 +44,6 @@ pub mod poll; pub mod profiles; #[cfg(feature = "recon")] pub mod recon; -#[cfg(feature = "v1")] pub mod refunds; #[cfg(feature = "olap")] pub mod routing; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d2d31790914..9dc67be1d2d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -48,6 +48,8 @@ use super::pm_auth; use super::poll; #[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))] use super::recovery_webhooks::*; +#[cfg(all(feature = "oltp", feature = "v2"))] +use super::refunds; #[cfg(feature = "olap")] use super::routing; #[cfg(all(feature = "olap", feature = "v1"))] @@ -1163,6 +1165,17 @@ impl Refunds { } } +#[cfg(all(feature = "v2", feature = "refunds_v2", feature = "oltp"))] +impl Refunds { + pub fn server(state: AppState) -> Scope { + let mut route = web::scope("/v2/refunds").app_data(web::Data::new(state)); + + route = route.service(web::resource("").route(web::post().to(refunds::refunds_create))); + + route + } +} + #[cfg(feature = "payouts")] pub struct Payouts; diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index aa2afa1c329..c4d157d7de4 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -1,16 +1,21 @@ use actix_web::{web, HttpRequest, HttpResponse}; +use common_utils; use router_env::{instrument, tracing, Flow}; use super::app::AppState; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +use crate::core::refunds::*; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use crate::core::refunds_v2::*; use crate::{ - core::{api_locking, refunds::*}, + core::api_locking, services::{api, authentication as auth, authorization::permissions::Permission}, types::api::refunds, }; - /// Refunds - Create /// /// To create a refund against an already processed payment +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[utoipa::path( post, path = "/refunds", @@ -59,6 +64,41 @@ pub async fn refunds_create( )) .await } + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))] +// #[post("")] +pub async fn refunds_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<refunds::RefundsCreateRequest>, +) -> HttpResponse { + let flow = Flow::RefundsCreate; + + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, req, _| { + refund_create_core(state, auth.merchant_account, auth.key_store, req) + }, + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::ProfileRefundWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] /// Refunds - Retrieve (GET) /// /// 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 @@ -125,6 +165,8 @@ pub async fn refunds_retrieve( )) .await } + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] /// Refunds - Retrieve (POST) /// /// 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 @@ -176,6 +218,8 @@ pub async fn refunds_retrieve_with_body( )) .await } + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] /// Refunds - Update /// /// To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields @@ -221,6 +265,12 @@ pub async fn refunds_update( )) .await } + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - List /// /// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided @@ -236,7 +286,6 @@ pub async fn refunds_update( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] -#[cfg(feature = "olap")] pub async fn refunds_list( state: web::Data<AppState>, req: HttpRequest, @@ -266,6 +315,11 @@ pub async fn refunds_list( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - List at profile level /// /// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided @@ -281,7 +335,6 @@ pub async fn refunds_list( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] -#[cfg(feature = "olap")] pub async fn refunds_list_profile( state: web::Data<AppState>, req: HttpRequest, @@ -316,6 +369,11 @@ pub async fn refunds_list_profile( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - Filter /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses @@ -331,7 +389,6 @@ pub async fn refunds_list_profile( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] -#[cfg(feature = "olap")] pub async fn refunds_filter_list( state: web::Data<AppState>, req: HttpRequest, @@ -361,6 +418,11 @@ pub async fn refunds_filter_list( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - Filter V2 /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses @@ -375,7 +437,6 @@ pub async fn refunds_filter_list( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))] -#[cfg(feature = "olap")] pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::RefundsFilters; Box::pin(api::server_wrap( @@ -401,6 +462,11 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) - .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - Filter V2 at profile level /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses @@ -415,7 +481,6 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) - security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))] -#[cfg(feature = "olap")] pub async fn get_refunds_filters_profile( state: web::Data<AppState>, req: HttpRequest, @@ -448,8 +513,12 @@ pub async fn get_refunds_filters_profile( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] #[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))] -#[cfg(feature = "olap")] pub async fn get_refunds_aggregates( state: web::Data<AppState>, req: HttpRequest, @@ -480,8 +549,12 @@ pub async fn get_refunds_aggregates( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] #[instrument(skip_all, fields(flow = ?Flow::RefundsManualUpdate))] -#[cfg(feature = "olap")] pub async fn refunds_manual_update( state: web::Data<AppState>, req: HttpRequest, @@ -503,8 +576,12 @@ pub async fn refunds_manual_update( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] #[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))] -#[cfg(feature = "olap")] pub async fn get_refunds_aggregate_profile( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index 7aafe4de152..ff1f192fd45 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -1,6 +1,9 @@ +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +pub use api_models::refunds::RefundRequest; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +pub use api_models::refunds::RefundsCreateRequest; pub use api_models::refunds::{ - RefundRequest, RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, - RefundsRetrieveRequest, + RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveRequest, }; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync}; diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 06f98bb26b0..baafc60f316 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -342,4 +342,26 @@ impl PaymentAttemptInterface for MockDb { .cloned() .unwrap()) } + + #[cfg(feature = "v2")] + #[allow(clippy::unwrap_used)] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + _key_manager_state: &KeyManagerState, + _merchant_key_store: &MerchantKeyStore, + payment_id: &id_type::GlobalPaymentId, + _storage_scheme: storage_enums::MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, StorageError> { + let payment_attempts = self.payment_attempts.lock().await; + + Ok(payment_attempts + .iter() + .find(|payment_attempt| { + payment_attempt.payment_id == *payment_id + && (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged + || payment_attempt.status == storage_enums::AttemptStatus::Charged) + }) + .cloned() + .unwrap()) + } } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 0156270484c..9720545821b 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -216,6 +216,33 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(feature = "v2")] + #[instrument(skip_all)] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_id: &common_utils::id_type::GlobalPaymentId, + _storage_scheme: MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, errors::StorageError> { + let conn = pg_connection_read(self).await?; + DieselPaymentAttempt::find_last_successful_or_partially_captured_attempt_by_payment_id( + &conn, payment_id, + ) + .await + .map_err(|er| { + let new_err = diesel_error_to_data_error(*er.current_context()); + er.change_context(new_err) + })? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } + #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( @@ -1050,6 +1077,26 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(feature = "v2")] + #[instrument(skip_all)] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_id: &common_utils::id_type::GlobalPaymentId, + storage_scheme: MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { + // Ignoring storage scheme for v2 implementation + self.router_store + .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + key_manager_state, + merchant_key_store, + payment_id, + storage_scheme, + ) + .await + } + #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self,
2025-03-25T09:37:59Z
## Description <!-- Describe your changes in detail --> This PR is a part of v2 implementation of refunds. This PR contains refunds create core flow, i.e we can be able to create refunds for payments in v2. **Important** We are moving `refunds/transformers.rs` and `refunds/validator.rs` to a separate location because of accessibility to both v1 and v2 refund code. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Merging this PR would add support for creating refunds for payments in v2 apis. #
2067bc352044f00f2c724b4a97f1de0cf599f337
- Create Payment Intent api call ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'api-key: xyz' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_' \ --header 'Authorization: api-key=xyz' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"automatic", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` - Response from the above call ```json { "id": "12345_pay_0195d13dd6497c12a3b187039fc4b71e", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "12345_pay_0195d13dd6497c12a3b187039fc4b71e_secret_0195d13dd6547a938bfe7b97b36203a5", "profile_id": "pro_TujgCYCsvWvO6YNsRAmC", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": null, "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-03-26T07:12:25.588Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` - Confirm Intent API call ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d13dd6497c12a3b187039fc4b71e/confirm-intent' \ --header 'x-client-secret: 12345_pay_0195d13dd6497c12a3b187039fc4b71e_secret_0195d13dd6547a938bfe7b97b36203a5' \ --header 'x-profile-id: pro_TujgCYCsvWvO6YNsRAmC' \ --header 'Content-Type: application/json' \ --header 'Authorization: publishable-key=pk_dev_58559cdf90434adcb0b92eeb6a8b633f,client-secret=12345_pay_0195d13dd6497c12a3b187039fc4b71e_secret_0195d13dd6547a938bfe7b97b36203a5' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "09", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" }' ``` - Response from the above call ```json { "id": "12345_pay_0195d13dd6497c12a3b187039fc4b71e", "status": "succeeded", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 100 }, "customer_id": null, "connector": "stripe", "client_secret": "12345_pay_0195d13dd6497c12a3b187039fc4b71e_secret_0195d13dd6547a938bfe7b97b36203a5", "created": "2025-03-26T06:57:25.588Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "pi_3R6ntzD5R7gDAGff0MYUxZFn", "connector_reference_id": null, "merchant_connector_id": "mca_FhEKUEAUdgv7mVCs3A9U", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1R6ntzD5R7gDAGff07DogD0c", "connector_token_request_reference_id": "oMf8ppmFul0oTqI6Zl" }, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` - Create refund for a successful payment ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_TujgCYCsvWvO6YNsRAmC' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_kksGlKY14xNypCzsrJIXFCzL3t2j5kUs7ChmloPryJsdRy2RWYljonzPCxJSDmuZ' \ --data '{ "payment_id":"12345_pay_0195d13dd6497c12a3b187039fc4b71e", "merchant_reference_id":"1742972385", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ```json { "id": "12345_ref_0195d13dfedb7790bc1a84be825e64d5", "payment_id": "12345_pay_0195d13dd6497c12a3b187039fc4b71e", "merchant_reference_id": "1742972256", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-03-26T06:57:35.993Z", "updated_at": "2025-03-26T06:57:36.981Z", "connector": "stripe", "profile_id": "pro_TujgCYCsvWvO6YNsRAmC", "merchant_connector_id": "mca_FhEKUEAUdgv7mVCs3A9U", "connector_refund_reference_id": "12345_ref_0195d13dfedb7790bc1a84be825e64d5" } ``` - Trying the same refund again will give us this response ```json {"error":{"type":"invalid_request","message":"The refund amount exceeds the amount captured","code":"IR_13"}} ``` - What if the payment was failed and we try to refund it. (Invalid card number in confirm intent call) ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d142100474c3bcb32e40935e290d/confirm-intent' \ --header 'x-client-secret: 12345_pay_0195d142100474c3bcb32e40935e290d_secret_0195d14210127d30b524ec0e063b3c0a' \ --header 'x-profile-id: pro_TujgCYCsvWvO6YNsRAmC' \ --header 'Content-Type: application/json' \ --header 'Authorization: publishable-key=pk_dev_58559cdf90434adcb0b92eeb6a8b633f,client-secret=12345_pay_0195d142100474c3bcb32e40935e290d_secret_0195d14210127d30b524ec0e063b3c0a' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" }' ``` - Response from the above call ```json { "id": "12345_pay_0195d142100474c3bcb32e40935e290d", "status": "failed", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "stripe", "client_secret": "12345_pay_0195d142100474c3bcb32e40935e290d_secret_0195d14210127d30b524ec0e063b3c0a", "created": "2025-03-26T07:02:02.514Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": null, "connector_reference_id": null, "merchant_connector_id": "mca_FhEKUEAUdgv7mVCs3A9U", "browser_info": null, "error": { "code": "invalid_expiry_month", "message": "invalid_expiry_month", "unified_code": null, "unified_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` - Trying to refund failed payment ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_TujgCYCsvWvO6YNsRAmC' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_kksGlKY14xNypCzsrJIXFCzL3t2j5kUs7ChmloPryJsdRy2RWYljonzPCxJSDmuZ' \ --data '{ "payment_id":"12345_pay_0195d142100474c3bcb32e40935e290d", "merchant_reference_id":"1742972638", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ```json { "error": { "type": "invalid_request", "message": "This Payment could not be refund because it has a status of failed. The expected state is succeeded, partially_captured", "code": "IR_14" } } ``` Error case responses - Connector NotImplemented Error (501) ``` { "error": { "type": "invalid_request", "message": "get_url method is not implemented", "code": "IR_00" } } ``` - Connector NotSupported Error (400) ``` { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "Refund is not supported by Stripe" } } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/Cargo.toml", "crates/api_models/src/events/refund.rs", "crates/api_models/src/refunds.rs", "crates/common_utils/src/types.rs", "crates/diesel_models/src/query/payment_attempt.rs", "crates/diesel_models/src/query/refund.rs", "crates/diesel_models/src/refund.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs", "crates/openapi/Cargo.toml", "crates/openapi/src/openapi_v2.rs", "crates/router/Cargo.toml", "crates/router/src/core.rs", "crates/router/src/core/refunds.rs", "crates/router/src/core/refunds_v2.rs", "crates/router/src/core/utils.rs", "crates/router/src/core/refunds/transformers.rs", "crates/router/src/core/refunds/validator.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/db/refund.rs", "crates/router/src/lib.rs", "crates/router/src/routes.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/refunds.rs", "crates/router/src/types/api/refunds.rs", "crates/storage_impl/src/mock_db/payment_attempt.rs", "crates/storage_impl/src/payments/payment_attempt.rs", "crates/router/src/core/utils/refunds_validator.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7608
Bug: [FEATURE] [BRAINTREE] Pass connector request reference id ### Feature Description Pass connector request reference id in payment requests to braintree ### Possible Implementation Pass connector request reference id in orderId field in payment requests. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs index 80a62072db2..7f008b24f1a 100644 --- a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs @@ -218,6 +218,7 @@ pub struct RegularTransactionBody { channel: String, #[serde(skip_serializing_if = "Option::is_none")] customer_details: Option<CustomerBody>, + order_id: String, } #[derive(Debug, Serialize)] @@ -228,6 +229,7 @@ pub struct VaultTransactionBody { vault_payment_method_after_transacting: TransactionTiming, #[serde(skip_serializing_if = "Option::is_none")] customer_details: Option<CustomerBody>, + order_id: String, } #[derive(Debug, Serialize)] @@ -268,6 +270,7 @@ impl merchant_account_id: metadata.merchant_account_id, channel: CHANNEL_CODE.to_string(), customer_details: None, + order_id: item.router_data.connector_request_reference_id.clone(), }), ); Ok(Self { @@ -875,6 +878,8 @@ pub struct DataResponse { pub struct RefundInputData { amount: StringMajorUnit, merchant_account_id: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + order_id: Option<String>, } #[derive(Serialize, Debug, Clone)] struct IdFilter { @@ -928,6 +933,7 @@ impl<F> TryFrom<BraintreeRouterData<&RefundsRouterData<F>>> for BraintreeRefundR refund: RefundInputData { amount: item.amount, merchant_account_id: metadata.merchant_account_id, + order_id: item.router_data.refund_id.clone(), }, }, }; @@ -1761,6 +1767,7 @@ impl .get_billing_email() .ok() .map(|email| CustomerBody { email }), + order_id: item.router_data.connector_request_reference_id.clone(), }), ) } else { @@ -1778,6 +1785,7 @@ impl .get_billing_email() .ok() .map(|email| CustomerBody { email }), + order_id: item.router_data.connector_request_reference_id.clone(), }), ) }; @@ -1870,6 +1878,7 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> .get_billing_email() .ok() .map(|email| CustomerBody { email }), + order_id: item.router_data.connector_request_reference_id.clone(), }), ) } else { @@ -1887,6 +1896,7 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> .get_billing_email() .ok() .map(|email| CustomerBody { email }), + order_id: item.router_data.connector_request_reference_id.clone(), }), ) };
2025-03-24T12:43:17Z
## Description <!-- Describe your changes in detail --> Pass connector request reference id in payment requests to braintree ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/7608 #
2b70c945406b1cf80831452b75e0c488eb60c86c
Order ID on braintree dashboard should contain Hyperswitch connector request reference ID for all the transactions: <img width="1618" alt="image" src="https://github.com/user-attachments/assets/63dbd338-ce24-4e45-91bf-99905de22775" /> Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_q0iUEbBtK5AYpgqOXSEq5bha8S9xpSZeZ7HeRzRDZSIVLREPxMnRGOBxEB6mcbjU' \ --data-raw '{ "amount": 100, "currency": "EUR", "confirm": true, "customer_id": "deepanshu", "email": "[email protected]", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5200000000001096", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Deepanshu Bansal", "card_cvc": "123" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline" }, "billing": { "email": "[email protected]" } }' ``` Response: ``` { "payment_id": "pay_qj6nnKBVA02m4m16Bf0p", "merchant_id": "postman_merchant_GHAction_8dc59add-138a-4366-b2f4-e7fd9a76682e", "status": "requires_customer_action", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 100, "amount_received": null, "connector": "braintree", "client_secret": "pay_qj6nnKBVA02m4m16Bf0p_secret_vp3Dm540FBjEy5oODEu0", "created": "2025-03-24T12:18:19.821Z", "currency": "EUR", "customer_id": "deepanshu", "customer": { "id": "deepanshu", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Deepanshu Bansal", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": null, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_qj6nnKBVA02m4m16Bf0p/postman_merchant_GHAction_8dc59add-138a-4366-b2f4-e7fd9a76682e/pay_qj6nnKBVA02m4m16Bf0p_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "deepanshu", "created_at": 1742818699, "expires": 1742822299, "secret": "epk_ece8705d8e4d40f59864e32e6e61727a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_7Mi4xtmmjuOFZgzb4rqz", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_fQJW054s61taxmNcIf7d", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-24T12:33:19.820Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_0j6JND9oAujfW12x9utN", "payment_method_status": "inactive", "updated": "2025-03-24T12:18:23.369Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } ``` Refunds Request: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_q0iUEbBtK5AYpgqOXSEq5bha8S9xpSZeZ7HeRzRDZSIVLREPxMnRGOBxEB6mcbjU' \ --data '{ "payment_id": "pay_0SDwU6UegcLz7XeOQdPR", "amount": 123, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Refunds Response: ``` { "refund_id": "ref_cqDKR27PsjuksAuU1feK", "payment_id": "pay_0SDwU6UegcLz7XeOQdPR", "amount": 123, "currency": "EUR", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-03-24T12:58:51.627Z", "updated_at": "2025-03-24T12:58:53.214Z", "connector": "braintree", "profile_id": "pro_7Mi4xtmmjuOFZgzb4rqz", "merchant_connector_id": "mca_fQJW054s61taxmNcIf7d", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` <img width="1618" alt="image" src="https://github.com/user-attachments/assets/1243347a-14d1-44bb-8f17-2d045affa523" />
[ "crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7607
Bug: [BUG] 5xx in PayPal when cancelling the Payment we're getting 5xx when you try to cancel the payment express checkout page. and this is not intended.
diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs index 223be54d3fd..45749332081 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs @@ -187,6 +187,9 @@ pub struct Notifications { /// The merchant URL that will receive the notification when the 3DS ACS successfully gathers /// de ice informatiSon and tonotification_configurations.cordingly. pub three_ds_method_return_url: Option<String>, + /// The URL on merchant's website to which the customer should be redirected in the event of + /// the customer canceling the transaction. + pub cancel_url: Option<String>, } #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs index a5f905d0e70..a36cdc2a53a 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs @@ -69,7 +69,7 @@ pub struct Action { pub time_created: Option<String>, /// Indicates the action taken. #[serde(rename = "type")] - pub action_type: Option<String>, + pub action_type: Option<ActionType>, } #[derive(Debug, Deserialize, Serialize)] @@ -266,6 +266,35 @@ pub struct ProviderClass { pub enum ResultCode { Declined, Success, + Pending, + Error, +} + +/// Indicates the specific action taken. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ActionType { + Adjust, + Authorize, + Capture, + Confirm, + Force, + Increment, + Initiate, + MultipleCapture, + Preauthorize, + PreauthorizeMultipleCapturere, + Authorization, + RedirectFrom, + RedirectTo, + Refund, + Hold, + Release, + Reverse, + Split, + StatusNotification, + TransactionList, + TransactionSingle, } /// A string generated by the payment method that represents to what degree the merchant is @@ -335,19 +364,6 @@ pub enum Brand { Visa, } -/// If enabled, this field indicates whether the payment method has been seen before or is -/// new. -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum FingerprintPresenceIndicator { - /// Indicates that the payment method was seen on the platform before by this - /// merchant. - Exists, - /// Indicates that the payment method was not seen on the platform before by this - /// merchant. - New, -} - /// Indicates where a transaction is in its lifecycle. #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] @@ -389,13 +405,6 @@ pub struct GlobalpayWebhookObjectEventType { pub status: GlobalpayWebhookStatus, } -#[derive(Debug, Deserialize, Serialize)] -pub struct GlobalpayPaymentsWebhookResponse { - pub id: String, - pub account_id: Option<String>, - pub account_name: Option<String>, -} - #[derive(Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GlobalpayWebhookStatus { @@ -404,8 +413,3 @@ pub enum GlobalpayWebhookStatus { #[serde(other)] Unknown, } - -#[derive(Debug, Serialize, Deserialize)] -pub struct GlobalpayRedirectResponse { - pub status: Option<GlobalpayPaymentStatus>, -} diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs index 24cfa66ef39..124b611d049 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs @@ -116,6 +116,7 @@ impl TryFrom<&GlobalPayRouterData<&PaymentsAuthorizeRouterData>> for GlobalpayPa decoupled_challenge_return_url: None, status_url: item.router_data.request.webhook_url.clone(), three_ds_method_return_url: None, + cancel_url: get_return_url(item.router_data), }), authorization_mode: None, cashback_amount: None, @@ -477,7 +478,14 @@ fn get_return_url(item: &PaymentsAuthorizeRouterData) -> Option<String> { match item.request.payment_method_data.clone() { payment_method_data::PaymentMethodData::Wallet( payment_method_data::WalletData::PaypalRedirect(_), - ) => item.request.complete_authorize_url.clone(), + ) => { + // Return URL handling for PayPal via Globalpay: + // - PayPal inconsistency: Return URLs work with HTTP, but cancel URLs require HTTPS + // - Local development: When testing locally, expose your server via HTTPS and replace + // the base URL with an HTTPS URL to ensure proper cancellation flow + // - Refer to commit 6499d429da87 for more information + item.request.complete_authorize_url.clone() + } _ => item.request.router_return_url.clone(), } } diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs index 23a0daa45b4..a1fc1bdd828 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs @@ -309,7 +309,7 @@ impl TryFrom<enums::AttemptStatus> for RecurlyRecordStatus { #[derive(Debug, Deserialize, Serialize, Clone)] pub struct RecurlyRecordbackResponse { - // inovice id + // invoice id pub id: id_type::PaymentReferenceId, }
2025-03-24T12:08:42Z
## Description <!-- Describe your changes in detail --> This PR addresses 5xx that currently is being thrown when a user tries to cancel the PayPal transactions from the redirected page: <img width="372" alt="image" src="https://github.com/user-attachments/assets/4f920b8b-6ab4-4bcb-9705-dc4d15635c2d" /> This is addressed by introducing a new field `cancel_url` that is required for PayPal. This PR also removes unused structs and enums. In addition to that, `ActionType` has been replaced the previous `String` and now that it only accepts limited number of values. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> We're getting a 5xx when trying to cancel the payment. Closes [#7607](https://github.com/juspay/hyperswitch/issues/7607) #
2b70c945406b1cf80831452b75e0c488eb60c86c
▶ Expose the `localhost` to the internet via `tailscale funnel` <details> <summary>Make a Paypal transaction</summary> Create Payment: ```curl curl --location 'https://pix-mbp.orthrus-monster.ts.net/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_DYcmLTXXQ6gF1HulHKL1WMBpoP8Uw2v1M4eO9mqp9za9AHCpJfhloE568dArpo5Y' \ --data-raw '{ "amount": 1000, "currency": "USD", "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": "US" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_nL4QMyfyB3Q6T0Cs2OEf", "merchant_id": "postman_merchant_GHAction_164c761e-166f-4a82-859f-609d96a725b0", "status": "requires_payment_method", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_nL4QMyfyB3Q6T0Cs2OEf_secret_No5MIK8z5xGpdgyfb5gH", "created": "2025-03-24T11:25:08.436Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1742815508, "expires": 1742819108, "secret": "epk_bc69bc123b7446839d02b177bc3273f7" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_bf5d6NP8wcNd1vnsH0eE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-24T11:40:08.436Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-24T11:25:08.461Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "issuer_error_code": null, "issuer_error_message": null } ``` Confirm payment: ```curl curl --location 'https://pix-mbp.orthrus-monster.ts.net/payments/pay_5Vm2zTuuBxSsYrddguto/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_DYcmLTXXQ6gF1HulHKL1WMBpoP8Uw2v1M4eO9mqp9za9AHCpJfhloE568dArpo5Y' \ --data '{ "payment_method": "wallet", "payment_method_type": "paypal", "return_url": "https://nohello.com", "payment_method_data": { "wallet": { "paypal_redirect": { } } } } ' ``` ```json { "payment_id": "pay_nL4QMyfyB3Q6T0Cs2OEf", "merchant_id": "postman_merchant_GHAction_164c761e-166f-4a82-859f-609d96a725b0", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "globalpay", "client_secret": "pay_nL4QMyfyB3Q6T0Cs2OEf_secret_No5MIK8z5xGpdgyfb5gH", "created": "2025-03-24T11:25:08.436Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://nohello.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_nL4QMyfyB3Q6T0Cs2OEf/postman_merchant_GHAction_164c761e-166f-4a82-859f-609d96a725b0/pay_nL4QMyfyB3Q6T0Cs2OEf_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "TRN_PRy15uCj0zyEXanseeWWt78nr53Zh4_Q6T0Cs2OEf_1", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_nL4QMyfyB3Q6T0Cs2OEf_1", "payment_link": null, "profile_id": "pro_bf5d6NP8wcNd1vnsH0eE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_vURZVfOwYJUGEdIvkfny", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-24T11:40:08.436Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "103.159.11.202", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-24T11:25:12.890Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>Click on `Cancel and return to Global Pay Merchant's Test Store` in PayPal **Express Checkout** page</summary> <img width="561" alt="image" src="https://github.com/user-attachments/assets/b13b7e05-31c1-4037-a9b7-a7fd8c2d017f" /> </details> <details> <summary>You should be redirected to the `return_url` with payment status as `failed`</summary> <img width="652" alt="image" src="https://github.com/user-attachments/assets/18aab179-ccce-4ce4-ab83-3a13e970999f" /> </details> <details> <summary>Retrieve the Payment to see the updated status</summary> ```curl curl --location 'https://pix-mbp.orthrus-monster.ts.net/payments/pay_5Vm2zTuuBxSsYrddguto?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_DYcmLTXXQ6gF1HulHKL1WMBpoP8Uw2v1M4eO9mqp9za9AHCpJfhloE568dArpo5Y' ``` ```json { "payment_id": "pay_nL4QMyfyB3Q6T0Cs2OEf", "merchant_id": "postman_merchant_GHAction_164c761e-166f-4a82-859f-609d96a725b0", "status": "failed", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "globalpay", "client_secret": "pay_nL4QMyfyB3Q6T0Cs2OEf_secret_No5MIK8z5xGpdgyfb5gH", "created": "2025-03-24T11:25:08.436Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://nohello.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "INVALID_REQUEST_DATA", "error_message": "The supplied Payer Id doesn't match the value saved in the database", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "TRN_PRy15uCj0zyEXanseeWWt78nr53Zh4_Q6T0Cs2OEf_1", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_nL4QMyfyB3Q6T0Cs2OEf_1", "payment_link": null, "profile_id": "pro_bf5d6NP8wcNd1vnsH0eE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_vURZVfOwYJUGEdIvkfny", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-24T11:40:08.436Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "103.159.11.202", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-24T11:25:23.530Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "issuer_error_code": null, "issuer_error_message": null } ``` </details>
[ "crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs", "crates/hyperswitch_connectors/src/connectors/globalpay/response.rs", "crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7587
Bug: [CHORE] Update GlobalPay production endpoint at present, production endpoint points to sandbox and we need to point to production url
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 0ae089c5ea0..0d10ad5cbd9 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -8365,10 +8365,12 @@ "CAD", "CDF", "CHF", + "CLF", "CLP", "CNY", "COP", "CRC", + "CUC", "CUP", "CVE", "CZK", @@ -8464,6 +8466,7 @@ "SOS", "SRD", "SSP", + "STD", "STN", "SVC", "SYP", @@ -9969,6 +9972,12 @@ } } }, + { + "type": "string", + "enum": [ + "user_social_security_number" + ] + }, { "type": "string", "enum": [ diff --git a/config/deployments/production.toml b/config/deployments/production.toml index e193253e5ac..aaaa1b1216f 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -64,7 +64,7 @@ fiuu.secondary_base_url="https://api.merchant.razer.com/" fiuu.third_base_url="https://api.merchant.razer.com/" forte.base_url = "https://sandbox.forte.net/api/v3" getnet.base_url = "https://api.getneteurope.com/engine/rest" -globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" +globalpay.base_url = "https://apis.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api.gocardless.com" gpayments.base_url = "https://{{merchant_endpoint_prefix}}-test.api.as1.gpayments.net" diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay.rs b/crates/hyperswitch_connectors/src/connectors/globalpay.rs index 641e9fd5f3d..8034f9ac9db 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay.rs @@ -482,8 +482,10 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Gl .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -561,7 +563,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Glo ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response - .parse_struct("globalpay PaymentsResponse") + .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); @@ -581,6 +583,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Glo )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } + fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { @@ -658,8 +661,10 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -748,8 +753,10 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -909,8 +916,10 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Globalpay .response .parse_struct("globalpay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(),
2025-03-21T07:47:05Z
## Description <!-- Describe your changes in detail --> This PR updates the production endpoint url environment value for GlobalPay while fixing minor inconsistencies ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> At present, the production endpoint URL points to sandbox endpoint URL which is not intended. Closes #7587 #
0efeaa890f7dbcfa9440229d66d1a4f6b0f8b664
NA.
[ "api-reference-v2/openapi_spec.json", "config/deployments/production.toml", "crates/hyperswitch_connectors/src/connectors/globalpay.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7567
Bug: feat(router): Make `payment_method_subtype` optional We can have situations where we don't know the `payment_method_subtype`. e.g. Frontend doesn't know whether a `card` is `credit` or `debit`. To support such scenarios we need to make `payment_method_subtype` nullable
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index a2440cfccd3..c5ce0eec7d5 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -14738,7 +14738,6 @@ "type": "object", "required": [ "payment_method_type", - "payment_method_subtype", "customer_id", "payment_method_data" ], @@ -14747,7 +14746,12 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "$ref": "#/components/schemas/PaymentMethodType" + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true }, "metadata": { "type": "object", @@ -16199,8 +16203,7 @@ "description": "Request for Payment Intent Confirm", "required": [ "payment_method_data", - "payment_method_type", - "payment_method_subtype" + "payment_method_type" ], "properties": { "return_url": { @@ -16216,7 +16219,12 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "$ref": "#/components/schemas/PaymentMethodType" + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true }, "shipping": { "allOf": [ @@ -16994,8 +17002,7 @@ "amount_details", "customer_id", "payment_method_data", - "payment_method_type", - "payment_method_subtype" + "payment_method_type" ], "properties": { "amount_details": { @@ -17187,7 +17194,12 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "$ref": "#/components/schemas/PaymentMethodType" + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true }, "customer_acceptance": { "allOf": [ diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index d665337fda0..56bffc02640 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -116,8 +116,8 @@ pub struct PaymentMethodCreate { pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. - #[schema(value_type = PaymentMethodType,example = "credit")] - pub payment_method_subtype: api_enums::PaymentMethodType, + #[schema(value_type = Option<PaymentMethodType>,example = "credit")] + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// 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. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] @@ -2790,7 +2790,7 @@ pub struct PaymentMethodSessionConfirmRequest { /// The payment method subtype #[schema(value_type = PaymentMethodType, example = "credit")] - pub payment_method_subtype: common_enums::PaymentMethodType, + pub payment_method_subtype: Option<common_enums::PaymentMethodType>, /// The payment instrument data to be used for the payment #[schema(value_type = PaymentMethodDataRequest)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b7d344317c7..87c765ce8fc 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5232,8 +5232,8 @@ pub struct PaymentsConfirmIntentRequest { pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided - #[schema(value_type = PaymentMethodType, example = "apple_pay")] - pub payment_method_subtype: api_enums::PaymentMethodType, + #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, @@ -5401,8 +5401,8 @@ pub struct PaymentsRequest { pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided - #[schema(value_type = PaymentMethodType, example = "apple_pay")] - pub payment_method_subtype: api_enums::PaymentMethodType, + #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] @@ -8477,7 +8477,7 @@ pub struct PaymentRevenueRecoveryMetadata { pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] - pub payment_method_subtype: common_enums::PaymentMethodType, + pub payment_method_subtype: Option<common_enums::PaymentMethodType>, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, @@ -8558,7 +8558,7 @@ pub struct PaymentsAttemptRecordRequest { /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] - pub payment_method_subtype: api_enums::PaymentMethodType, + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 8fb4afeb8ed..672745bc39b 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -91,7 +91,7 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, - pub payment_method_subtype: storage_enums::PaymentMethodType, + pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub routing_result: Option<serde_json::Value>, pub authentication_applied: Option<common_enums::AuthenticationType>, pub external_reference_id: Option<String>, @@ -314,7 +314,7 @@ pub struct PaymentAttemptNew { pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, - pub payment_method_subtype: storage_enums::PaymentMethodType, + pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: id_type::GlobalAttemptId, pub connector_token_details: Option<ConnectorTokenDetails>, pub card_discovery: Option<storage_enums::CardDiscovery>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 5d028ad5214..30be42300c6 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -874,7 +874,7 @@ diesel::table! { #[max_length = 128] connector_payment_id -> Nullable<Varchar>, #[max_length = 64] - payment_method_subtype -> Varchar, + payment_method_subtype -> Nullable<Varchar>, routing_result -> Nullable<Jsonb>, authentication_applied -> Nullable<AuthenticationType>, #[max_length = 128] diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index eb2818ba244..69916de49a0 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -61,7 +61,7 @@ impl FeatureMetadata { pub fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> { self.payment_revenue_recovery_metadata .as_ref() - .map(|rrm| rrm.payment_method_subtype) + .and_then(|val| val.payment_method_subtype) } pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> { @@ -158,7 +158,7 @@ pub struct PaymentRevenueRecoveryMetadata { ///Payment Method Type pub payment_method_type: common_enums::enums::PaymentMethod, /// PaymentMethod Subtype - pub payment_method_subtype: common_enums::enums::PaymentMethodType, + pub payment_method_subtype: Option<common_enums::enums::PaymentMethodType>, /// The name of the payment connector through which the payment attempt was made. pub connector: common_enums::connector_enums::Connector, } diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index e6e8e1b123f..557d2455279 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -447,8 +447,9 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD let payment_method_details: ChargebeePaymentMethodDetails = serde_json::from_str(&item.content.transaction.payment_method_details) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - let payment_method_sub_type = - enums::PaymentMethodType::from(payment_method_details.card.funding_type); + let payment_method_sub_type = Some(enums::PaymentMethodType::from( + payment_method_details.card.funding_type, + )); Ok(Self { amount, currency, diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 9921cee8a63..d0a74406d50 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -226,7 +226,7 @@ impl AmountDetails { let order_tax_amount = match self.skip_external_tax_calculation { common_enums::TaxCalculationOverride::Skip => { self.tax_details.as_ref().and_then(|tax_details| { - tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype)) + tax_details.get_tax_amount(confirm_intent_request.payment_method_subtype) }) } common_enums::TaxCalculationOverride::Calculate => None, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 2dc4eec15f1..e6583db20e1 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -425,7 +425,7 @@ pub struct PaymentAttempt { /// The reference to the payment at the connector side pub connector_payment_id: Option<String>, /// The payment method subtype for the payment attempt. - pub payment_method_subtype: storage_enums::PaymentMethodType, + pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, /// The authentication type that was applied for the payment attempt. pub authentication_applied: Option<common_enums::AuthenticationType>, /// A reference to the payment at connector side. This is returned by the connector @@ -465,7 +465,7 @@ impl PaymentAttempt { #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { // TODO: check if we can fix this - Some(self.payment_method_subtype) + self.payment_method_subtype } #[cfg(feature = "v1")] @@ -649,8 +649,7 @@ impl PaymentAttempt { .unwrap_or(common_enums::PaymentMethod::Card), payment_method_id: None, connector_payment_id: None, - payment_method_subtype: payment_method_subtype_data - .unwrap_or(common_enums::PaymentMethodType::Credit), + payment_method_subtype: payment_method_subtype_data, authentication_applied: None, external_reference_id: None, payment_method_billing_address, diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 3e1bc93d91c..4bf1fece028 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -31,7 +31,7 @@ pub struct RevenueRecoveryAttemptData { /// payment method of payment attempt. pub payment_method_type: common_enums::PaymentMethod, /// payment method sub type of the payment attempt. - pub payment_method_sub_type: common_enums::PaymentMethodType, + pub payment_method_sub_type: Option<common_enums::PaymentMethodType>, } /// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index eec47ca6255..27fb3959bfe 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -707,7 +707,7 @@ pub async fn retrieve_payment_method_with_token( pub(crate) fn get_payment_method_create_request( payment_method_data: &api_models::payments::PaymentMethodData, payment_method_type: storage_enums::PaymentMethod, - payment_method_subtype: storage_enums::PaymentMethodType, + payment_method_subtype: Option<storage_enums::PaymentMethodType>, customer_id: id_type::GlobalCustomerId, billing_address: Option<&api_models::payments::Address>, payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>, @@ -971,7 +971,7 @@ pub async fn create_payment_method_core( None, network_tokenization_resp, Some(req.payment_method_type), - Some(req.payment_method_subtype), + req.payment_method_subtype, ) .await .attach_printable("Unable to create Payment method data")?; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index ceac9eaf43a..e566b69534c 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -228,7 +228,7 @@ pub fn make_dsl_input( }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type), - payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype), + payment_method_type: payments_dsl_input.payment_attempt.payment_method_subtype, card_network: payments_dsl_input .payment_method_data .as_ref() diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5186bb32206..2da3e91caed 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -285,7 +285,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( session_token: None, enrolled_for_3ds: true, related_transaction_id: None, - payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), + payment_method_type: payment_data.payment_attempt.payment_method_subtype, router_return_url: Some(router_return_url), webhook_url, complete_authorize_url, @@ -607,7 +607,7 @@ pub async fn construct_router_data_for_psync<'a>( capture_method: Some(payment_intent.capture_method), connector_meta: attempt.connector_metadata.clone().expose_option(), sync_type: types::SyncRequestType::SinglePaymentSync, - payment_method_type: Some(attempt.payment_method_subtype), + payment_method_type: attempt.payment_method_subtype, currency: payment_intent.amount_details.currency, // TODO: Get the charges object from feature metadata split_payments: None, @@ -948,7 +948,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( email, customer_name: None, return_url: Some(router_return_url), - payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), + payment_method_type: payment_data.payment_attempt.payment_method_subtype, request_incremental_authorization: matches!( payment_data .payment_intent @@ -1666,7 +1666,7 @@ where created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), - payment_method_subtype: Some(payment_attempt.payment_method_subtype), + payment_method_subtype: payment_attempt.payment_method_subtype, next_action, connector_transaction_id: payment_attempt.connector_payment_id.clone(), connector_reference_id: None, @@ -1770,7 +1770,7 @@ where payment_method_subtype: self .payment_attempt .as_ref() - .map(|attempt| attempt.payment_method_subtype), + .and_then(|attempt| attempt.payment_method_subtype), connector_transaction_id: self .payment_attempt .as_ref() @@ -2897,7 +2897,7 @@ impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> )), created: pi.created_at, payment_method_type: pa.as_ref().and_then(|p| p.payment_method_type.into()), - payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype.into()), + payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype), connector: pa.as_ref().and_then(|p| p.connector.clone()), merchant_connector_id: pa.as_ref().and_then(|p| p.merchant_connector_id.clone()), customer: None, diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 9c5030a30a0..4c925b9d467 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -69,10 +69,15 @@ impl PaymentMethodCreateExt for PaymentMethodCreate { impl PaymentMethodCreateExt for PaymentMethodCreate { fn validate(&self) -> RouterResult<()> { utils::when( - !validate_payment_method_type_against_payment_method( - self.payment_method_type, - self.payment_method_subtype, - ), + !self + .payment_method_subtype + .map(|sub| { + validate_payment_method_type_against_payment_method( + self.payment_method_type, + sub, + ) + }) + .unwrap_or(true), // If payment_method_subtype is None, we assume it to be valid || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_type' provided".to_string() diff --git a/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/down.sql b/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/down.sql new file mode 100644 index 00000000000..d8983958168 --- /dev/null +++ b/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/down.sql @@ -0,0 +1 @@ +ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype SET NOT NULL; diff --git a/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/up.sql b/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/up.sql new file mode 100644 index 00000000000..8f878c4e39f --- /dev/null +++ b/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype DROP NOT NULL; \ No newline at end of file
2025-03-19T09:58:14Z
## Description <!-- Describe your changes in detail --> - Added diesel migration to make `payment_method_subtype` Nullable in `payment_attempt` table - Made `payment_method_subtype` an `Option` in request and response structs ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #7567 #
a1ecce8f256081da1127f0ca4ed06356856c0e8b
1. Payments - Confirm: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195adf1544079139067663acdbff178/confirm-intent' \ --header 'x-client-secret: 12345_pay_0195adf1544079139067663acdbff178_secret_0195adf154487933ae61c8ca769286b0' \ --header 'x-profile-id: pro_6XA4kopfg4VAYLy2jNzW' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_196e797040ba4ecbb064ee14e53c8817' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card" }' ``` Response: ```json { "id": "12345_pay_0195adf1544079139067663acdbff178", "status": "requires_capture", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 100, "amount_captured": 0 }, "customer_id": null, "connector": "stripe", "client_secret": "12345_pay_0195adf1544079139067663acdbff178_secret_0195adf154487933ae61c8ca769286b0", "created": "2025-03-19T10:27:09.001Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": null, "connector_transaction_id": "pi_3R4Jq8D5R7gDAGff1B5K8RjQ", "connector_reference_id": null, "merchant_connector_id": "mca_vwmIHkB372B5SHcDO0wC", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1R4Jq8D5R7gDAGffQmkzcinv", "connector_token_request_reference_id": "q0miVgxYfHkoOfwax6" }, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payment_methods.rs", "crates/api_models/src/payments.rs", "crates/diesel_models/src/payment_attempt.rs", "crates/diesel_models/src/schema_v2.rs", "crates/diesel_models/src/types.rs", "crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs", "crates/hyperswitch_domain_models/src/revenue_recovery.rs", "crates/router/src/core/payment_methods.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/types/api/payment_methods.rs", "v2_migrations/2025-03-19-080705_payment-method-subtype-optional/down.sql", "v2_migrations/2025-03-19-080705_payment-method-subtype-optional/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7565
Bug: [BUG] AuthorizeDotNet Deserialization Failed in RSync Response in Production ### Bug Description AuthorizeDotNet has started sending status `voided` in RSync Response which is not mapped in Hyperswitch. ### Expected Behavior `voided` status should be mapped to `Failure`. ### Actual Behavior Deserialization failed. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: MacOS 2. Rust version (output of `rustc --version`): `rustc 1.83.0 (90b35a623 2024-11-26)` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index 2d329ec82fd..deefa7a1595 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -1562,6 +1562,7 @@ pub enum RSyncStatus { RefundPendingSettlement, Declined, GeneralError, + Voided, } #[derive(Debug, Deserialize, Serialize)] @@ -1615,7 +1616,9 @@ impl From<RSyncStatus> for enums::RefundStatus { match transaction_status { RSyncStatus::RefundSettledSuccessfully => Self::Success, RSyncStatus::RefundPendingSettlement => Self::Pending, - RSyncStatus::Declined | RSyncStatus::GeneralError => Self::Failure, + RSyncStatus::Declined | RSyncStatus::GeneralError | RSyncStatus::Voided => { + Self::Failure + } } } }
2025-03-19T08:34:21Z
## Description <!-- Describe your changes in detail --> Mapped status `voided` coming from AuthorizeDotNet to `Failure` in Hyperswitch. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> AuthorizeDotNet has started sending status voided in RSync Response which is not mapped in Hyperswitch. As a result, deserialization failed. #
10371af561ecc7536bb1db191af90a3cac2ab515
Can't be tested as AuthorizeDotNet takes 5-6 business days to send any other status than `RefundPendingSettlement`.
[ "crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7560
Bug: Revert "refactor(core): filter default routing config response based on connector type" This will revert pr https://github.com/juspay/hyperswitch/pull/7199
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 6c138488248..1a595cc7339 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -1,6 +1,6 @@ pub mod helpers; pub mod transformers; -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::DynamicRoutingAlgoAccessor; @@ -11,7 +11,6 @@ use api_models::{ use async_trait::async_trait; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::AsyncExt; -use common_utils::id_type::MerchantConnectorAccountId; use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] @@ -19,9 +18,7 @@ use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, success_rate_client::SuccessBasedDynamicRouting, }; -use hyperswitch_domain_models::{ - mandates, merchant_connector_account::MerchantConnectorAccount, payment_address, -}; +use hyperswitch_domain_models::{mandates, payment_address}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::logger; use rustc_hash::FxHashSet; @@ -979,66 +976,16 @@ pub async fn retrieve_default_routing_config( ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]); let db = state.store.as_ref(); - let key_manager_state = &(&state).into(); - let key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - merchant_account.get_id(), - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let id = profile_id .map(|profile_id| profile_id.get_string_repr().to_owned()) .unwrap_or_else(|| merchant_account.get_id().get_string_repr().to_string()); - let mut merchant_connector_details: HashMap< - MerchantConnectorAccountId, - MerchantConnectorAccount, - > = HashMap::new(); - state - .store - .find_merchant_connector_account_by_merchant_id_and_disabled_list( - key_manager_state, - merchant_account.get_id(), - false, - &key_store, - ) + helpers::get_merchant_default_config(db, &id, transaction_type) .await - .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { - message: format!( - "Unable to find merchant_connector_accounts associate with merchant_id: {}", - merchant_account.get_id().get_string_repr() - ), - })? - .iter() - .for_each(|mca| { - merchant_connector_details.insert(mca.get_id(), mca.clone()); - }); - - let connectors = helpers::get_merchant_default_config(db, &id, transaction_type) - .await? - .iter() - .filter(|connector| { - connector - .merchant_connector_id - .as_ref() - .is_some_and(|mca_id| { - merchant_connector_details.get(mca_id).is_some_and(|mca| { - (*transaction_type == common_enums::TransactionType::Payment - && mca.connector_type == common_enums::ConnectorType::PaymentProcessor) - || (*transaction_type == common_enums::TransactionType::Payout - && mca.connector_type - == common_enums::ConnectorType::PayoutProcessor) - }) - }) + .map(|conn_choice| { + metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); + service_api::ApplicationResponse::Json(conn_choice) }) - .cloned() - .collect::<Vec<routing_types::RoutableConnectorChoice>>(); - metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); - Ok(service_api::ApplicationResponse::Json(connectors)) } #[cfg(feature = "v2")]
2025-03-18T13:11:12Z
Reverts juspay/hyperswitch#7199 ## Description <!-- Describe your changes in detail --> We are reverting the filtering of response for payment and payout processors. So this works as follows: If Payment's route is hit all the PaymentProcessors will be listed like PayoutConnectors etc. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
e4c7ab8e683d969092910b3fcc046c2e65e18df9
Tested after creating JWT locally and adding 1 payment and 1 payout connector. Payment : ``` curl --location 'http://localhost:8080/routing/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' ``` Payout : ``` curl --location 'http://localhost:8080/routing/payout/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' ```
[ "crates/router/src/core/routing.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7548
Bug: feat(analytics): add issuer as filter for authentication analytics hotfix Add acs_reference_number as filter for authentication analytics.
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index bdcbdd86a94..4d11f19d531 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -169,6 +169,7 @@ pub async fn get_filters( AuthEventDimensions::ErrorMessage => fil.error_message, AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, + AuthEventDimensions::AcsReferenceNumber => fil.acs_reference_number, }) .collect::<Vec<String>>(); res.query_data.push(AuthEventFilterValue { diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index 5f65eeaa279..1961116b84c 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -59,4 +59,5 @@ pub struct AuthEventFilterRow { pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, } diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index a3d0fe7b683..6315c1338ee 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -45,6 +45,7 @@ pub struct AuthEventMetricRow { pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index b82d1ef4c35..fbdc4b75b3e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -110,6 +110,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 682e8a07f6b..b4c0a5c5957 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -100,6 +100,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index 047511d477c..b064cb7ab30 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -119,6 +119,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 9342e9047e0..3a122fd42a9 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -111,6 +111,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 984350efe6b..37435123623 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -105,6 +105,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index 5a2a9400b20..0265fc7e457 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -115,6 +115,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 279844388f2..178dcba20bf 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -107,6 +107,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 91e8cc54289..b78f84326de 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -112,6 +112,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index b08edb10113..d114e36f140 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -108,6 +108,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 80417ac64bf..a56d5b660aa 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -112,6 +112,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/types.rs b/crates/analytics/src/auth_events/types.rs index ac7ee2462ee..863e50a0af2 100644 --- a/crates/analytics/src/auth_events/types.rs +++ b/crates/analytics/src/auth_events/types.rs @@ -53,6 +53,15 @@ where ) .attach_printable("Error adding message version filter")?; } + + if !self.acs_reference_number.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::AcsReferenceNumber, + &self.acs_reference_number, + ) + .attach_printable("Error adding acs reference number filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 6a6237e6783..5a2f097bb0d 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -231,6 +231,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let acs_reference_number: Option<String> = + row.try_get("acs_reference_number").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -249,6 +254,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow error_message, authentication_connector, message_version, + acs_reference_number, count, start_bucket, end_bucket, @@ -288,6 +294,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let acs_reference_number: Option<String> = + row.try_get("acs_reference_number").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { authentication_status, trans_status, @@ -295,6 +306,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow error_message, authentication_connector, message_version, + acs_reference_number, }) } } diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index a0ddead1363..0832788e261 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -51,6 +51,7 @@ pub fn get_auth_event_dimensions() -> Vec<NameDescription> { vec![ AuthEventDimensions::AuthenticationConnector, AuthEventDimensions::MessageVersion, + AuthEventDimensions::AcsReferenceNumber, ] .into_iter() .map(Into::into) diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 2360e564642..8a1c168aa2f 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -23,6 +23,8 @@ pub struct AuthEventFilters { pub authentication_connector: Vec<AuthenticationConnectors>, #[serde(default)] pub message_version: Vec<String>, + #[serde(default)] + pub acs_reference_number: Vec<String>, } #[derive( @@ -50,6 +52,7 @@ pub enum AuthEventDimensions { ErrorMessage, AuthenticationConnector, MessageVersion, + AcsReferenceNumber, } #[derive( @@ -135,6 +138,7 @@ pub struct AuthEventMetricsBucketIdentifier { pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -151,6 +155,7 @@ impl AuthEventMetricsBucketIdentifier { error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, + acs_reference_number: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { @@ -160,6 +165,7 @@ impl AuthEventMetricsBucketIdentifier { error_message, authentication_connector, message_version, + acs_reference_number, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -173,6 +179,7 @@ impl Hash for AuthEventMetricsBucketIdentifier { self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); + self.acs_reference_number.hash(state); self.error_message.hash(state); self.time_bucket.hash(state); }
2025-03-18T11:22:16Z
## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7535](https://github.com/juspay/hyperswitch/pull/7535) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
8c85c9c000cc203393a6e88f9fea093b192f18d7
[ "crates/analytics/src/auth_events/core.rs", "crates/analytics/src/auth_events/filters.rs", "crates/analytics/src/auth_events/metrics.rs", "crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs", "crates/analytics/src/auth_events/metrics/authentication_count.rs", "crates/analytics/src/auth_events/metrics/authentication_error_message.rs", "crates/analytics/src/auth_events/metrics/authentication_funnel.rs", "crates/analytics/src/auth_events/metrics/authentication_success_count.rs", "crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs", "crates/analytics/src/auth_events/metrics/challenge_flow_count.rs", "crates/analytics/src/auth_events/metrics/challenge_success_count.rs", "crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs", "crates/analytics/src/auth_events/metrics/frictionless_success_count.rs", "crates/analytics/src/auth_events/types.rs", "crates/analytics/src/sqlx.rs", "crates/analytics/src/utils.rs", "crates/api_models/src/analytics/auth_events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7541
Bug: [BUG] Deserialization issue when `account_name` is not passed for globalpay during mca create Issue: - When `account_name` is not passed, which is a [required](https://developer.globalpay.com/api/transactions#/transactions_post_request__account_name) field, `5xx` is thrown: ``` {"error":{"type":"api","message":"Something went wrong","code":"HE_00"}} ├╴at crates/router/src/services/api.rs:800:14 │ ├─▶ {"error":{"type":"server_not_available","code":"HE_00","message":"Something went wrong"}} │ ╰╴at crates/router/src/core/errors/utils.rs:321:17 │ ├─▶ Parsing failed │ ╰╴at crates/hyperswitch_connectors/src/utils.rs:288:50 │ ├─▶ Failed to parse struct: hyperswitch_connectors::connectors::globalpay::transformers::GlobalPayMeta │ ├╴at /router/crates/common_utils/src/ext_traits.rs:227:14 │ ╰╴Unable to parse hyperswitch_connectors::connectors::globalpay::transformers::GlobalPayMeta from serde_json::Value: Object {"google_pay": Object {"merchant_info": Object {"merchant_name": String("Narayan Bhat")}, "allowed_payment_methods": Array [Object {"type": String("CARD"), "parameters": Object {"allowed_auth_methods": Array [String("PAN_ONLY"), String("CRYPTOGRAM_3DS")], "allowed_card_networks": Array [String("AMEX"), String("DISCOVER"), String("INTERAC"), String("JCB"), String("MASTERCARD"), String("VISA")]}, "tokenization_specification": Object {"type": String("PAYMENT_GATEWAY"), "parameters": Object {"gateway": String("example"), "gateway_merchant_id": String("22956")}}}]}} │ ╰─▶ missing field `account_name` ╰╴at /router/crates/common_utils/src/ext_traits.rs:227:14 ```
diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs index 57cf5d0f287..24cfa66ef39 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs @@ -1,6 +1,7 @@ use common_utils::{ crypto::{self, GenerateDigest}, errors::ParsingError, + pii, request::Method, types::{AmountConvertor, MinorUnit, StringMinorUnit, StringMinorUnitForConnector}, }; @@ -35,9 +36,8 @@ use super::{ use crate::{ types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ - construct_captures_response_hashmap, to_connector_meta_from_secret, CardData, - ForeignTryFrom, MultipleCaptureSyncResponse, PaymentsAuthorizeRequestData, RouterData as _, - WalletData, + self, construct_captures_response_hashmap, CardData, ForeignTryFrom, + MultipleCaptureSyncResponse, PaymentsAuthorizeRequestData, RouterData as _, WalletData, }, }; @@ -66,13 +66,23 @@ pub struct GlobalPayMeta { account_name: Secret<String>, } +impl TryFrom<&Option<pii::SecretSerdeValue>> for GlobalPayMeta { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { + let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "metadata", + })?; + Ok(metadata) + } +} + impl TryFrom<&GlobalPayRouterData<&PaymentsAuthorizeRouterData>> for GlobalpayPaymentsRequest { type Error = Error; fn try_from( item: &GlobalPayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let metadata: GlobalPayMeta = - to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())?; + let metadata = GlobalPayMeta::try_from(&item.router_data.connector_meta_data)?; let account_name = metadata.account_name; let (initiator, stored_credential, brand_reference) = get_mandate_details(item.router_data)?; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 454a090b639..e928decfdd7 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1388,6 +1388,7 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { } api_enums::Connector::Globalpay => { globalpay::transformers::GlobalpayAuthType::try_from(self.auth_type)?; + globalpay::transformers::GlobalPayMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Globepay => {
2025-03-17T17:28:25Z
## Description <!-- Describe your changes in detail --> This PR address the 5xx that occurs with GlobalPay connector when the required field `account_name` is not passed during MCA creation. Below migration needs to be run on hosted environments: ```sql UPDATE merchant_connector_account SET metadata = jsonb_set( metadata, '{account_name}', '""', true ) WHERE connector_name = 'globalpay' AND NOT metadata ? 'account_name'; ``` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Getting the connector production ready. #
10371af561ecc7536bb1db191af90a3cac2ab515
<details> <summary>0. try creating mca without passing `metadata` field</summary> ```curl curl --location 'http://Localhost:8080/account/postman_merchant_GHAction_b7e0e1f4-ca0a-495e-8a6f-915769911e30/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "globalpay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "key", "key1": "key1" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "installment_payment_enabled": true, "recurring_enabled": true } ] } ] }' ``` ```json { "error": { "type": "invalid_request", "message": "The metadata is invalid", "code": "IR_06" } } ``` </details> <details> <summary>1. try creating mca with `metadata` field but different values</summary> ```curl curl --location 'http://Localhost:8080/account/postman_merchant_GHAction_b7e0e1f4-ca0a-495e-8a6f-915769911e30/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "globalpay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "key", "key1": "key1" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "installment_payment_enabled": true, "recurring_enabled": true } ] } ] , "metadata": { "city": "NY", "unit": "245" } }' ``` ```json { "error": { "type": "invalid_request", "message": "The metadata is invalid", "code": "IR_06" } } ``` </details> <details> <summary>2. try creating mca with `metadata` field with valid values</summary> ```curl curl --location 'http://Localhost:8080/account/postman_merchant_GHAction_b7e0e1f4-ca0a-495e-8a6f-915769911e30/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "globalpay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "key", "key1": "key11" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "installment_payment_enabled": true, "recurring_enabled": true } ] } ], "metadata": { "account_name": "transaction_processing" } }' ``` ```json { "connector_type": "payment_processor", "connector_name": "globalpay", "connector_label": "globalpay_US_default", "merchant_connector_id": "mca_lZZrlORyN0n7fuQpEgKz", "profile_id": "pro_cKEsY4S7wK3izgeOFXhw", "connector_account_details": { "auth_type": "BodyKey", "api_key": "****************", "key1": "********************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "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", "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": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "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": null, "maximum_amount": null, "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": null, "maximum_amount": null, "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": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "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": "google_pay", "payment_experience": "invoke_sdk_client", "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": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": { "account_name": "transaction_processing" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` </details> <details> <summary>3. try creating mca with `metadata` field with valid values and additional values like certs</summary> ```curl curl --location 'http://Localhost:8080/account/postman_merchant_GHAction_798f9222-9a5f-4cb3-8e61-3ae4c576b6b9/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "globalpay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "key", "key1": "key1" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "installment_payment_enabled": true, "recurring_enabled": true } ] } ], "metadata": { "account_name": "transaction_processing" , "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": "22956" } } } ], "merchant_info": { "merchant_name": "Narayan Bhat" } } } }' ``` ```json { "connector_type": "payment_processor", "connector_name": "globalpay", "connector_label": "globalpay_US_default", "merchant_connector_id": "mca_a45nhudvFQkdJeOTrJqd", "profile_id": "pro_zdAl1MuX7MuMUsGzlRZw", "connector_account_details": { "auth_type": "BodyKey", "api_key": "****************", "key1": "********************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "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", "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": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "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": null, "maximum_amount": null, "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": null, "maximum_amount": null, "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": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "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": "google_pay", "payment_experience": "invoke_sdk_client", "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": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": { "google_pay": { "merchant_info": { "merchant_name": "Narayan Bhat" }, "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": "22956" } } } ] }, "account_name": "transaction_processing" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` </details> <details> <summary>4. tried making a payment</summary> ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_8jOdTW9kwO9a50lrA8OfxY6m0iDGOhjpi2BJseJtaCU9xFz5YR6ROHuKYCeiTuz7' \ --data-raw '{ "amount": 1000, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4263970000005262", "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" } } }' ``` ```json { "payment_id": "pay_APA4HDesgk5NntotYd5P", "merchant_id": "postman_merchant_GHAction_798f9222-9a5f-4cb3-8e61-3ae4c576b6b9", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "globalpay", "client_secret": "pay_APA4HDesgk5NntotYd5P_secret_VLhRFg5ApKxEhnzxQbho", "created": "2025-03-17T17:25:53.489Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5262", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "426397", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1742232353, "expires": 1742235953, "secret": "epk_84c190a7359d4428a18118725e659805" }, "manual_retry_allowed": false, "connector_transaction_id": "TRN_aQvML8KHNMNMhOv3OHBZhO3hK3xQXC_5NntotYd5P_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_APA4HDesgk5NntotYd5P_1", "payment_link": null, "profile_id": "pro_zdAl1MuX7MuMUsGzlRZw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_a45nhudvFQkdJeOTrJqd", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-17T17:40:53.489Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-17T17:25:55.934Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` </details>
[ "crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs", "crates/router/src/core/admin.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7534
Bug: feat(analytics): add issuer as filter for authentication analytics Add `acs_reference_number` as filter for authentication analytics.
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index bdcbdd86a94..4d11f19d531 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -169,6 +169,7 @@ pub async fn get_filters( AuthEventDimensions::ErrorMessage => fil.error_message, AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, + AuthEventDimensions::AcsReferenceNumber => fil.acs_reference_number, }) .collect::<Vec<String>>(); res.query_data.push(AuthEventFilterValue { diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index 5f65eeaa279..1961116b84c 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -59,4 +59,5 @@ pub struct AuthEventFilterRow { pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, } diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index a3d0fe7b683..6315c1338ee 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -45,6 +45,7 @@ pub struct AuthEventMetricRow { pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index b82d1ef4c35..fbdc4b75b3e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -110,6 +110,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 682e8a07f6b..b4c0a5c5957 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -100,6 +100,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index 047511d477c..b064cb7ab30 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -119,6 +119,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 9342e9047e0..3a122fd42a9 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -111,6 +111,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 984350efe6b..37435123623 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -105,6 +105,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index 5a2a9400b20..0265fc7e457 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -115,6 +115,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 279844388f2..178dcba20bf 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -107,6 +107,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 91e8cc54289..b78f84326de 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -112,6 +112,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index b08edb10113..d114e36f140 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -108,6 +108,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 80417ac64bf..a56d5b660aa 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -112,6 +112,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/types.rs b/crates/analytics/src/auth_events/types.rs index ac7ee2462ee..863e50a0af2 100644 --- a/crates/analytics/src/auth_events/types.rs +++ b/crates/analytics/src/auth_events/types.rs @@ -53,6 +53,15 @@ where ) .attach_printable("Error adding message version filter")?; } + + if !self.acs_reference_number.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::AcsReferenceNumber, + &self.acs_reference_number, + ) + .attach_printable("Error adding acs reference number filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 6a6237e6783..5a2f097bb0d 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -231,6 +231,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let acs_reference_number: Option<String> = + row.try_get("acs_reference_number").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -249,6 +254,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow error_message, authentication_connector, message_version, + acs_reference_number, count, start_bucket, end_bucket, @@ -288,6 +294,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let acs_reference_number: Option<String> = + row.try_get("acs_reference_number").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { authentication_status, trans_status, @@ -295,6 +306,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow error_message, authentication_connector, message_version, + acs_reference_number, }) } } diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index a0ddead1363..0832788e261 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -51,6 +51,7 @@ pub fn get_auth_event_dimensions() -> Vec<NameDescription> { vec![ AuthEventDimensions::AuthenticationConnector, AuthEventDimensions::MessageVersion, + AuthEventDimensions::AcsReferenceNumber, ] .into_iter() .map(Into::into) diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 2360e564642..8a1c168aa2f 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -23,6 +23,8 @@ pub struct AuthEventFilters { pub authentication_connector: Vec<AuthenticationConnectors>, #[serde(default)] pub message_version: Vec<String>, + #[serde(default)] + pub acs_reference_number: Vec<String>, } #[derive( @@ -50,6 +52,7 @@ pub enum AuthEventDimensions { ErrorMessage, AuthenticationConnector, MessageVersion, + AcsReferenceNumber, } #[derive( @@ -135,6 +138,7 @@ pub struct AuthEventMetricsBucketIdentifier { pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -151,6 +155,7 @@ impl AuthEventMetricsBucketIdentifier { error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, + acs_reference_number: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { @@ -160,6 +165,7 @@ impl AuthEventMetricsBucketIdentifier { error_message, authentication_connector, message_version, + acs_reference_number, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -173,6 +179,7 @@ impl Hash for AuthEventMetricsBucketIdentifier { self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); + self.acs_reference_number.hash(state); self.error_message.hash(state); self.time_bucket.hash(state); }
2025-03-17T11:39:35Z
## Description <!-- Describe your changes in detail --> Added `acs_reference_number` as filter for authentication analytics. Will display it as `issuer` on FE dashboard. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Better insights into authentication data by applying filters #
2d17dad25d0966fc95f17e0ee91598ea445d4dc9
Get Info curl: ```bash curl --location 'http://localhost:8080/analytics/v1/auth_events/info' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Referer: http://localhost:9000/dashboard/analytics-payments' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-origin' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36' \ --header 'X-Merchant-Id: merchant_1740414909' \ --header 'X-Profile-Id: pro_q9g6emqpc7b41Lo7UXpx' \ --header 'api-key: dev_zKT6VT7TvcxCtwq8N716HELM6HZJAwZvkWVHrlKAU54Pzu6D18GL3u3UswnkMkug' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' ``` Sample Output: ```json { "metrics": [ { "name": "authentication_count", "desc": "" }, { "name": "authentication_attempt_count", "desc": "" }, { "name": "authentication_success_count", "desc": "" }, { "name": "challenge_flow_count", "desc": "" }, { "name": "frictionless_flow_count", "desc": "" }, { "name": "frictionless_success_count", "desc": "" }, { "name": "challenge_attempt_count", "desc": "" }, { "name": "challenge_success_count", "desc": "" }, { "name": "authentication_error_message", "desc": "" }, { "name": "authentication_funnel", "desc": "" } ], "downloadDimensions": null, "dimensions": [ { "name": "authentication_connector", "desc": "" }, { "name": "message_version", "desc": "" }, { "name": "acs_reference_number", "desc": "" } ] } ``` acs_reference_number is being sent in the dimensions list. Filters API: ```bash curl --location 'http://localhost:8080/analytics/v1/filters/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2RlMDFhYWYtOWVkMi00YTY5LTg3YWItNWU1YmI2ZWFiNGQ5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQyMjEyMzQxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MjM4NTE0Miwib3JnX2lkIjoib3JnX3pMQmRNTnpLaDZrNmhiT2tockdJIiwicHJvZmlsZV9pZCI6InByb19LWnhHZ21rUHFkMldQdXBFa2psWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.efMstkbz90nfMKju4PmdIedl_tN-FHW3aQKD44jOnxo' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '{ "timeRange": { "startTime": "2025-02-01T18:30:00.000Z", "endTime": "2025-02-28T09:22:30.000Z" }, "groupByNames": [ "message_version", "authentication_connector", "acs_reference_number" ], "source": "BATCH", "delta": true }' ``` Sample Output: ```json { "queryData": [ { "dimension": "message_version", "values": [ "2.3.1" ] }, { "dimension": "authentication_connector", "values": [ "netcetera" ] }, { "dimension": "acs_reference_number", "values": [ "3DS_LOA_ACS_201_13579" ] } ] } ```
[ "crates/analytics/src/auth_events/core.rs", "crates/analytics/src/auth_events/filters.rs", "crates/analytics/src/auth_events/metrics.rs", "crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs", "crates/analytics/src/auth_events/metrics/authentication_count.rs", "crates/analytics/src/auth_events/metrics/authentication_error_message.rs", "crates/analytics/src/auth_events/metrics/authentication_funnel.rs", "crates/analytics/src/auth_events/metrics/authentication_success_count.rs", "crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs", "crates/analytics/src/auth_events/metrics/challenge_flow_count.rs", "crates/analytics/src/auth_events/metrics/challenge_success_count.rs", "crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs", "crates/analytics/src/auth_events/metrics/frictionless_success_count.rs", "crates/analytics/src/auth_events/types.rs", "crates/analytics/src/sqlx.rs", "crates/analytics/src/utils.rs", "crates/api_models/src/analytics/auth_events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7533
Bug: Add zero auth mandates support for nexixpay Zero auth mandates support for nexixpay.
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index 8e0694336b5..b047d99a9d0 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -72,10 +72,7 @@ use hyperswitch_interfaces::{ use masking::{ExposeInterface, Mask, Maskable, Secret}; use ring::hmac; use router_env::{instrument, tracing}; -use transformers::{ - self as adyen, convert_payment_authorize_router_response, - convert_setup_mandate_router_data_to_authorize_router_data, -}; +use transformers as adyen; #[cfg(feature = "payouts")] use crate::utils::PayoutsData as UtilsPayoutData; @@ -86,7 +83,11 @@ use crate::{ AcceptDisputeRouterData, DefendDisputeRouterData, ResponseRouterData, SubmitEvidenceRouterData, }, - utils::{self as connector_utils, is_mandate_supported, ForeignTryFrom, PaymentMethodDataType}, + utils::{ + self as connector_utils, convert_payment_authorize_router_response, + convert_setup_mandate_router_data_to_authorize_router_data, is_mandate_supported, + ForeignTryFrom, PaymentMethodDataType, + }, }; const ADYEN_API_VERSION: &str = "v68"; diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 793a33e1fc1..2e87967b0f9 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -1,5 +1,3 @@ -use std::marker::PhantomData; - #[cfg(feature = "payouts")] use api_models::payouts::{self, PayoutMethodData}; use api_models::{ @@ -27,16 +25,14 @@ use hyperswitch_domain_models::{ router_data::{ ConnectorAuthType, ErrorResponse, PaymentMethodBalance, PaymentMethodToken, RouterData, }, - router_request_types::{ - PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId, SubmitEvidenceRequestData, - }, + router_request_types::{PaymentsPreProcessingData, ResponseId, SubmitEvidenceRequestData}, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, SubmitEvidenceResponse, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsPreProcessingRouterData, RefundsRouterData, SetupMandateRouterData, + PaymentsPreProcessingRouterData, RefundsRouterData, }, }; #[cfg(feature = "payouts")] @@ -5545,106 +5541,3 @@ impl }) } } - -pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data( - data: &SetupMandateRouterData, -) -> PaymentsAuthorizeData { - PaymentsAuthorizeData { - currency: data.request.currency, - payment_method_data: data.request.payment_method_data.clone(), - confirm: data.request.confirm, - statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), - mandate_id: data.request.mandate_id.clone(), - setup_future_usage: data.request.setup_future_usage, - off_session: data.request.off_session, - setup_mandate_details: data.request.setup_mandate_details.clone(), - router_return_url: data.request.router_return_url.clone(), - email: data.request.email.clone(), - customer_name: data.request.customer_name.clone(), - amount: 0, - order_tax_amount: Some(MinorUnit::zero()), - minor_amount: MinorUnit::new(0), - statement_descriptor: None, - capture_method: None, - webhook_url: None, - complete_authorize_url: None, - browser_info: data.request.browser_info.clone(), - order_details: None, - order_category: None, - session_token: None, - enrolled_for_3ds: true, - related_transaction_id: None, - payment_experience: None, - payment_method_type: None, - customer_id: None, - surcharge_details: None, - request_incremental_authorization: data.request.request_incremental_authorization, - metadata: None, - authentication_data: None, - customer_acceptance: data.request.customer_acceptance.clone(), - split_payments: None, // TODO: allow charges on mandates? - merchant_order_reference_id: None, - integrity_object: None, - additional_payment_method_data: None, - shipping_cost: data.request.shipping_cost, - merchant_account_id: None, - merchant_config_currency: None, - } -} - -pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>( - item: (&RouterData<F1, T1, PaymentsResponseData>, T2), -) -> RouterData<F2, T2, PaymentsResponseData> { - let data = item.0; - let request = item.1; - RouterData { - flow: PhantomData, - request, - merchant_id: data.merchant_id.clone(), - connector: data.connector.clone(), - attempt_id: data.attempt_id.clone(), - tenant_id: data.tenant_id.clone(), - status: data.status, - payment_method: data.payment_method, - connector_auth_type: data.connector_auth_type.clone(), - description: data.description.clone(), - address: data.address.clone(), - auth_type: data.auth_type, - connector_meta_data: data.connector_meta_data.clone(), - connector_wallets_details: data.connector_wallets_details.clone(), - amount_captured: data.amount_captured, - minor_amount_captured: data.minor_amount_captured, - access_token: data.access_token.clone(), - response: data.response.clone(), - 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, - preprocessing_id: None, - connector_customer: data.connector_customer.clone(), - recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(), - connector_request_reference_id: data.connector_request_reference_id.clone(), - #[cfg(feature = "payouts")] - payout_method_data: data.payout_method_data.clone(), - #[cfg(feature = "payouts")] - quote_id: data.quote_id.clone(), - test_mode: data.test_mode, - payment_method_status: None, - payment_method_balance: data.payment_method_balance.clone(), - connector_api_version: data.connector_api_version.clone(), - connector_http_status_code: data.connector_http_status_code, - external_latency: data.external_latency, - apple_pay_flow: data.apple_pay_flow.clone(), - frm_metadata: data.frm_metadata.clone(), - dispute_id: data.dispute_id.clone(), - refund_id: data.refund_id.clone(), - connector_response: data.connector_response.clone(), - integrity_check: Ok(()), - additional_merchant_data: data.additional_merchant_data.clone(), - header_payload: data.header_payload.clone(), - connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(), - authentication_id: data.authentication_id.clone(), - psd2_sca_exemption_type: data.psd2_sca_exemption_type, - } -} diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs index 264bca6b5a9..bed54d66e4d 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs @@ -32,7 +32,7 @@ use hyperswitch_domain_models::{ types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, - PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::{ @@ -228,6 +228,91 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nexixpay { + fn get_headers( + &self, + req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/orders/3steps/init", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &SetupMandateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let authorize_req = utils::convert_payment_authorize_router_response(( + req, + utils::convert_setup_mandate_router_data_to_authorize_router_data(req), + )); + + let amount = utils::convert_amount( + self.amount_converter, + authorize_req.request.minor_amount, + authorize_req.request.currency, + )?; + + let connector_router_data = nexixpay::NexixpayRouterData::from((amount, &authorize_req)); + let connector_req = nexixpay::NexixpayPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::SetupMandateType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::SetupMandateType::get_headers(self, req, connectors)?) + .set_body(types::SetupMandateType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> { + let response: nexixpay::PaymentsResponse = res + .response + .parse_struct("PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 27eebf78dfb..06925eea6cf 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -9,10 +9,13 @@ use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, + router_flow_types::{ + refunds::{Execute, RSync}, + SetupMandate, + }, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsPreProcessingData, PaymentsSyncData, ResponseId, + PaymentsPreProcessingData, PaymentsSyncData, ResponseId, SetupMandateRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, @@ -31,7 +34,8 @@ use crate::{ utils::{ get_unimplemented_payment_method_error_message, to_connector_meta, to_connector_meta_from_secret, CardData, PaymentsAuthorizeRequestData, - PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _, + PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, + PaymentsSetupMandateRequestData, RouterData as _, }, }; @@ -1290,3 +1294,74 @@ impl<F> }) } } + +impl + TryFrom< + ResponseRouterData< + SetupMandate, + PaymentsResponse, + SetupMandateRequestData, + PaymentsResponseData, + >, + > for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + SetupMandate, + PaymentsResponse, + SetupMandateRequestData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let complete_authorize_url = item.data.request.get_complete_authorize_url()?; + let operation_id: String = item.response.operation.operation_id.clone(); + let redirection_form = nexixpay_threeds_link(NexixpayRedirectionRequest { + three_d_s_auth_url: item + .response + .three_d_s_auth_url + .clone() + .expose() + .to_string(), + three_ds_request: item.response.three_d_s_auth_request.clone(), + return_url: complete_authorize_url.clone(), + transaction_id: operation_id.clone(), + })?; + let is_auto_capture = item.data.request.is_auto_capture()?; + let connector_metadata = Some(serde_json::json!(NexixpayConnectorMetaData { + three_d_s_auth_result: None, + three_d_s_auth_response: None, + authorization_operation_id: Some(operation_id.clone()), + cancel_operation_id: None, + capture_operation_id: { + if is_auto_capture { + Some(operation_id) + } else { + None + } + }, + psync_flow: NexixpayPaymentIntent::Authorize + })); + Ok(Self { + status: AttemptStatus::from(item.response.operation.operation_result.clone()), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.operation.order_id.clone(), + ), + redirection_data: Box::new(Some(redirection_form.clone())), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some(item.response.operation.order_id.clone()), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index a34699498b5..b1bd7a04d5f 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1,5 +1,6 @@ use std::{ collections::{HashMap, HashSet}, + marker::PhantomData, str::FromStr, }; @@ -44,6 +45,7 @@ use hyperswitch_domain_models::{ payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData}, router_data::{ ApplePayPredecryptData, ErrorResponse, PaymentMethodToken, RecurringMandatePaymentData, + RouterData as ConnectorRouterData, }, router_request_types::{ AuthenticationData, BrowserInformation, CompleteAuthorizeData, ConnectorCustomerData, @@ -52,8 +54,8 @@ use hyperswitch_domain_models::{ PaymentsPreProcessingData, PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData, }, - router_response_types::CaptureSyncResponse, - types::OrderDetailsWithAmount, + router_response_types::{CaptureSyncResponse, PaymentsResponseData}, + types::{OrderDetailsWithAmount, SetupMandateRouterData}, }; use hyperswitch_interfaces::{api, consts, errors, types::Response}; use image::{DynamicImage, ImageBuffer, ImageFormat, Luma, Rgba}; @@ -2014,6 +2016,8 @@ pub trait PaymentsSetupMandateRequestData { fn get_return_url(&self) -> Result<String, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_optional_language_from_browser_info(&self) -> Option<String>; + fn get_complete_authorize_url(&self) -> Result<String, Error>; + fn is_auto_capture(&self) -> Result<bool, Error>; } impl PaymentsSetupMandateRequestData for SetupMandateRequestData { @@ -2048,6 +2052,20 @@ impl PaymentsSetupMandateRequestData for SetupMandateRequestData { .clone() .and_then(|browser_info| browser_info.language) } + fn get_complete_authorize_url(&self) -> Result<String, Error> { + self.complete_authorize_url + .clone() + .ok_or_else(missing_field_err("complete_authorize_url")) + } + fn is_auto_capture(&self) -> Result<bool, Error> { + match self.capture_method { + Some(enums::CaptureMethod::Automatic) + | Some(enums::CaptureMethod::SequentialAutomatic) + | None => Ok(true), + Some(enums::CaptureMethod::Manual) => Ok(false), + Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), + } + } } pub trait PaymentMethodTokenizationRequestData { @@ -5855,3 +5873,106 @@ where let output = <&str>::deserialize(v)?; output.to_uppercase().parse::<T>().map_err(D::Error::custom) } + +pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data( + data: &SetupMandateRouterData, +) -> PaymentsAuthorizeData { + PaymentsAuthorizeData { + currency: data.request.currency, + payment_method_data: data.request.payment_method_data.clone(), + confirm: data.request.confirm, + statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), + mandate_id: data.request.mandate_id.clone(), + setup_future_usage: data.request.setup_future_usage, + off_session: data.request.off_session, + setup_mandate_details: data.request.setup_mandate_details.clone(), + router_return_url: data.request.router_return_url.clone(), + email: data.request.email.clone(), + customer_name: data.request.customer_name.clone(), + amount: 0, + order_tax_amount: Some(MinorUnit::zero()), + minor_amount: MinorUnit::new(0), + statement_descriptor: None, + capture_method: None, + webhook_url: None, + complete_authorize_url: None, + browser_info: data.request.browser_info.clone(), + order_details: None, + order_category: None, + session_token: None, + enrolled_for_3ds: true, + related_transaction_id: None, + payment_experience: None, + payment_method_type: None, + customer_id: None, + surcharge_details: None, + request_incremental_authorization: data.request.request_incremental_authorization, + metadata: None, + authentication_data: None, + customer_acceptance: data.request.customer_acceptance.clone(), + split_payments: None, // TODO: allow charges on mandates? + merchant_order_reference_id: None, + integrity_object: None, + additional_payment_method_data: None, + shipping_cost: data.request.shipping_cost, + merchant_account_id: None, + merchant_config_currency: None, + } +} + +pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>( + item: (&ConnectorRouterData<F1, T1, PaymentsResponseData>, T2), +) -> ConnectorRouterData<F2, T2, PaymentsResponseData> { + let data = item.0; + let request = item.1; + ConnectorRouterData { + flow: PhantomData, + request, + merchant_id: data.merchant_id.clone(), + connector: data.connector.clone(), + attempt_id: data.attempt_id.clone(), + tenant_id: data.tenant_id.clone(), + status: data.status, + payment_method: data.payment_method, + connector_auth_type: data.connector_auth_type.clone(), + description: data.description.clone(), + address: data.address.clone(), + auth_type: data.auth_type, + connector_meta_data: data.connector_meta_data.clone(), + connector_wallets_details: data.connector_wallets_details.clone(), + amount_captured: data.amount_captured, + minor_amount_captured: data.minor_amount_captured, + access_token: data.access_token.clone(), + response: data.response.clone(), + 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, + preprocessing_id: None, + connector_customer: data.connector_customer.clone(), + recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(), + connector_request_reference_id: data.connector_request_reference_id.clone(), + #[cfg(feature = "payouts")] + payout_method_data: data.payout_method_data.clone(), + #[cfg(feature = "payouts")] + quote_id: data.quote_id.clone(), + test_mode: data.test_mode, + payment_method_status: None, + payment_method_balance: data.payment_method_balance.clone(), + connector_api_version: data.connector_api_version.clone(), + connector_http_status_code: data.connector_http_status_code, + external_latency: data.external_latency, + apple_pay_flow: data.apple_pay_flow.clone(), + frm_metadata: data.frm_metadata.clone(), + dispute_id: data.dispute_id.clone(), + refund_id: data.refund_id.clone(), + connector_response: data.connector_response.clone(), + integrity_check: Ok(()), + additional_merchant_data: data.additional_merchant_data.clone(), + header_payload: data.header_payload.clone(), + connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(), + authentication_id: data.authentication_id.clone(), + psd2_sca_exemption_type: data.psd2_sca_exemption_type, + } +} diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index ff5534dcebc..4671c4552f0 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -918,6 +918,8 @@ pub struct SetupMandateRequestData { pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub request_incremental_authorization: bool, pub metadata: Option<pii::SecretSerdeValue>, + pub complete_authorize_url: Option<String>, + pub capture_method: Option<storage_enums::CaptureMethod>, // MinorUnit for amount framework pub minor_amount: Option<MinorUnit>, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 804516b86a4..f50e28e940a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -958,6 +958,8 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( metadata: payment_data.payment_intent.metadata, minor_amount: Some(payment_data.payment_attempt.amount_details.get_net_amount()), shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, + capture_method: Some(payment_data.payment_intent.capture_method), + complete_authorize_url, }; let connector_mandate_request_reference_id = payment_data .payment_attempt @@ -4001,6 +4003,12 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); + let complete_authorize_url = Some(helpers::create_complete_authorize_url( + router_base_url, + attempt, + connector_name, + payment_data.creds_identifier.as_deref(), + )); Ok(Self { currency: payment_data.currency, @@ -4032,6 +4040,8 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ metadata: payment_data.payment_intent.metadata.clone().map(Into::into), shipping_cost: payment_data.payment_intent.shipping_cost, webhook_url, + complete_authorize_url, + capture_method: payment_data.payment_attempt.capture_method, }) } }
2025-03-17T09:06:38Z
## Description <!-- Describe your changes in detail --> Add zero auth mandate flow for nexixpay connector. It uses 3ds payments flow to create mandates. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> We have to add support for zero amount CIT payments for nexixpay so that merchants can do MIT payments with required value. #
a87471c45dee50e7b9c9674aa8c9bb668c892917
Cypress test: <img width="1728" alt="image" src="https://github.com/user-attachments/assets/63853683-40cd-409c-a3e7-00c1b0ffc0e0" /> Below curls should be used for testing zero auth mandates: 1. Payments CIT ``` curl --location 'localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PczXRK73enU0k1JDyjEZ8u76iSUxrocg963jiEzfbY7z1ncgosfLvQFlRoHOcux4' \ --data-raw '{ "amount": 0, "currency": "EUR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://abc.com", "email": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage": "off_session" }' ``` 2. Confirm CIT ``` curl --location 'http://localhost:8080/payments/pay_I46gW94NSY7cGwi0BTjl/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PczXRK73enU0k1JDyjEZ8u76iSUxrocg963jiEzfbY7z1ncgosfLvQFlRoHOcux4' \ --data-raw '{ "confirm": true, "customer_id": "customer123", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "online", "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", "email": "[email protected]", "payment_method_data": { "card": { "card_number": "4349940199004549", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "396" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IT", "first_name": "joseph", "last_name": "Doe" }, "email": "[email protected]", "phone": { "number": "8056594427", "country_code": "+91" } } } }' ``` 3. MIT payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PczXRK73enU0k1JDyjEZ8u76iSUxrocg963jiEzfbY7z1ncgosfLvQFlRoHOcux4' \ --data '{ "amount": 3545, "currency": "EUR", "confirm": true, "customer_id": "customer123", "recurring_details": { "type": "payment_method_id", "data": "pm_unSAF4FSldeu1wAeLvpe" }, "off_session": true }' ```
[ "crates/hyperswitch_connectors/src/connectors/adyen.rs", "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", "crates/hyperswitch_connectors/src/connectors/nexixpay.rs", "crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs", "crates/hyperswitch_connectors/src/utils.rs", "crates/hyperswitch_domain_models/src/router_request_types.rs", "crates/router/src/core/payments/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7529
Bug: [FEATURE] emit payment status before rendering the UI ### Feature Description Payment link to emit the latest payment intent status before mounting the SDK and rendering UI. Usecase - this can be used by merchants who embed these links as an iframe to take decision based on the latest intent status. ### Possible Implementation Before mounting SDK or rendering the UI, emit an event via `postMessage` which can be listened on by the parent window. Message format ``` { "payment": { "status": "IntentStatus" } } ``` ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 27d7b82e547..840d4274709 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7944,6 +7944,7 @@ pub struct PaymentLinkDetails { pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index c13e087947b..48004dd740b 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -191,7 +191,7 @@ pub async fn form_payment_link_data( let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let payment_link_status = check_payment_link_status(session_expiry); - let is_terminal_state = check_payment_link_invalid_conditions( + let is_payment_link_terminal_state = check_payment_link_invalid_conditions( payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, @@ -201,9 +201,11 @@ pub async fn form_payment_link_data( storage_enums::IntentStatus::RequiresMerchantAction, storage_enums::IntentStatus::Succeeded, storage_enums::IntentStatus::PartiallyCaptured, + storage_enums::IntentStatus::RequiresCustomerAction, ], ); - if is_terminal_state || payment_link_status == api_models::payments::PaymentLinkStatus::Expired + if is_payment_link_terminal_state + || payment_link_status == api_models::payments::PaymentLinkStatus::Expired { let status = match payment_link_status { api_models::payments::PaymentLinkStatus::Active => { @@ -211,7 +213,7 @@ pub async fn form_payment_link_data( PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } api_models::payments::PaymentLinkStatus::Expired => { - if is_terminal_state { + if is_payment_link_terminal_state { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } else { @@ -292,6 +294,7 @@ pub async fn form_payment_link_data( payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), + status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, }; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index e73e23076a9..5c6f3a6b373 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -181,6 +181,30 @@ var hyper = null; const translations = getTranslations(window.__PAYMENT_DETAILS.locale); +var isFramed = false; +try { + isFramed = window.parent.location !== window.location; + + // If parent's window object is restricted, DOMException is + // thrown which concludes that the webpage is iframed +} catch (err) { + isFramed = true; +} + +/** + * Trigger - on boot + * Use - emit latest payment status to parent window + */ +function emitPaymentStatus(paymentDetails) { + var message = { + payment: { + status: paymentDetails.status, + } + }; + + window.parent.postMessage(message, "*"); +} + /** * Trigger - init function invoked once the script tag is loaded * Use @@ -190,13 +214,16 @@ const translations = getTranslations(window.__PAYMENT_DETAILS.locale); * - Initialize event listeners for updating UI on screen size changes * - Initialize SDK **/ - - function boot() { // @ts-ignore var paymentDetails = window.__PAYMENT_DETAILS; + // Emit latest payment status + if (isFramed) { + emitPaymentStatus(paymentDetails); + } + if (paymentDetails.display_sdk_only) { hide(".checkout-page") var sdkDisplayWidth = document.querySelector('.hyper-checkout-sdk'); diff --git a/crates/router/src/core/payment_link/payment_link_status/status.css b/crates/router/src/core/payment_link/payment_link_status/status.css index 113f1353138..65b7b11d956 100644 --- a/crates/router/src/core/payment_link/payment_link_status/status.css +++ b/crates/router/src/core/payment_link/payment_link_status/status.css @@ -137,6 +137,10 @@ body > div { font-size: 13px; } +.hidden { + display: none; +} + .ellipsis-container-2 { height: 2.5em; overflow: hidden; diff --git a/crates/router/src/core/payment_link/payment_link_status/status.html b/crates/router/src/core/payment_link/payment_link_status/status.html index c78a0bb556d..7531c8df444 100644 --- a/crates/router/src/core/payment_link/payment_link_status/status.html +++ b/crates/router/src/core/payment_link/payment_link_status/status.html @@ -16,7 +16,7 @@ {{ rendered_js }} </script> </head> - <body onload="boot()"> + <body onload="boot()" class="hidden"> <div> <div class="hyper-checkout-status-wrap"> <div id="hyper-checkout-status-header"></div> diff --git a/crates/router/src/core/payment_link/payment_link_status/status.js b/crates/router/src/core/payment_link/payment_link_status/status.js index 8c9697fd53e..16949d546a6 100644 --- a/crates/router/src/core/payment_link/payment_link_status/status.js +++ b/crates/router/src/core/payment_link/payment_link_status/status.js @@ -52,8 +52,8 @@ function invertToBW(color, bw, asArr) { ? hexToRgbArray(options.black) : options.black : asArr - ? hexToRgbArray(options.white) - : options.white; + ? hexToRgbArray(options.white) + : options.white; } function invert(color, bw) { if (bw === void 0) { @@ -87,6 +87,31 @@ window.state = { }; const translations = getTranslations(window.__PAYMENT_DETAILS.locale); + +var isFramed = false; +try { + isFramed = window.parent.location !== window.location; + + // If parent's window object is restricted, DOMException is + // thrown which concludes that the webpage is iframed +} catch (err) { + isFramed = true; +} + +/** + * Trigger - on boot + * Use - emit latest payment status to parent window + */ +function emitPaymentStatus(paymentDetails) { + var message = { + payment: { + status: paymentDetails.status, + } + }; + + window.parent.postMessage(message, "*"); +} + /** * Trigger - init function invoked once the script tag is loaded * Use @@ -100,20 +125,43 @@ function boot() { // @ts-ignore var paymentDetails = window.__PAYMENT_DETAILS; - // Attach document icon - if (paymentDetails.merchant_logo) { - var link = document.createElement("link"); - link.rel = "icon"; - link.href = paymentDetails.merchant_logo; - link.type = "image/x-icon"; - document.head.appendChild(link); + // Emit latest payment status + if (isFramed) { + emitPaymentStatus(paymentDetails); } - // Render status details - renderStatusDetails(paymentDetails); + if (shouldRenderUI(paymentDetails)) { + removeClass("body", "hidden"); + // Attach document icon + if (paymentDetails.merchant_logo) { + var link = document.createElement("link"); + link.rel = "icon"; + link.href = paymentDetails.merchant_logo; + link.type = "image/x-icon"; + document.head.appendChild(link); + } + + // Render status details + renderStatusDetails(paymentDetails); - // Add event listeners - initializeEventListeners(paymentDetails); + // Add event listeners + initializeEventListeners(paymentDetails); + } +} + +/** + * Trigger - on boot + * Use - Check if UI should be rendered based on some conditions + * @returns {Boolean} + */ +function shouldRenderUI(paymentDetails) { + var status = paymentDetails.status; + if (isFramed) { + switch (status) { + case "requires_customer_action": return false; + } + } + return true; } /** @@ -158,6 +206,7 @@ function renderStatusDetails(paymentDetails) { ).toTimeString(); break; + case "requires_customer_action": case "processing": statusDetails.imageSource = "https://live.hyperswitch.io/payment-link-assets/pending.png"; statusDetails.message = translations.paymentTakingLonger; @@ -279,7 +328,7 @@ function renderStatusDetails(paymentDetails) { var innerText = secondsLeft === 0 ? translations.redirecting - : translations.redirectingIn + secondsLeft + " "+translations.seconds; + : translations.redirectingIn + secondsLeft + " " + translations.seconds; // @ts-ignore statusRedirectTextNode.innerText = innerText; if (secondsLeft === 0) { @@ -341,5 +390,18 @@ function initializeEventListeners(paymentDetails) { if (statusRedirectTextNode instanceof HTMLDivElement) { statusRedirectTextNode.style.color = contrastBWColor; } - }; +}; +function addClass(id, className) { + var element = document.querySelector(id); + if (element instanceof HTMLElement) { + element.classList.add(className); + } +} + +function removeClass(id, className) { + var element = document.querySelector(id); + if (element instanceof HTMLElement) { + element.classList.remove(className); + } +} \ No newline at end of file
2025-03-17T08:03:13Z
## Description This PR adds functionality for payment links to - emit latest payment intent status before rendering status UI or payment widget - consider `requires_customer_action` as payment link's terminal state ## Motivation and Context Helps merchants take action for `requires_customer_action` state in case user re-renders the link for the mentioned intent status. # ##### Things to test [expected behavior in both the cases - payment link should redirect to the link mentioned in HTML template] - Make a redirection payment, and come back to the iframe - Wait for payment link to be expired, and come back to the iframe
f6633a72d5f826804c6a24317f8e5c836b0bc95a
Tested locally using an iframe. <details> <summary>1. Use below template for payment links</summary> ``` <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> html, body { margin: 0; display: flex; align-items: center; justify-content: center; background-color: bisque; height: 100vh; width: 100vw; } iframe { border-radius: 4px; height: 90vh; width: 90vw; background-color: white; } </style> </head> <body> <iframe src="http://localhost:8080/payment_link/merchant_1742192403/pay_1aHs36MZD0zffE4bO538?locale=en" frameborder="0"></iframe> </body> <script> window.addEventListener("message", function(event) { if (event.origin === "http://localhost:8080") { var status = event.data.payment.status; switch (status) { case "expired": case "requires_customer_action": { window.location.href = "https://google.com"; } } } }); </script> </html> ``` </details> <details> <summary>2. Create a payment link</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_4AE12pRff5kcWKXt1Dn3CfMCHOtgfXPyAO92s8kWae1xALFonMSs2hzpAGZ1ov6Q' \ --data-raw '{"customer_id":"cus_ALQFPJO2ZOSIg4XOUIZo","profile_id":"pro_qukvQ1whBBb6pdKnzvvN","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":100,"currency":"USD","payment_link":true,"capture_method":"automatic","email":"[email protected]","session_expiry":100000,"return_url":"https://example.com","payment_link_config_id":"style1"}' Response {"payment_id":"pay_yzSbFQNh8oJoa6cSkxQM","merchant_id":"merchant_1742192403","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_yzSbFQNh8oJoa6cSkxQM_secret_tPrHESV8PXuLApSxMxZj","created":"2025-03-17T08:06:06.305Z","currency":"USD","customer_id":"cus_ALQFPJO2ZOSIg4XOUIZo","customer":{"id":"cus_ALQFPJO2ZOSIg4XOUIZo","name":"John Nether","email":"[email protected]","phone":"6168205362","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Nether","phone":"6168205362","return_url":"https://example.com/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_ALQFPJO2ZOSIg4XOUIZo","created_at":1742198766,"expires":1742202366,"secret":"epk_db9da1a985644cd08c4bcb3bb152ebd1"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1742192403/pay_yzSbFQNh8oJoa6cSkxQM?locale=en","secure_link":null,"payment_link_id":"plink_h1btlpLkVr0030VJXs1g"},"profile_id":"pro_qukvQ1whBBb6pdKnzvvN","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-03-18T11:52:46.283Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-03-17T08:06:06.355Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null} </details> 3. Update the payment link in above HTML template ##### Things to test [expected behavior in both the cases - payment link should redirect to the link mentioned in HTML template] - Make a redirection payment, and come back to the iframe - Wait for payment link to be expired, and come back to the iframe
[ "crates/api_models/src/payments.rs", "crates/router/src/core/payment_link.rs", "crates/router/src/core/payment_link/payment_link_initiate/payment_link.js", "crates/router/src/core/payment_link/payment_link_status/status.css", "crates/router/src/core/payment_link/payment_link_status/status.html", "crates/router/src/core/payment_link/payment_link_status/status.js" ]
juspay/hyperswitch
juspay__hyperswitch-7467
Bug: [FEATURE] scheme error code and messages in /payments API response ### Feature Description If the payment is declined for a card transaction, the card scheme or issuer can send a raw response explaining why. These are the raw acquirer responses which helps in understanding why a card transaction was declined. Some connectors like Adyen supports this - [reference](https://docs.adyen.com/development-resources/raw-acquirer-responses/#search-modal). HyperSwitch today sends back `error_code` and `error_message` in the payments API response which are connector's error code and messages. Payments API response has to be extended to send back issuer specific error codes and messages. ### Possible Implementation Issuer's error code and messages are received in payments API response or through webhooks. Considering this, below steps are to be followed 1. Ensure issuer's error code and messages are sent back from connector integration to core layer in `ErrorResponse` 2. Ensure this is handled in `IncomingWebhook` flows 3. Ensure this is stored in `payment_attempt` table 4. Ensure this is sent back in payments response ##### Changes required 1. Add below fields in `payment_attempt` table - `issuer_error_code` - `issuer_error_message` 2. Add below fields to payments API response - `issuer_error_code` - `issuer_error_message` This maintains the existing naming convention. Today, HyperSwitch has - - `error_code` and `unified_code` - `error_message` and `unified_message` ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index d93208fb665..081ec577185 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -7633,6 +7633,7 @@ "globepay", "gocardless", "gpayments", + "hipay", "helcim", "inespay", "iatapay", @@ -8720,6 +8721,14 @@ } ], "nullable": true + }, + "network_tokenization": { + "allOf": [ + { + "$ref": "#/components/schemas/NetworkTokenResponse" + } + ], + "nullable": true } } }, @@ -11583,6 +11592,14 @@ "type": "object", "description": "Metadata is useful for storing additional, unstructured information about the merchant account.", "nullable": true + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } }, "additionalProperties": false @@ -11717,6 +11734,14 @@ }, "recon_status": { "$ref": "#/components/schemas/ReconStatus" + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } } }, @@ -15350,6 +15375,14 @@ }, "description": "The connector token details if available", "nullable": true + }, + "network_token": { + "allOf": [ + { + "$ref": "#/components/schemas/NetworkTokenResponse" + } + ], + "nullable": true } } }, @@ -15883,7 +15916,8 @@ "active_attempt_payment_connector_id", "billing_connector_payment_details", "payment_method_type", - "payment_method_subtype" + "payment_method_subtype", + "connector" ], "properties": { "total_retry_count": { @@ -15914,6 +15948,9 @@ }, "payment_method_subtype": { "$ref": "#/components/schemas/PaymentMethodType" + }, + "connector": { + "$ref": "#/components/schemas/Connector" } } }, @@ -20300,6 +20337,7 @@ "globalpay", "globepay", "gocardless", + "hipay", "helcim", "iatapay", "inespay", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 651b0096566..2e21de61083 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5036,6 +5036,12 @@ pub struct PaymentsResponse { /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, + + /// Error code received from the issuer in case of failed payments + pub issuer_error_code: Option<String>, + + /// Error message received from the issuer in case of failed payments + pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index ad09c333ea7..ece1edb72bd 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -210,6 +210,10 @@ pub struct RefundResponse { /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>,)] pub split_refunds: Option<common_types::refunds::SplitRefund>, + /// Error code received from the issuer in case of failed refunds + pub issuer_error_code: Option<String>, + /// Error message received from the issuer in case of failed refunds + pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 7409b722653..8fb4afeb8ed 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -187,6 +187,8 @@ pub struct PaymentAttempt { pub processor_transaction_data: Option<String>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] @@ -547,6 +549,8 @@ pub enum PaymentAttemptUpdate { connector_transaction_id: Option<String>, payment_method_data: Option<serde_json::Value>, authentication_type: Option<storage_enums::AuthenticationType>, + issuer_error_code: Option<String>, + issuer_error_message: Option<String>, }, CaptureUpdate { amount_to_capture: Option<MinorUnit>, @@ -898,6 +902,8 @@ pub struct PaymentAttemptUpdateInternal { pub processor_transaction_data: Option<String>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] @@ -1082,6 +1088,8 @@ impl PaymentAttemptUpdate { connector_mandate_detail, card_discovery, charges, + issuer_error_code, + issuer_error_message, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); PaymentAttempt { amount: amount.unwrap_or(source.amount), @@ -1141,6 +1149,8 @@ impl PaymentAttemptUpdate { connector_mandate_detail: connector_mandate_detail.or(source.connector_mandate_detail), card_discovery: card_discovery.or(source.card_discovery), charges: charges.or(source.charges), + issuer_error_code: issuer_error_code.or(source.issuer_error_code), + issuer_error_message: issuer_error_message.or(source.issuer_error_message), ..source } } @@ -2194,6 +2204,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type, @@ -2251,6 +2263,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ConfirmUpdate { amount, @@ -2340,6 +2354,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail, card_discovery, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::VoidUpdate { status, @@ -2398,6 +2414,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::RejectUpdate { status, @@ -2457,6 +2475,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::BlocklistUpdate { status, @@ -2516,6 +2536,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ConnectorMandateDetailUpdate { connector_mandate_detail, @@ -2573,6 +2595,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, @@ -2630,6 +2654,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ResponseUpdate { status, @@ -2712,6 +2738,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::ErrorUpdate { @@ -2727,6 +2755,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, payment_method_data, authentication_type, + issuer_error_code, + issuer_error_message, } => { let (connector_transaction_id, processor_transaction_data) = connector_transaction_id @@ -2748,6 +2778,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { payment_method_data, authentication_type, processor_transaction_data, + issuer_error_code, + issuer_error_message, amount: None, net_amount: None, currency: None, @@ -2841,6 +2873,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::UpdateTrackers { payment_token, @@ -2904,6 +2938,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::UnresolvedResponseUpdate { status, @@ -2974,6 +3010,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::PreprocessingUpdate { @@ -3043,6 +3081,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::CaptureUpdate { @@ -3102,6 +3142,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::AmountToCaptureUpdate { status, @@ -3160,6 +3202,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ConnectorResponse { authentication_data, @@ -3227,6 +3271,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { @@ -3285,6 +3331,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::AuthenticationUpdate { status, @@ -3345,6 +3393,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ManualUpdate { status, @@ -3414,6 +3464,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::PostSessionTokensUpdate { @@ -3472,6 +3524,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, } } diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index f19c3252c60..ee598bebd2f 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -60,6 +60,8 @@ pub struct Refund { pub unified_message: Option<String>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } #[derive( @@ -140,6 +142,8 @@ pub enum RefundUpdate { processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, + issuer_error_code: Option<String>, + issuer_error_message: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, @@ -165,6 +169,8 @@ pub struct RefundUpdateInternal { processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, + issuer_error_code: Option<String>, + issuer_error_message: Option<String>, } impl RefundUpdateInternal { @@ -213,6 +219,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }, RefundUpdate::MetadataAndReasonUpdate { metadata, @@ -232,6 +240,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }, RefundUpdate::StatusUpdate { connector_refund_id, @@ -253,6 +263,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }, RefundUpdate::ErrorUpdate { refund_status, @@ -263,6 +275,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { updated_by, connector_refund_id, processor_refund_data, + issuer_error_code, + issuer_error_message, } => Self { refund_status, refund_error_message, @@ -277,6 +291,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { modified_at: common_utils::date_time::now(), unified_code, unified_message, + issuer_error_code, + issuer_error_message, }, RefundUpdate::ManualUpdate { refund_status, @@ -297,6 +313,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }, } } @@ -318,6 +336,8 @@ impl RefundUpdate { processor_refund_data, unified_code, unified_message, + issuer_error_code, + issuer_error_message, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), @@ -333,6 +353,8 @@ impl RefundUpdate { 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), + issuer_error_code: issuer_error_code.or(source.issuer_error_code), + issuer_error_message: issuer_error_message.or(source.issuer_error_message), ..source } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index ae01a54bd43..4e2ba4811b1 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -922,6 +922,9 @@ diesel::table! { processor_transaction_data -> Nullable<Text>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, + #[max_length = 64] + issuer_error_code -> Nullable<Varchar>, + issuer_error_message -> Nullable<Text>, } } @@ -1276,6 +1279,9 @@ diesel::table! { unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, + #[max_length = 64] + issuer_error_code -> Nullable<Varchar>, + issuer_error_message -> Nullable<Text>, } } diff --git a/crates/hyperswitch_connectors/src/connectors/aci.rs b/crates/hyperswitch_connectors/src/connectors/aci.rs index f4fce668ee0..8219105ed2f 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci.rs @@ -121,6 +121,8 @@ impl ConnectorCommon for Aci { }), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index 1e57cbbcf65..8e0694336b5 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Adyen { reason: Some(response.message), attempt_status: None, connector_transaction_id: response.psp_reference, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -988,6 +990,8 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp status_code: res.status_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(response.psp_reference), + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 13a29f16a0d..793a33e1fc1 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -144,6 +144,8 @@ pub struct AdditionalData { #[cfg(feature = "payouts")] payout_eligible: Option<PayoutEligibility>, funds_availability: Option<String>, + refusal_reason_raw: Option<String>, + refusal_code_raw: Option<String>, } #[serde_with::skip_serializing_none] @@ -444,6 +446,10 @@ pub struct AdyenWebhookResponse { refusal_reason: Option<String>, refusal_reason_code: Option<String>, event_code: WebhookEventCode, + // Raw acquirer refusal code + refusal_code_raw: Option<String>, + // Raw acquirer refusal reason + refusal_reason_raw: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -453,6 +459,7 @@ pub struct RedirectionErrorResponse { refusal_reason: Option<String>, psp_reference: Option<String>, merchant_reference: Option<String>, + additional_data: Option<AdditionalData>, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -466,6 +473,7 @@ pub struct RedirectionResponse { merchant_reference: Option<String>, store: Option<String>, splits: Option<Vec<AdyenSplitData>>, + additional_data: Option<AdditionalData>, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -3461,6 +3469,14 @@ pub fn get_adyen_response( status_code, attempt_status: None, connector_transaction_id: Some(response.psp_reference.clone()), + issuer_error_code: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_code_raw.clone()), + issuer_error_message: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_reason_raw.clone()), }) } else { None @@ -3533,6 +3549,8 @@ pub fn get_webhook_response( status_code, attempt_status: None, connector_transaction_id: Some(response.transaction_id.clone()), + issuer_error_code: response.refusal_code_raw.clone(), + issuer_error_message: response.refusal_reason_raw.clone(), }) } else { None @@ -3598,6 +3616,14 @@ pub fn get_redirection_response( status_code, attempt_status: None, connector_transaction_id: response.psp_reference.clone(), + issuer_error_code: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_code_raw.clone()), + issuer_error_message: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_reason_raw.clone()), }) } else { None @@ -3674,6 +3700,8 @@ pub fn get_present_to_shopper_response( status_code, attempt_status: None, connector_transaction_id: response.psp_reference.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -3739,6 +3767,8 @@ pub fn get_qr_code_response( status_code, attempt_status: None, connector_transaction_id: response.psp_reference.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -3796,6 +3826,14 @@ pub fn get_redirection_error_response( status_code, attempt_status: None, connector_transaction_id: response.psp_reference.clone(), + issuer_error_code: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_code_raw.clone()), + issuer_error_message: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_reason_raw.clone()), }); // We don't get connector transaction id for redirections in Adyen. let payments_response_data = PaymentsResponseData::TransactionResponse { @@ -4307,6 +4345,10 @@ pub struct AdyenAdditionalDataWH { #[serde(rename = "recurring.recurringDetailReference")] pub recurring_detail_reference: Option<Secret<String>>, pub network_tx_reference: Option<Secret<String>>, + /// [only for cards] Enable raw acquirer from Adyen dashboard to receive this (https://docs.adyen.com/development-resources/raw-acquirer-responses/#search-modal) + pub refusal_reason_raw: Option<String>, + /// [only for cards] This is only available for Visa and Mastercard + pub refusal_code_raw: Option<String>, } #[derive(Debug, Deserialize)] @@ -4592,6 +4634,8 @@ impl From<AdyenNotificationRequestItemWH> for AdyenWebhookResponse { refusal_reason, refusal_reason_code, event_code: notif.event_code, + refusal_code_raw: notif.additional_data.refusal_code_raw, + refusal_reason_raw: notif.additional_data.refusal_reason_raw, } } } @@ -5307,6 +5351,8 @@ impl ForeignTryFrom<(&Self, AdyenDisputeResponse)> for AcceptDisputeRouterData { )?, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) @@ -5345,6 +5391,8 @@ impl ForeignTryFrom<(&Self, AdyenDisputeResponse)> for SubmitEvidenceRouterData )?, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) @@ -5385,6 +5433,8 @@ impl ForeignTryFrom<(&Self, AdyenDisputeResponse)> for DefendDisputeRouterData { )?, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) diff --git a/crates/hyperswitch_connectors/src/connectors/airwallex.rs b/crates/hyperswitch_connectors/src/connectors/airwallex.rs index f37bef83026..c7482236264 100644 --- a/crates/hyperswitch_connectors/src/connectors/airwallex.rs +++ b/crates/hyperswitch_connectors/src/connectors/airwallex.rs @@ -122,6 +122,8 @@ impl ConnectorCommon for Airwallex { reason: response.source, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/amazonpay.rs b/crates/hyperswitch_connectors/src/connectors/amazonpay.rs index f8959541574..d383bb59b74 100644 --- a/crates/hyperswitch_connectors/src/connectors/amazonpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/amazonpay.rs @@ -145,6 +145,8 @@ impl ConnectorCommon for Amazonpay { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs index 3bd39fd38b5..de72dbe2aeb 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs @@ -1000,6 +1000,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) }) .unwrap_or_else(|| ErrorResponse { @@ -1009,6 +1011,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, })), Some(authorizedotnet::TransactionResponse::AuthorizedotnetTransactionResponseError(_)) | None => { @@ -1025,6 +1029,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index d7f50aa7405..6481d41748c 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -551,6 +551,8 @@ impl<F, T> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }); Ok(Self { response, @@ -1219,6 +1221,8 @@ impl<F, T> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(transaction_response.transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) }); let metadata = transaction_response @@ -1310,6 +1314,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetVoidResponse, T, Payment status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(transaction_response.transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) }); let metadata = transaction_response @@ -1458,6 +1464,8 @@ impl<F> TryFrom<RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(transaction_response.transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) }); @@ -1735,6 +1743,8 @@ fn get_err_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } diff --git a/crates/hyperswitch_connectors/src/connectors/bambora.rs b/crates/hyperswitch_connectors/src/connectors/bambora.rs index c4a9edea65c..1bf524392d7 100644 --- a/crates/hyperswitch_connectors/src/connectors/bambora.rs +++ b/crates/hyperswitch_connectors/src/connectors/bambora.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Bambora { reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs b/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs index f7453495077..fb9c0799124 100644 --- a/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs +++ b/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs @@ -163,6 +163,8 @@ impl ConnectorCommon for Bamboraapac { reason: response_data.declined_message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { diff --git a/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs index 5996ba05834..525b0456cec 100644 --- a/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs @@ -346,6 +346,8 @@ impl<F> reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -501,6 +503,8 @@ impl<F> reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -663,6 +667,8 @@ impl<F> reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -944,6 +950,8 @@ impl<F> reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs index 36d12fe3fc5..c1cc1b644a7 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs @@ -276,6 +276,8 @@ impl ConnectorCommon for Bankofamerica { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } transformers::BankOfAmericaErrorResponse::AuthenticationError(response) => { @@ -286,6 +288,8 @@ impl ConnectorCommon for Bankofamerica { reason: Some(response.response.rmsg), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -434,6 +438,8 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -556,6 +562,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -746,6 +754,8 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -867,6 +877,8 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Ba .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs index 9804f6c4e6c..4b40e36a7a6 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs @@ -1445,6 +1445,8 @@ fn map_error_response<F, T>( status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }); match transaction_status { @@ -1486,10 +1488,10 @@ fn get_payment_response( enums::AttemptStatus, u16, ), -) -> Result<PaymentsResponseData, ErrorResponse> { +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { - Some(error) => Err(error), + Some(error) => Err(Box::new(error)), None => { let mandate_reference = info_response @@ -1549,7 +1551,8 @@ impl<F> info_response.status.clone(), item.data.request.is_auto_capture()?, )); - let response = get_payment_response((&info_response, status, item.http_code)); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); let connector_response = match item.data.payment_method { common_enums::PaymentMethod::Card => info_response .processor_information @@ -1648,7 +1651,8 @@ impl<F> match item.response { BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { let status = map_boa_attempt_status((info_response.status.clone(), true)); - let response = get_payment_response((&info_response, status, item.http_code)); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); Ok(Self { status, response, @@ -1684,7 +1688,8 @@ impl<F> match item.response { BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { let status = map_boa_attempt_status((info_response.status.clone(), false)); - let response = get_payment_response((&info_response, status, item.http_code)); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); Ok(Self { status, response, @@ -2244,6 +2249,8 @@ fn get_error_response( status_code, attempt_status, connector_transaction_id: Some(transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } @@ -2521,6 +2528,8 @@ fn convert_to_error_response_from_error_info( status_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/billwerk.rs b/crates/hyperswitch_connectors/src/connectors/billwerk.rs index b5ddef00358..34bf83a7bd5 100644 --- a/crates/hyperswitch_connectors/src/connectors/billwerk.rs +++ b/crates/hyperswitch_connectors/src/connectors/billwerk.rs @@ -154,6 +154,8 @@ impl ConnectorCommon for Billwerk { reason: Some(response.error), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs index 9fe00bac046..e6499306d0f 100644 --- a/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs @@ -279,6 +279,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsRe status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.handle.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None diff --git a/crates/hyperswitch_connectors/src/connectors/bitpay.rs b/crates/hyperswitch_connectors/src/connectors/bitpay.rs index 4de2f422b94..992196c61d3 100644 --- a/crates/hyperswitch_connectors/src/connectors/bitpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/bitpay.rs @@ -153,6 +153,8 @@ impl ConnectorCommon for Bitpay { reason: response.message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs index 29b0611c979..23720360294 100644 --- a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs +++ b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs @@ -168,6 +168,8 @@ impl ConnectorCommon for Bluesnap { reason: Some(reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } bluesnap::BluesnapErrors::Auth(error_res) => ErrorResponse { @@ -177,6 +179,8 @@ impl ConnectorCommon for Bluesnap { reason: Some(error_res.error_description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }, bluesnap::BluesnapErrors::General(error_response) => { let (error_res, attempt_status) = if res.status_code == 403 @@ -199,6 +203,8 @@ impl ConnectorCommon for Bluesnap { reason: Some(error_res), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } }; diff --git a/crates/hyperswitch_connectors/src/connectors/boku.rs b/crates/hyperswitch_connectors/src/connectors/boku.rs index 68195979874..330e7b5ab45 100644 --- a/crates/hyperswitch_connectors/src/connectors/boku.rs +++ b/crates/hyperswitch_connectors/src/connectors/boku.rs @@ -163,6 +163,8 @@ impl ConnectorCommon for Boku { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(_) => get_xml_deserialized(res, event_builder), @@ -705,6 +707,8 @@ fn get_xml_deserialized( reason: Some(response_data), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/braintree.rs b/crates/hyperswitch_connectors/src/connectors/braintree.rs index e965e964293..67c54759152 100644 --- a/crates/hyperswitch_connectors/src/connectors/braintree.rs +++ b/crates/hyperswitch_connectors/src/connectors/braintree.rs @@ -169,6 +169,8 @@ impl ConnectorCommon for Braintree { reason: Some(response.api_error_response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(braintree::ErrorResponses::BraintreeErrorResponse(response)) => { @@ -182,6 +184,8 @@ impl ConnectorCommon for Braintree { reason: Some(response.errors), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { diff --git a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs index 2a5fabb7788..dfde2e0a26d 100644 --- a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs @@ -447,7 +447,8 @@ impl<F> ) -> Result<Self, Self::Error> { match item.response { BraintreeAuthResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeAuthResponse::AuthResponse(auth_response) => { @@ -461,6 +462,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -513,7 +516,7 @@ impl<F> fn build_error_response<T>( response: &[ErrorDetails], http_code: u16, -) -> Result<T, hyperswitch_domain_models::router_data::ErrorResponse> { +) -> Result<T, Box<hyperswitch_domain_models::router_data::ErrorResponse>> { let error_messages = response .iter() .map(|error| error.message.to_string()) @@ -542,15 +545,19 @@ fn get_error_response<T>( error_msg: Option<String>, error_reason: Option<String>, http_code: u16, -) -> Result<T, hyperswitch_domain_models::router_data::ErrorResponse> { - Err(hyperswitch_domain_models::router_data::ErrorResponse { - code: error_code.unwrap_or_else(|| NO_ERROR_CODE.to_string()), - message: error_msg.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), - reason: error_reason, - status_code: http_code, - attempt_status: None, - connector_transaction_id: None, - }) +) -> Result<T, Box<hyperswitch_domain_models::router_data::ErrorResponse>> { + Err(Box::new( + hyperswitch_domain_models::router_data::ErrorResponse { + code: error_code.unwrap_or_else(|| NO_ERROR_CODE.to_string()), + message: error_msg.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), + reason: error_reason, + status_code: http_code, + attempt_status: None, + connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, + }, + )) } #[derive(Debug, Clone, Deserialize, Serialize, strum::Display)] @@ -624,7 +631,8 @@ impl<F> ) -> Result<Self, Self::Error> { match item.response { BraintreePaymentsResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors.clone(), item.http_code), + response: build_error_response(&error_response.errors.clone(), item.http_code) + .map_err(|err| *err), ..item.data }), BraintreePaymentsResponse::PaymentsResponse(payment_response) => { @@ -638,6 +646,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -708,7 +718,8 @@ impl<F> ) -> Result<Self, Self::Error> { match item.response { BraintreeCompleteChargeResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors.clone(), item.http_code), + response: build_error_response(&error_response.errors.clone(), item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeCompleteChargeResponse::PaymentsResponse(payment_response) => { @@ -722,6 +733,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -773,7 +786,8 @@ impl<F> ) -> Result<Self, Self::Error> { match item.response { BraintreeCompleteAuthResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeCompleteAuthResponse::AuthResponse(auth_response) => { @@ -787,6 +801,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -962,7 +978,7 @@ impl TryFrom<RefundsResponseRouterData<Execute, BraintreeRefundResponse>> Ok(Self { response: match item.response { BraintreeRefundResponse::ErrorResponse(error_response) => { - build_error_response(&error_response.errors, item.http_code) + build_error_response(&error_response.errors, item.http_code).map_err(|err| *err) } BraintreeRefundResponse::SuccessResponse(refund_data) => { let refund_data = refund_data.data.refund_transaction.refund; @@ -975,6 +991,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, BraintreeRefundResponse>> attempt_status: None, connector_transaction_id: Some(refund_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { @@ -1079,7 +1097,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, BraintreeRSyncResponse>> ) -> Result<Self, Self::Error> { match item.response { BraintreeRSyncResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeRSyncResponse::RSyncResponse(rsync_response) => { @@ -1241,6 +1260,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreeTokenResponse, T, PaymentsResp response: match item.response { BraintreeTokenResponse::ErrorResponse(error_response) => { build_error_response(error_response.errors.as_ref(), item.http_code) + .map_err(|err| *err) } BraintreeTokenResponse::TokenResponse(token_response) => { @@ -1332,6 +1352,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -1352,7 +1374,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>> }) } BraintreeCaptureResponse::ErrorResponse(error_data) => Ok(Self { - response: build_error_response(&error_data.errors, item.http_code), + response: build_error_response(&error_data.errors, item.http_code) + .map_err(|err| *err), ..item.data }), } @@ -1417,6 +1440,7 @@ impl<F> response: match item.response { BraintreeRevokeMandateResponse::ErrorResponse(error_response) => { build_error_response(error_response.errors.as_ref(), item.http_code) + .map_err(|err| *err) } BraintreeRevokeMandateResponse::RevokeMandateResponse(..) => { Ok(MandateRevokeResponseData { @@ -1515,7 +1539,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreeCancelResponse, T, PaymentsRes ) -> Result<Self, Self::Error> { match item.response { BraintreeCancelResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeCancelResponse::CancelResponse(void_response) => { @@ -1529,6 +1554,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreeCancelResponse, T, PaymentsRes attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -1611,7 +1638,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreePSyncResponse, T, PaymentsResp ) -> Result<Self, Self::Error> { match item.response { BraintreePSyncResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreePSyncResponse::SuccessResponse(psync_response) => { @@ -1631,6 +1659,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreePSyncResponse, T, PaymentsResp attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs index a2a8cf9df65..edd6e54e0ce 100644 --- a/crates/hyperswitch_connectors/src/connectors/cashtocode.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs @@ -146,6 +146,8 @@ impl ConnectorCommon for Cashtocode { reason: Some(response.error_description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs index 209092c6b6f..684099deb05 100644 --- a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs @@ -253,6 +253,8 @@ impl<F> reason: Some(error_data.error_description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ), CashtocodePaymentsResponse::CashtoCodeData(response_data) => { diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index 73eeabe4356..bde9a165b21 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Chargebee { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/checkout.rs b/crates/hyperswitch_connectors/src/connectors/checkout.rs index 61977098476..4d151c12159 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout.rs @@ -179,6 +179,8 @@ impl ConnectorCommon for Checkout { .or(response.error_type), attempt_status: None, connector_transaction_id: response.request_id, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs index 4630f00b1d5..d364e327504 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs @@ -705,6 +705,8 @@ impl TryFrom<PaymentsResponseRouterData<PaymentsResponse>> for PaymentsAuthorize reason: item.response.response_summary, attempt_status: None, connector_transaction_id: Some(item.response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -757,6 +759,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponse>> for PaymentsSyncR reason: item.response.response_summary, attempt_status: None, connector_transaction_id: Some(item.response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None diff --git a/crates/hyperswitch_connectors/src/connectors/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs index cfdac514847..9e998abebbc 100644 --- a/crates/hyperswitch_connectors/src/connectors/coinbase.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs @@ -135,6 +135,8 @@ impl ConnectorCommon for Coinbase { reason: response.error.code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/coingate.rs b/crates/hyperswitch_connectors/src/connectors/coingate.rs index 81bb9116950..e426dcb2384 100644 --- a/crates/hyperswitch_connectors/src/connectors/coingate.rs +++ b/crates/hyperswitch_connectors/src/connectors/coingate.rs @@ -142,6 +142,8 @@ impl ConnectorCommon for Coingate { reason: Some(response.reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs index 2650d8f1e91..4c24018fcbc 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs @@ -193,6 +193,8 @@ impl ConnectorCommon for Cryptopay { reason: response.error.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index 98d3dd76cdd..67a67c8878d 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -175,6 +175,8 @@ impl<F, T> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(payment_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { let redirection_data = item diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs index 812d0391dec..8b5e748906f 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs @@ -239,6 +239,8 @@ impl ConnectorCommon for Cybersource { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(transformers::CybersourceErrorResponse::AuthenticationError(response)) => { @@ -251,6 +253,8 @@ impl ConnectorCommon for Cybersource { reason: Some(response.response.rmsg), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(transformers::CybersourceErrorResponse::NotAvailableError(response)) => { @@ -275,6 +279,8 @@ impl ConnectorCommon for Cybersource { reason: Some(error_response), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { @@ -506,6 +512,8 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -586,6 +594,8 @@ impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevoke status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) @@ -823,6 +833,8 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1058,6 +1070,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1172,6 +1186,8 @@ impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Cyber .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1294,6 +1310,8 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1415,6 +1433,8 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cy .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index ea5d9b25f84..2a0ebdc9f79 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -2679,10 +2679,10 @@ fn get_error_response_if_failure( fn get_payment_response( (info_response, status, http_code): (&CybersourcePaymentsResponse, enums::AttemptStatus, u16), -) -> Result<PaymentsResponseData, ErrorResponse> { +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { - Some(error) => Err(error), + Some(error) => Err(Box::new(error)), None => { let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); @@ -2747,7 +2747,8 @@ impl .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information @@ -2845,6 +2846,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }), status: enums::AttemptStatus::AuthenticationFailed, ..item.data @@ -3255,6 +3258,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }); Ok(Self { response, @@ -3292,7 +3297,8 @@ impl<F> .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information @@ -3348,7 +3354,8 @@ impl<F> .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), true, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, @@ -3383,7 +3390,8 @@ impl<F> .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), false, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, @@ -4131,6 +4139,8 @@ pub fn get_error_response( status_code, attempt_status, connector_transaction_id: Some(transaction_id), + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/datatrans.rs b/crates/hyperswitch_connectors/src/connectors/datatrans.rs index f06d7be8693..0f82ae28d8f 100644 --- a/crates/hyperswitch_connectors/src/connectors/datatrans.rs +++ b/crates/hyperswitch_connectors/src/connectors/datatrans.rs @@ -153,6 +153,8 @@ impl ConnectorCommon for Datatrans { reason: Some(response), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { let response: datatrans::DatatransErrorResponse = res @@ -168,6 +170,8 @@ impl ConnectorCommon for Datatrans { reason: Some(response.error.message.clone()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs index 9297f783d3e..8299b0387ae 100644 --- a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs @@ -560,6 +560,8 @@ impl<F> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), DatatransResponse::TransactionResponse(response) => { Ok(PaymentsResponseData::TransactionResponse { @@ -629,6 +631,8 @@ impl<F> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), DatatransResponse::TransactionResponse(response) => { Ok(PaymentsResponseData::TransactionResponse { @@ -704,6 +708,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, DatatransRefundsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -733,6 +739,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, DatatransSyncResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), DatatransSyncResponse::Response(response) => Ok(RefundsResponseData { connector_refund_id: response.transaction_id.to_string(), @@ -762,6 +770,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }); Ok(Self { response, @@ -785,6 +795,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { let mandate_reference = sync_response diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs index b481c3e808d..0972eb63b9e 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs @@ -174,6 +174,8 @@ impl ConnectorCommon for Deutschebank { reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -304,6 +306,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), deutschebank::DeutschebankError::AccessTokenErrorResponse(response) => { Ok(ErrorResponse { @@ -313,6 +317,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: Some(response.description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs index bf8a7fc9528..bee5d8662e1 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -444,7 +444,8 @@ impl reason: Some("METHOD_REQUIRED Flow is not currently supported for deutschebank 3ds payments".to_owned()), status_code: item.http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: None,issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -514,6 +515,8 @@ fn get_error_response(error_code: String, error_reason: String, status_code: u16 status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs b/crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs index a58a086f5e7..55294d6a588 100644 --- a/crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs +++ b/crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs @@ -161,6 +161,8 @@ impl ConnectorCommon for Digitalvirgo { reason: response.description, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal.rs b/crates/hyperswitch_connectors/src/connectors/dlocal.rs index 60813a4ea08..965575bbe17 100644 --- a/crates/hyperswitch_connectors/src/connectors/dlocal.rs +++ b/crates/hyperswitch_connectors/src/connectors/dlocal.rs @@ -152,6 +152,8 @@ impl ConnectorCommon for Dlocal { reason: response.param, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs index a11c608d69f..861ff22e60f 100644 --- a/crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs @@ -214,6 +214,8 @@ impl<F> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ElavonPaymentsResponse::Success(response) => { if status == enums::AttemptStatus::Failure { @@ -224,6 +226,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(response.ssl_txn_id.clone()), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -428,6 +432,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<ElavonPaymentsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ElavonPaymentsResponse::Success(response) => { if status == enums::AttemptStatus::Failure { @@ -438,6 +444,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<ElavonPaymentsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -478,6 +486,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, ElavonPaymentsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ElavonPaymentsResponse::Success(response) => { if status == enums::RefundStatus::Failure { @@ -488,6 +498,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, ElavonPaymentsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv.rs b/crates/hyperswitch_connectors/src/connectors/fiserv.rs index 50eebb99518..14374a8e18a 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiserv.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiserv.rs @@ -178,6 +178,8 @@ impl ConnectorCommon for Fiserv { status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) }) .unwrap_or(ErrorResponse { @@ -187,6 +189,8 @@ impl ConnectorCommon for Fiserv { status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, })) } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs index b124949c078..d129ed69554 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs @@ -236,6 +236,8 @@ impl ConnectorCommon for Fiservemea { }, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } None => Ok(ErrorResponse { @@ -248,6 +250,8 @@ impl ConnectorCommon for Fiservemea { reason: response.response_type, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu.rs b/crates/hyperswitch_connectors/src/connectors/fiuu.rs index 7e9bb8c120c..4069d6af8f9 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu.rs @@ -235,6 +235,8 @@ impl ConnectorCommon for Fiuu { reason: Some(response.error_desc.clone()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index 8b1296a0159..181574b54bb 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -828,6 +828,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -898,6 +900,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(data.txn_id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -944,6 +948,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: recurring_response.tran_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -1077,6 +1083,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, FiuuRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -1101,6 +1109,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, FiuuRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(refund_data.refund_id.to_string()), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -1240,6 +1250,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy reason: response.error_desc, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(txn_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1305,6 +1317,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy reason: response.error_desc.clone(), attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(txn_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1474,6 +1488,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> ), attempt_status: None, connector_transaction_id: Some(item.response.tran_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1587,6 +1603,8 @@ impl TryFrom<PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>> ), attempt_status: None, connector_transaction_id: Some(item.response.tran_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1682,6 +1700,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, FiuuRefundSyncResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), diff --git a/crates/hyperswitch_connectors/src/connectors/forte.rs b/crates/hyperswitch_connectors/src/connectors/forte.rs index 1068922faa7..2356fae53c3 100644 --- a/crates/hyperswitch_connectors/src/connectors/forte.rs +++ b/crates/hyperswitch_connectors/src/connectors/forte.rs @@ -165,6 +165,8 @@ impl ConnectorCommon for Forte { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/getnet.rs b/crates/hyperswitch_connectors/src/connectors/getnet.rs index 557dfbeaca3..0f0ee9e32c3 100644 --- a/crates/hyperswitch_connectors/src/connectors/getnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/getnet.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Getnet { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay.rs b/crates/hyperswitch_connectors/src/connectors/globalpay.rs index 6d233bcfc33..641e9fd5f3d 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay.rs @@ -148,6 +148,8 @@ impl ConnectorCommon for Globalpay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -376,6 +378,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs index 27ff359a7ad..57cf5d0f287 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs @@ -268,7 +268,7 @@ fn get_payment_response( status: common_enums::AttemptStatus, response: GlobalpayPaymentsResponse, redirection_data: Option<RedirectForm>, -) -> Result<PaymentsResponseData, ErrorResponse> { +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let mandate_reference = response.payment_method.as_ref().and_then(|pm| { pm.card .as_ref() @@ -281,13 +281,13 @@ fn get_payment_response( }) }); match status { - common_enums::AttemptStatus::Failure => Err(ErrorResponse { + common_enums::AttemptStatus::Failure => Err(Box::new(ErrorResponse { message: response .payment_method .and_then(|pm| pm.message) .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), ..Default::default() - }), + })), _ => Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.id), redirection_data: Box::new(redirection_data), @@ -327,7 +327,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, GlobalpayPaymentsResponse, T, PaymentsR let redirection_data = redirect_url.map(|url| RedirectForm::from((url, Method::Get))); Ok(Self { status, - response: get_payment_response(status, item.response, redirection_data), + response: get_payment_response(status, item.response, redirection_data) + .map_err(|err| *err), ..item.data }) } diff --git a/crates/hyperswitch_connectors/src/connectors/globepay.rs b/crates/hyperswitch_connectors/src/connectors/globepay.rs index f11b7b5977f..cca5e99bccd 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay.rs @@ -154,6 +154,8 @@ impl ConnectorCommon for Globepay { reason: Some(response.return_msg), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs index a3c027cb5a2..89686f199ad 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs @@ -325,6 +325,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/gocardless.rs b/crates/hyperswitch_connectors/src/connectors/gocardless.rs index a953e01dce0..a36ffdd9e34 100644 --- a/crates/hyperswitch_connectors/src/connectors/gocardless.rs +++ b/crates/hyperswitch_connectors/src/connectors/gocardless.rs @@ -158,6 +158,8 @@ impl ConnectorCommon for Gocardless { reason: Some(error_reason.join("; ")), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/helcim.rs b/crates/hyperswitch_connectors/src/connectors/helcim.rs index 79b950063c3..65927bb0f35 100644 --- a/crates/hyperswitch_connectors/src/connectors/helcim.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim.rs @@ -181,6 +181,8 @@ impl ConnectorCommon for Helcim { reason: Some(error_string), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/hipay.rs b/crates/hyperswitch_connectors/src/connectors/hipay.rs index 1575e361a5b..be1a829efb3 100644 --- a/crates/hyperswitch_connectors/src/connectors/hipay.rs +++ b/crates/hyperswitch_connectors/src/connectors/hipay.rs @@ -244,6 +244,8 @@ impl ConnectorCommon for Hipay { reason: response.description, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs index cefa332bc8f..b121b0698cd 100644 --- a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs @@ -582,6 +582,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<HipaySyncResponse>> for PaymentsSync attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }); Ok(Self { status: enums::AttemptStatus::Failure, @@ -606,6 +608,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<HipaySyncResponse>> for PaymentsSync status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/iatapay.rs b/crates/hyperswitch_connectors/src/connectors/iatapay.rs index f9ab2f3159f..b5ea844fb2e 100644 --- a/crates/hyperswitch_connectors/src/connectors/iatapay.rs +++ b/crates/hyperswitch_connectors/src/connectors/iatapay.rs @@ -155,6 +155,8 @@ impl ConnectorCommon for Iatapay { reason: Some(CONNECTOR_UNAUTHORIZED_ERROR.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } else { let response: iatapay::IatapayErrorResponse = res @@ -171,6 +173,8 @@ impl ConnectorCommon for Iatapay { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } }; Ok(response_error_message) @@ -288,6 +292,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs index e41057fb8e6..0c5c9fc6786 100644 --- a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs @@ -343,6 +343,8 @@ fn get_iatpay_response( status_code, attempt_status: Some(status), connector_transaction_id: response.iata_payment_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -527,6 +529,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRout status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.iata_refund_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { @@ -563,6 +567,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouter status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.iata_refund_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/inespay.rs b/crates/hyperswitch_connectors/src/connectors/inespay.rs index 41ae798ade3..e0bd27d47b1 100644 --- a/crates/hyperswitch_connectors/src/connectors/inespay.rs +++ b/crates/hyperswitch_connectors/src/connectors/inespay.rs @@ -151,6 +151,8 @@ impl ConnectorCommon for Inespay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs index 3922929892e..508e91438ef 100644 --- a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs @@ -142,6 +142,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsRes attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ), }; @@ -267,6 +269,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, InespayPSyncResponse, T, PaymentsRespon attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -359,6 +363,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, InespayRefundsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -403,6 +409,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, InespayRSyncResponse>> for Refunds attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), }; Ok(Self { diff --git a/crates/hyperswitch_connectors/src/connectors/itaubank.rs b/crates/hyperswitch_connectors/src/connectors/itaubank.rs index 34956ace644..e31f86b0385 100644 --- a/crates/hyperswitch_connectors/src/connectors/itaubank.rs +++ b/crates/hyperswitch_connectors/src/connectors/itaubank.rs @@ -176,6 +176,8 @@ impl ConnectorCommon for Itaubank { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -296,6 +298,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: response.detail.or(response.user_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs b/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs index 9d6037877f2..68529f725a8 100644 --- a/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs +++ b/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs @@ -167,6 +167,8 @@ impl ConnectorCommon for Jpmorgan { reason: Some(response_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs b/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs index cbe7881c536..6dd867421a9 100644 --- a/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs +++ b/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs @@ -187,6 +187,8 @@ impl ConnectorCommon for Juspaythreedsserver { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index 86ad19d7dc2..50a830fdba2 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -126,6 +126,8 @@ impl ConnectorCommon for Klarna { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/mifinity.rs b/crates/hyperswitch_connectors/src/connectors/mifinity.rs index 3b597597e38..eaaa94b4290 100644 --- a/crates/hyperswitch_connectors/src/connectors/mifinity.rs +++ b/crates/hyperswitch_connectors/src/connectors/mifinity.rs @@ -154,6 +154,8 @@ impl ConnectorCommon for Mifinity { reason: Some(CONNECTOR_UNAUTHORIZED_ERROR.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { let response: Result< @@ -189,6 +191,8 @@ impl ConnectorCommon for Mifinity { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } diff --git a/crates/hyperswitch_connectors/src/connectors/mollie.rs b/crates/hyperswitch_connectors/src/connectors/mollie.rs index 325c031c33f..b043dbdd8cc 100644 --- a/crates/hyperswitch_connectors/src/connectors/mollie.rs +++ b/crates/hyperswitch_connectors/src/connectors/mollie.rs @@ -135,6 +135,8 @@ impl ConnectorCommon for Mollie { reason: response.field, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/moneris.rs b/crates/hyperswitch_connectors/src/connectors/moneris.rs index c8f542c1bad..3562a2e838e 100644 --- a/crates/hyperswitch_connectors/src/connectors/moneris.rs +++ b/crates/hyperswitch_connectors/src/connectors/moneris.rs @@ -174,6 +174,8 @@ impl ConnectorCommon for Moneris { reason: Some(reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -298,6 +300,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: response.error_description, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index 3e632e048a2..e11ac59e75f 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -1045,6 +1045,8 @@ pub fn populate_error_reason( status_code: http_code, attempt_status, connector_transaction_id, + issuer_error_code: None, + issuer_error_message: None, } } // REFUND : @@ -1150,6 +1152,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, MultisafepayRefundResponse>> status_code: item.http_code, attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets.rs b/crates/hyperswitch_connectors/src/connectors/nexinets.rs index f93eef65724..69a8543286d 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets.rs @@ -162,6 +162,8 @@ impl ConnectorCommon for Nexinets { reason: Some(connector_reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs index 8a9c804cbf2..264bca6b5a9 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs @@ -203,6 +203,8 @@ impl ConnectorCommon for Nexixpay { reason: concatenated_descriptions, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/nomupay.rs b/crates/hyperswitch_connectors/src/connectors/nomupay.rs index a6a5b0357e1..075b955be49 100644 --- a/crates/hyperswitch_connectors/src/connectors/nomupay.rs +++ b/crates/hyperswitch_connectors/src/connectors/nomupay.rs @@ -285,6 +285,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), (None, None, Some(nomupay_inner_error), _, _) => { match ( @@ -298,6 +300,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), (_, Some(validation_errors)) => Ok(ErrorResponse { status_code: res.status_code, @@ -314,6 +318,8 @@ impl ConnectorCommon for Nomupay { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), (None, None) => Ok(ErrorResponse { status_code: res.status_code, @@ -322,6 +328,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } @@ -335,6 +343,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), _ => Ok(ErrorResponse { status_code: res.status_code, @@ -343,6 +353,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } diff --git a/crates/hyperswitch_connectors/src/connectors/noon.rs b/crates/hyperswitch_connectors/src/connectors/noon.rs index c4f2eef275d..3f3de600063 100644 --- a/crates/hyperswitch_connectors/src/connectors/noon.rs +++ b/crates/hyperswitch_connectors/src/connectors/noon.rs @@ -178,6 +178,8 @@ impl ConnectorCommon for Noon { reason: Some(noon_error_response.message), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_message) => { diff --git a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs index b2128b990c1..81dc0186356 100644 --- a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs @@ -596,6 +596,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsRespon status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(order.id.to_string()), + issuer_error_code: None, + issuer_error_message: None, }), _ => { let connector_response_reference_id = @@ -826,6 +828,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRout reason: Some(response.message.clone()), attempt_status: None, connector_transaction_id: Some(response.result.transaction.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { @@ -892,6 +896,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for RefundsRo reason: Some(response.message.clone()), attempt_status: None, connector_transaction_id: Some(noon_transaction.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet.rs b/crates/hyperswitch_connectors/src/connectors/novalnet.rs index 0a47c8ccfba..a6f2e2fc643 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet.rs @@ -153,6 +153,8 @@ impl ConnectorCommon for Novalnet { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index 44f84bf475d..607acb37fb0 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -589,6 +589,8 @@ pub fn get_error_response(result: ResultData, status_code: u16) -> ErrorResponse status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 0bfd3af7e99..cbc4a244d8c 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -1543,17 +1543,14 @@ fn build_error_response<T>( http_code: u16, ) -> Option<Result<T, ErrorResponse>> { match response.status { - NuveiPaymentStatus::Error => Some(get_error_response( - response.err_code, - &response.reason, - http_code, - )), + NuveiPaymentStatus::Error => Some( + get_error_response(response.err_code, &response.reason, http_code).map_err(|err| *err), + ), _ => { - let err = Some(get_error_response( - response.gw_error_code, - &response.gw_error_reason, - http_code, - )); + let err = Some( + get_error_response(response.gw_error_code, &response.gw_error_reason, http_code) + .map_err(|err| *err), + ); match response.transaction_status { Some(NuveiTransactionStatus::Error) | Some(NuveiTransactionStatus::Declined) => err, _ => match response @@ -1709,7 +1706,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, NuveiPaymentsResponse>> item.response .transaction_id .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - ), + ) + .map_err(|err| *err), ..item.data }) } @@ -1729,7 +1727,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, NuveiPaymentsResponse>> item.response .transaction_id .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - ), + ) + .map_err(|err| *err), ..item.data }) } @@ -1783,7 +1782,7 @@ fn get_refund_response( response: NuveiPaymentsResponse, http_code: u16, txn_id: String, -) -> Result<RefundsResponseData, ErrorResponse> { +) -> Result<RefundsResponseData, Box<ErrorResponse>> { let refund_status = response .transaction_status .clone() @@ -1809,8 +1808,8 @@ fn get_error_response<T>( error_code: Option<i64>, error_msg: &Option<String>, http_code: u16, -) -> Result<T, ErrorResponse> { - Err(ErrorResponse { +) -> Result<T, Box<ErrorResponse>> { + Err(Box::new(ErrorResponse { code: error_code .map(|c| c.to_string()) .unwrap_or_else(|| NO_ERROR_CODE.to_string()), @@ -1821,7 +1820,9 @@ fn get_error_response<T>( status_code: http_code, attempt_status: None, connector_transaction_id: None, - }) + issuer_error_code: None, + issuer_error_message: None, + })) } #[derive(Debug, Default, Serialize, Deserialize)] diff --git a/crates/hyperswitch_connectors/src/connectors/opayo.rs b/crates/hyperswitch_connectors/src/connectors/opayo.rs index b2aadda37f7..eef0da72a2c 100644 --- a/crates/hyperswitch_connectors/src/connectors/opayo.rs +++ b/crates/hyperswitch_connectors/src/connectors/opayo.rs @@ -139,6 +139,8 @@ impl ConnectorCommon for Opayo { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/opennode.rs b/crates/hyperswitch_connectors/src/connectors/opennode.rs index fefd2f77768..56e30ac3426 100644 --- a/crates/hyperswitch_connectors/src/connectors/opennode.rs +++ b/crates/hyperswitch_connectors/src/connectors/opennode.rs @@ -135,6 +135,8 @@ impl ConnectorCommon for Opennode { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/paybox.rs b/crates/hyperswitch_connectors/src/connectors/paybox.rs index 395fc73808c..0c8577a29d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/paybox.rs +++ b/crates/hyperswitch_connectors/src/connectors/paybox.rs @@ -156,6 +156,8 @@ impl ConnectorCommon for Paybox { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs index ef4e308d968..7da6b6e95ea 100644 --- a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs @@ -715,6 +715,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayboxCaptureResponse, T, PaymentsRespo status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -773,6 +775,8 @@ impl<F> TryFrom<ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, Pay status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -802,6 +806,8 @@ impl<F> TryFrom<ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, Pay status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -845,6 +851,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayboxSyncResponse, T, PaymentsResponse status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -933,6 +941,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, PayboxSyncResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -964,6 +974,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, TransactionResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -1033,6 +1045,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), diff --git a/crates/hyperswitch_connectors/src/connectors/payeezy.rs b/crates/hyperswitch_connectors/src/connectors/payeezy.rs index 5621b9d1230..b6266d30d21 100644 --- a/crates/hyperswitch_connectors/src/connectors/payeezy.rs +++ b/crates/hyperswitch_connectors/src/connectors/payeezy.rs @@ -149,6 +149,8 @@ impl ConnectorCommon for Payeezy { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/payme.rs b/crates/hyperswitch_connectors/src/connectors/payme.rs index 9c1a94ad3c0..80dd60c172b 100644 --- a/crates/hyperswitch_connectors/src/connectors/payme.rs +++ b/crates/hyperswitch_connectors/src/connectors/payme.rs @@ -149,6 +149,8 @@ impl ConnectorCommon for Payme { )), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { diff --git a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs index 8dd83d1ebd7..180d22b2a75 100644 --- a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs @@ -232,6 +232,8 @@ fn get_pay_sale_error_response( status_code: http_code, attempt_status: None, connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } @@ -314,6 +316,8 @@ fn get_sale_query_error_response( status_code: http_code, attempt_status: None, connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } @@ -1033,6 +1037,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, PaymeRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: payme_response.payme_transaction_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { @@ -1104,6 +1110,8 @@ impl TryFrom<PaymentsCancelResponseRouterData<PaymeVoidResponse>> for PaymentsCa status_code: item.http_code, attempt_status: None, connector_transaction_id: payme_response.payme_transaction_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { // Since we are not receiving payme_sale_id, we are not populating the transaction response @@ -1158,6 +1166,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaymeQueryTransactionResponse, T, Refun status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(pay_sale_response.payme_transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs index 1859deeaad1..76283fad3a2 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs @@ -178,6 +178,8 @@ impl Paypal { reason: error_reason.or(Some(response.message)), attempt_status: None, connector_transaction_id: response.debug_id, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -350,6 +352,8 @@ impl ConnectorCommon for Paypal { reason, attempt_status: None, connector_transaction_id: response.debug_id, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -488,6 +492,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: Some(response.error_description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1235,6 +1241,8 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp .unwrap_or(paypal::AuthenticationStatus::Null), )), status_code: res.status_code, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }), diff --git a/crates/hyperswitch_connectors/src/connectors/paystack.rs b/crates/hyperswitch_connectors/src/connectors/paystack.rs index 6d6ce2ff83a..2f15b1541a5 100644 --- a/crates/hyperswitch_connectors/src/connectors/paystack.rs +++ b/crates/hyperswitch_connectors/src/connectors/paystack.rs @@ -143,6 +143,8 @@ impl ConnectorCommon for Paystack { reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs index 2ced7d44d54..4117f689cb6 100644 --- a/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs @@ -144,6 +144,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsRe attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ) } @@ -251,6 +253,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaystackPSyncResponse, T, PaymentsRespo attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -348,6 +352,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, PaystackRefundsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -388,6 +394,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, PaystackRefundsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/connectors/payu.rs b/crates/hyperswitch_connectors/src/connectors/payu.rs index cd8c99b6151..6d09c85d917 100644 --- a/crates/hyperswitch_connectors/src/connectors/payu.rs +++ b/crates/hyperswitch_connectors/src/connectors/payu.rs @@ -139,6 +139,8 @@ impl ConnectorCommon for Payu { reason: response.status.code_literal, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -339,6 +341,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/placetopay.rs b/crates/hyperswitch_connectors/src/connectors/placetopay.rs index 6e593c53e16..54d8ffadf34 100644 --- a/crates/hyperswitch_connectors/src/connectors/placetopay.rs +++ b/crates/hyperswitch_connectors/src/connectors/placetopay.rs @@ -134,6 +134,8 @@ impl ConnectorCommon for Placetopay { reason: Some(response.status.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz.rs b/crates/hyperswitch_connectors/src/connectors/powertranz.rs index 6d88ac368a0..52db1eb49d2 100644 --- a/crates/hyperswitch_connectors/src/connectors/powertranz.rs +++ b/crates/hyperswitch_connectors/src/connectors/powertranz.rs @@ -147,6 +147,8 @@ impl ConnectorCommon for Powertranz { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs index 03eaa27281c..04df8ee5e54 100644 --- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs @@ -459,6 +459,8 @@ fn build_error_response(item: &PowertranzBaseResponse, status_code: u16) -> Opti ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } }) } else if !ISO_SUCCESS_CODES.contains(&item.iso_response_code.as_str()) { @@ -470,6 +472,8 @@ fn build_error_response(item: &PowertranzBaseResponse, status_code: u16) -> Opti reason: Some(item.response_message.clone()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None diff --git a/crates/hyperswitch_connectors/src/connectors/prophetpay.rs b/crates/hyperswitch_connectors/src/connectors/prophetpay.rs index 245eaf73e75..2518f08c69b 100644 --- a/crates/hyperswitch_connectors/src/connectors/prophetpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/prophetpay.rs @@ -141,6 +141,8 @@ impl ConnectorCommon for Prophetpay { reason: Some(response.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs index cb93caded2c..28f0e4981be 100644 --- a/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs @@ -425,6 +425,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -473,6 +475,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ProphetpaySyncResponse, T, PaymentsResp status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -521,6 +525,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ProphetpayVoidResponse, T, PaymentsResp status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -629,6 +635,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, ProphetpayRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -669,6 +677,8 @@ impl<T> TryFrom<RefundsResponseRouterData<T, ProphetpayRefundSyncResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd.rs b/crates/hyperswitch_connectors/src/connectors/rapyd.rs index d5473b260f9..b777aff4d9d 100644 --- a/crates/hyperswitch_connectors/src/connectors/rapyd.rs +++ b/crates/hyperswitch_connectors/src/connectors/rapyd.rs @@ -140,6 +140,8 @@ impl ConnectorCommon for Rapyd { reason: response_data.status.message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs b/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs index 7d4517e00bd..236d9e55b5a 100644 --- a/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs @@ -451,6 +451,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsRespo reason: data.failure_message.to_owned(), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ), _ => { @@ -495,6 +497,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsRespo reason: item.response.status.message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ), }; diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay.rs b/crates/hyperswitch_connectors/src/connectors/razorpay.rs index 435ff983c8b..fc7cdeb69ab 100644 --- a/crates/hyperswitch_connectors/src/connectors/razorpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/razorpay.rs @@ -160,6 +160,8 @@ impl ConnectorCommon for Razorpay { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } razorpay::ErrorResponse::RazorpayStringError(error_string) => { @@ -170,6 +172,8 @@ impl ConnectorCommon for Razorpay { reason: Some(error_string.clone()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs index af9e67f8dbe..214102e42f3 100644 --- a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs @@ -817,6 +817,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, RazorpayPaymentsResponse, T, PaymentsRe status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -1273,6 +1275,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.refund.unique_request_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }), }; Ok(Self { diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index c16810a6ab7..99714dd55f4 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Recurly { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/redsys.rs b/crates/hyperswitch_connectors/src/connectors/redsys.rs index 501182dec07..97f4b4c4b4b 100644 --- a/crates/hyperswitch_connectors/src/connectors/redsys.rs +++ b/crates/hyperswitch_connectors/src/connectors/redsys.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Redsys { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/shift4.rs b/crates/hyperswitch_connectors/src/connectors/shift4.rs index 0bf8c4094b1..b85c2472e58 100644 --- a/crates/hyperswitch_connectors/src/connectors/shift4.rs +++ b/crates/hyperswitch_connectors/src/connectors/shift4.rs @@ -140,6 +140,8 @@ impl ConnectorCommon for Shift4 { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/square.rs b/crates/hyperswitch_connectors/src/connectors/square.rs index 9615d4afdd7..6ac3420219d 100644 --- a/crates/hyperswitch_connectors/src/connectors/square.rs +++ b/crates/hyperswitch_connectors/src/connectors/square.rs @@ -158,6 +158,8 @@ impl ConnectorCommon for Square { reason: Some(reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/stax.rs b/crates/hyperswitch_connectors/src/connectors/stax.rs index 27be4d309dc..57b8ce1a282 100644 --- a/crates/hyperswitch_connectors/src/connectors/stax.rs +++ b/crates/hyperswitch_connectors/src/connectors/stax.rs @@ -135,6 +135,8 @@ impl ConnectorCommon for Stax { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs index e05fb8b8e33..f3d63ed9ea4 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -141,6 +141,8 @@ impl ConnectorCommon for Stripebilling { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/taxjar.rs b/crates/hyperswitch_connectors/src/connectors/taxjar.rs index 30b92d9ceb8..4420384e87f 100644 --- a/crates/hyperswitch_connectors/src/connectors/taxjar.rs +++ b/crates/hyperswitch_connectors/src/connectors/taxjar.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Taxjar { reason: Some(response.detail), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/thunes.rs b/crates/hyperswitch_connectors/src/connectors/thunes.rs index b26c0e67fec..3e2e2fec33c 100644 --- a/crates/hyperswitch_connectors/src/connectors/thunes.rs +++ b/crates/hyperswitch_connectors/src/connectors/thunes.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Thunes { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rs index b3f2c1f9c3e..fed5c109460 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs @@ -177,6 +177,8 @@ impl ConnectorCommon for Trustpay { .or(response_data.payment_description), attempt_status: None, connector_transaction_id: response_data.instance_id, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { @@ -333,6 +335,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: response.result_info.additional_info, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs index e8da94fae34..0b94b816196 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs @@ -732,6 +732,8 @@ fn handle_cards_response( status_code, attempt_status: None, connector_transaction_id: Some(response.instance_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -797,6 +799,8 @@ fn handle_bank_redirects_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }); let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, @@ -849,6 +853,8 @@ fn handle_bank_redirects_sync_response( .payment_request_id .clone(), ), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -903,6 +909,8 @@ pub fn handle_webhook_response( status_code, attempt_status: None, connector_transaction_id: payment_information.references.payment_request_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1011,6 +1019,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessTo status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -1482,6 +1492,8 @@ fn handle_cards_refund_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1515,6 +1527,8 @@ fn handle_webhooks_refund_response( status_code, attempt_status: None, connector_transaction_id: response.references.payment_request_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1543,6 +1557,8 @@ fn handle_bank_redirects_refund_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1579,6 +1595,8 @@ fn handle_bank_redirects_refund_sync_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1602,6 +1620,8 @@ fn handle_bank_redirects_refund_sync_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }); //unreachable case as we are sending error as Some() let refund_response_data = RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs index c2c99c88439..a0e014fd159 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs @@ -238,6 +238,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs index ac634d58aea..61e29203979 100644 --- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs +++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs @@ -149,6 +149,8 @@ impl ConnectorCommon for UnifiedAuthenticationService { reason: Some(response.error), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/volt.rs b/crates/hyperswitch_connectors/src/connectors/volt.rs index cec1194f281..ae3699bcc20 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt.rs @@ -171,6 +171,8 @@ impl ConnectorCommon for Volt { reason: Some(reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -275,6 +277,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index 3841b7e33b4..33d174d5db8 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -354,6 +354,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsRe status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(payment_response.id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -395,6 +397,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsRe status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(webhook_response.payment.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs index 8566ec70341..e58b9d4439a 100644 --- a/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs +++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs @@ -222,6 +222,8 @@ impl ConnectorCommon for Wellsfargo { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(transformers::WellsfargoErrorResponse::AuthenticationError(response)) => { @@ -234,6 +236,8 @@ impl ConnectorCommon for Wellsfargo { reason: Some(response.response.rmsg), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(transformers::WellsfargoErrorResponse::NotAvailableError(response)) => { @@ -258,6 +262,8 @@ impl ConnectorCommon for Wellsfargo { reason: Some(error_response), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { @@ -482,6 +488,8 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -562,6 +570,8 @@ impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevoke status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) @@ -696,6 +706,8 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -890,6 +902,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1011,6 +1025,8 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for We .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs index 10c381fa857..b346d396866 100644 --- a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs @@ -1708,10 +1708,10 @@ fn get_error_response_if_failure( fn get_payment_response( (info_response, status, http_code): (&WellsfargoPaymentsResponse, enums::AttemptStatus, u16), -) -> Result<PaymentsResponseData, ErrorResponse> { +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { - Some(error) => Err(error), + Some(error) => Err(Box::new(error)), None => { let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); @@ -1776,7 +1776,8 @@ impl .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information @@ -1832,7 +1833,8 @@ impl<F> .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), true, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, @@ -1862,7 +1864,8 @@ impl<F> .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), false, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, @@ -2376,6 +2379,8 @@ pub fn get_error_response( status_code, attempt_status, connector_transaction_id: Some(transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } pub fn get_error_reason( diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index 41b2207b175..b261343c5b1 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -156,6 +156,8 @@ impl ConnectorCommon for Worldpay { reason: response.validation_errors.map(|e| e.to_string()), attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -483,6 +485,8 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wor reason: response.validation_errors.map(|e| e.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index 65c884601de..61621b3cc93 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -786,6 +786,8 @@ impl<F, T> status_code: router_data.http_code, attempt_status: Some(status), connector_transaction_id: optional_correlation_id, + issuer_error_code: None, + issuer_error_message: None, }), (_, Some((code, message))) => Err(ErrorResponse { code, @@ -794,6 +796,8 @@ impl<F, T> status_code: router_data.http_code, attempt_status: Some(status), connector_transaction_id: optional_correlation_id, + issuer_error_code: None, + issuer_error_message: None, }), }; Ok(Self { diff --git a/crates/hyperswitch_connectors/src/connectors/xendit.rs b/crates/hyperswitch_connectors/src/connectors/xendit.rs index f1872e31ae7..cd65b25fda4 100644 --- a/crates/hyperswitch_connectors/src/connectors/xendit.rs +++ b/crates/hyperswitch_connectors/src/connectors/xendit.rs @@ -154,6 +154,8 @@ impl ConnectorCommon for Xendit { status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs index 47936d43065..30b023e6dc4 100644 --- a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs @@ -330,6 +330,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(item.response.id.clone()), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { let charges = match item.data.request.split_payments.as_ref() { @@ -439,6 +441,8 @@ impl<F> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -572,6 +576,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<XenditResponse>> for PaymentsSyncRou attempt_status: None, connector_transaction_id: Some(payment_response.id.clone()), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/zen.rs b/crates/hyperswitch_connectors/src/connectors/zen.rs index 70703b31643..71ca8c7758d 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen.rs @@ -146,6 +146,8 @@ impl ConnectorCommon for Zen { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index 305c8518c8e..bec1f6be0a4 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -939,6 +939,8 @@ fn get_zen_response( status_code, attempt_status: Some(status), connector_transaction_id: Some(response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1085,6 +1087,8 @@ fn get_zen_refund_response( status_code, attempt_status: None, connector_transaction_id: Some(response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None diff --git a/crates/hyperswitch_connectors/src/connectors/zsl.rs b/crates/hyperswitch_connectors/src/connectors/zsl.rs index d7c0152b7a6..7ed2a660822 100644 --- a/crates/hyperswitch_connectors/src/connectors/zsl.rs +++ b/crates/hyperswitch_connectors/src/connectors/zsl.rs @@ -123,6 +123,8 @@ impl ConnectorCommon for Zsl { reason: Some(error_reason), attempt_status: Some(common_enums::AttemptStatus::Failure), connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs index 8a39901e5de..66bd3eda1d1 100644 --- a/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs @@ -349,6 +349,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsRespons status_code: item.http_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(item.response.mer_ref.clone()), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -365,6 +367,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsRespons status_code: item.http_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(item.response.mer_ref.clone()), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -443,6 +447,8 @@ impl<F> TryFrom<ResponseRouterData<F, ZslWebhookResponse, PaymentsSyncData, Paym status_code: item.http_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(item.response.mer_ref.clone()), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index b082962e400..97c27539c67 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -336,6 +336,8 @@ pub(crate) fn handle_json_response_deserialization_failure( reason: Some(response_data), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index fd8e144f4f2..733c6a73c93 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -702,6 +702,8 @@ impl From<ApiErrorResponse> for router_data::ErrorResponse { }, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 70926056957..2dc4eec15f1 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -846,6 +846,8 @@ pub struct PaymentAttempt { pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] @@ -1239,6 +1241,8 @@ pub enum PaymentAttemptUpdate { connector_transaction_id: Option<String>, payment_method_data: Option<serde_json::Value>, authentication_type: Option<storage_enums::AuthenticationType>, + issuer_error_code: Option<String>, + issuer_error_message: Option<String>, }, CaptureUpdate { amount_to_capture: Option<MinorUnit>, @@ -1542,6 +1546,8 @@ impl PaymentAttemptUpdate { connector_transaction_id, payment_method_data, authentication_type, + issuer_error_code, + issuer_error_message, } => DieselPaymentAttemptUpdate::ErrorUpdate { connector, status, @@ -1555,6 +1561,8 @@ impl PaymentAttemptUpdate { connector_transaction_id, payment_method_data, authentication_type, + issuer_error_code, + issuer_error_message, }, Self::CaptureUpdate { multiple_capture_count, @@ -1824,6 +1832,8 @@ impl behaviour::Conversion for PaymentAttempt { processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, + issuer_error_code: self.issuer_error_code, + issuer_error_message: self.issuer_error_message, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, }) @@ -1912,6 +1922,8 @@ impl behaviour::Conversion for PaymentAttempt { capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, charges: storage_model.charges, + issuer_error_code: storage_model.issuer_error_code, + issuer_error_message: storage_model.issuer_error_message, }) } .await diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index 7f1278414ea..6618d2fbc80 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -399,6 +399,8 @@ pub struct ErrorResponse { pub status_code: u16, pub attempt_status: Option<common_enums::enums::AttemptStatus>, pub connector_transaction_id: Option<String>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } impl Default for ErrorResponse { @@ -410,6 +412,8 @@ impl Default for ErrorResponse { status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } } @@ -423,6 +427,8 @@ impl ErrorResponse { status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } } @@ -601,6 +607,8 @@ impl status_code: _, attempt_status, connector_transaction_id, + issuer_error_code: _, + issuer_error_message: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); @@ -798,6 +806,8 @@ impl status_code: _, attempt_status, connector_transaction_id, + issuer_error_code: _, + issuer_error_message: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); @@ -1013,6 +1023,8 @@ impl status_code: _, attempt_status, connector_transaction_id, + issuer_error_code: _, + issuer_error_message: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(common_enums::AttemptStatus::Failure); @@ -1256,6 +1268,8 @@ impl status_code: _, attempt_status, connector_transaction_id, + issuer_error_code: _, + issuer_error_message: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs index b70d326feb6..78fdba32c9b 100644 --- a/crates/hyperswitch_interfaces/src/api.rs +++ b/crates/hyperswitch_interfaces/src/api.rs @@ -198,6 +198,8 @@ pub trait ConnectorIntegration<T, Req, Resp>: status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } @@ -286,6 +288,8 @@ pub trait ConnectorCommon { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs index bc18f5c6639..e0974f5d04d 100644 --- a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs +++ b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs @@ -158,6 +158,8 @@ pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } diff --git a/crates/router/src/connector/adyenplatform.rs b/crates/router/src/connector/adyenplatform.rs index f95e9cd4d64..5ff89721cb4 100644 --- a/crates/router/src/connector/adyenplatform.rs +++ b/crates/router/src/connector/adyenplatform.rs @@ -99,6 +99,8 @@ impl ConnectorCommon for Adyenplatform { reason: response.detail, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs index 226067cef96..f2058c17f6c 100644 --- a/crates/router/src/connector/dummyconnector.rs +++ b/crates/router/src/connector/dummyconnector.rs @@ -125,6 +125,8 @@ impl<const T: u8> ConnectorCommon for DummyConnector<T> { reason: response.error.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/ebanx.rs b/crates/router/src/connector/ebanx.rs index 01db54c1f67..b38297ed5c7 100644 --- a/crates/router/src/connector/ebanx.rs +++ b/crates/router/src/connector/ebanx.rs @@ -124,6 +124,8 @@ impl ConnectorCommon for Ebanx { reason: response.message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/gpayments.rs b/crates/router/src/connector/gpayments.rs index 1febbfa7885..2d3b1c37d58 100644 --- a/crates/router/src/connector/gpayments.rs +++ b/crates/router/src/connector/gpayments.rs @@ -123,6 +123,8 @@ impl ConnectorCommon for Gpayments { reason: response.error_detail, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/netcetera.rs b/crates/router/src/connector/netcetera.rs index 459ac93e068..f1fc94bd482 100644 --- a/crates/router/src/connector/netcetera.rs +++ b/crates/router/src/connector/netcetera.rs @@ -111,6 +111,8 @@ impl ConnectorCommon for Netcetera { reason: response.error_details.error_detail, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs index 886dbc18ad4..1169f29563e 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/router/src/connector/netcetera/transformers.rs @@ -110,6 +110,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } }; @@ -179,6 +181,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), }; Ok(Self { diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs index 73aaec55e57..d0cc0f156d7 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/router/src/connector/nmi.rs @@ -103,6 +103,8 @@ impl ConnectorCommon for Nmi { code: response.response_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index d6f1cb1962f..da2649cc444 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -224,6 +224,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transactionid), + issuer_error_code: None, + issuer_error_message: None, }), enums::AttemptStatus::Failure, ), @@ -401,6 +403,8 @@ impl ForeignFrom<(NmiCompleteResponse, u16)> for types::ErrorResponse { status_code: http_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), + issuer_error_code: None, + issuer_error_message: None, } } } @@ -905,6 +909,8 @@ impl ForeignFrom<(StandardResponse, u16)> for types::ErrorResponse { status_code: http_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), + issuer_error_code: None, + issuer_error_message: None, } } } diff --git a/crates/router/src/connector/payone.rs b/crates/router/src/connector/payone.rs index 58b179e5799..2e7656f08cf 100644 --- a/crates/router/src/connector/payone.rs +++ b/crates/router/src/connector/payone.rs @@ -210,6 +210,8 @@ impl ConnectorCommon for Payone { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), None => Ok(ErrorResponse { status_code: res.status_code, @@ -218,6 +220,8 @@ impl ConnectorCommon for Payone { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } diff --git a/crates/router/src/connector/plaid.rs b/crates/router/src/connector/plaid.rs index f24d7bd8d6d..b5428fba4d3 100644 --- a/crates/router/src/connector/plaid.rs +++ b/crates/router/src/connector/plaid.rs @@ -133,6 +133,8 @@ impl ConnectorCommon for Plaid { reason: response.display_message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs index 4e4fb1863ee..ebab8c185af 100644 --- a/crates/router/src/connector/plaid/transformers.rs +++ b/crates/router/src/connector/plaid/transformers.rs @@ -302,6 +302,8 @@ impl<F, T> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.payment_id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { @@ -388,6 +390,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::Pay status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.payment_id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs index 1268e041603..a9585e5d3fd 100644 --- a/crates/router/src/connector/riskified.rs +++ b/crates/router/src/connector/riskified.rs @@ -147,6 +147,8 @@ impl ConnectorCommon for Riskified { message: response.error.message.clone(), reason: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs index 21452819c39..857dce8c2e3 100644 --- a/crates/router/src/connector/signifyd.rs +++ b/crates/router/src/connector/signifyd.rs @@ -108,6 +108,8 @@ impl ConnectorCommon for Signifyd { reason: Some(response.errors.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index a971bd96741..3971ecc7db8 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -129,6 +129,8 @@ impl ConnectorCommon for Stripe { reason: response.error.message, attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -331,6 +333,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -463,6 +467,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -591,6 +597,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -744,6 +752,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -914,6 +924,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1164,6 +1176,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1291,6 +1305,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1451,6 +1467,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1620,6 +1638,8 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1754,6 +1774,8 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1908,6 +1930,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -2021,6 +2045,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -2152,6 +2178,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 41fb23e7e9e..39d43bd2e06 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -3158,6 +3158,8 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::RefundsResponseData { @@ -3193,6 +3195,8 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::RefundsResponseData { @@ -3549,6 +3553,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(item.response.id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { @@ -4169,6 +4175,8 @@ impl ForeignTryFrom<(&Option<ErrorDetails>, u16, String)> for types::PaymentsRes status_code: http_code, attempt_status: None, connector_transaction_id: Some(response_id), + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/threedsecureio.rs b/crates/router/src/connector/threedsecureio.rs index aec8f780451..09d232c7471 100644 --- a/crates/router/src/connector/threedsecureio.rs +++ b/crates/router/src/connector/threedsecureio.rs @@ -122,6 +122,8 @@ impl ConnectorCommon for Threedsecureio { reason: response.error_description, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(err) => { diff --git a/crates/router/src/connector/threedsecureio/transformers.rs b/crates/router/src/connector/threedsecureio/transformers.rs index dc1a90f36e7..faf72a2951b 100644 --- a/crates/router/src/connector/threedsecureio/transformers.rs +++ b/crates/router/src/connector/threedsecureio/transformers.rs @@ -124,6 +124,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } }; @@ -205,6 +207,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } ThreedsecureioErrorResponseWrapper::ErrorString(error) => { @@ -215,6 +219,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } }, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 8a186e0291a..5009eaf4daa 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2621,6 +2621,8 @@ impl status_code: http_code, attempt_status, connector_transaction_id, + issuer_error_code: None, + issuer_error_message: None, } } } diff --git a/crates/router/src/connector/wellsfargopayout.rs b/crates/router/src/connector/wellsfargopayout.rs index 33111ee7be0..5caf3c689b2 100644 --- a/crates/router/src/connector/wellsfargopayout.rs +++ b/crates/router/src/connector/wellsfargopayout.rs @@ -132,6 +132,8 @@ impl ConnectorCommon for Wellsfargopayout { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs index e4493f5016f..a1d75f18b2a 100644 --- a/crates/router/src/connector/wise.rs +++ b/crates/router/src/connector/wise.rs @@ -113,6 +113,8 @@ impl ConnectorCommon for Wise { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::ErrorResponse { @@ -122,6 +124,8 @@ impl ConnectorCommon for Wise { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -132,6 +136,8 @@ impl ConnectorCommon for Wise { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } @@ -338,6 +344,8 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index 7d56c2ccb91..22f1b593f13 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -233,6 +233,8 @@ pub async fn refresh_connector_auth( status_code: 504, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }; Ok(Err(error_response)) diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index bcf0d624ff9..409fccf5e63 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1436,6 +1436,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( connector_transaction_id: err.connector_transaction_id, payment_method_data: additional_payment_method_data, authentication_type: auth_update, + issuer_error_code: err.issuer_error_code, + issuer_error_message: err.issuer_error_message, }), ) } @@ -1473,6 +1475,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( connector_transaction_id, payment_method_data: None, authentication_type: auth_update, + issuer_error_code: None, + issuer_error_message: None, }), ) } diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 5fdf14dbf5a..24a3ac2ec86 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -537,6 +537,8 @@ where connector_transaction_id: error_response.connector_transaction_id.clone(), payment_method_data: additional_payment_method_data, authentication_type: auth_update, + issuer_error_code: error_response.issuer_error_code.clone(), + issuer_error_message: error_response.issuer_error_message.clone(), }; #[cfg(feature = "v1")] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index a34c137dbda..7f5f7858a3a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2569,6 +2569,8 @@ where capture_before: payment_attempt.capture_before, extended_authorization_applied: payment_attempt.extended_authorization_applied, card_discovery: payment_attempt.card_discovery, + issuer_error_code: payment_attempt.issuer_error_code, + issuer_error_message: payment_attempt.issuer_error_message, }; services::ApplicationResponse::JsonWithHeaders((payments_response, headers)) @@ -2827,7 +2829,9 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay order_tax_amount: None, connector_mandate_id:None, shipping_cost: None, - card_discovery: pa.card_discovery + card_discovery: pa.card_discovery, + issuer_error_code: pa.issuer_error_code, + issuer_error_message: pa.issuer_error_message, } } } diff --git a/crates/router/src/core/payouts/access_token.rs b/crates/router/src/core/payouts/access_token.rs index e5e9b47e4ff..52c31e8fa94 100644 --- a/crates/router/src/core/payouts/access_token.rs +++ b/crates/router/src/core/payouts/access_token.rs @@ -172,6 +172,8 @@ pub async fn refresh_connector_auth( status_code: 504, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }; Ok(Err(error_response)) diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index b850420dfd7..7d663a48a1a 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -238,6 +238,8 @@ pub async fn trigger_refund_to_gateway( processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }) } errors::ConnectorError::NotSupported { message, connector } => { @@ -252,6 +254,8 @@ pub async fn trigger_refund_to_gateway( processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }) } _ => None, @@ -335,6 +339,8 @@ pub async fn trigger_refund_to_gateway( processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), + issuer_error_code: err.issuer_error_code, + issuer_error_message: err.issuer_error_message, } } Ok(response) => { @@ -366,6 +372,8 @@ pub async fn trigger_refund_to_gateway( processor_refund_data, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, } } Ok(()) => { @@ -680,6 +688,8 @@ pub async fn sync_refund_with_gateway( processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: error_message.issuer_error_code, + issuer_error_message: error_message.issuer_error_message, } } Ok(response) => match router_data_res.integrity_check.clone() { @@ -710,6 +720,8 @@ pub async fn sync_refund_with_gateway( processor_refund_data, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, } } Ok(()) => { @@ -1265,6 +1277,8 @@ impl ForeignFrom<storage::Refund> for api::RefundResponse { split_refunds: refund.split_refunds, unified_code: refund.unified_code, unified_message: refund.unified_message, + issuer_error_code: refund.issuer_error_code, + issuer_error_message: refund.issuer_error_message, } } } diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 07bdfa3f77d..1f54eeb5fdc 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -439,6 +439,8 @@ mod storage { unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), + issuer_error_code: None, + issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, @@ -939,6 +941,8 @@ impl RefundInterface for MockDb { unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), + issuer_error_code: None, + issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index df33e803ab8..e8af5b3b773 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -170,6 +170,8 @@ where reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -359,6 +361,8 @@ where status_code: 504, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }; router_data.response = Err(error_response); router_data.connector_http_status_code = Some(504); diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index f9ef4880924..59ee4e4fb38 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -699,6 +699,8 @@ pub fn handle_json_response_deserialization_failure( reason: Some(response_data), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index 64c4853d14b..dac001bac9d 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -154,6 +154,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { connector_transaction_id: None, payment_method_data: None, authentication_type: None, + issuer_error_code: None, + issuer_error_message: None, }; payment_data.payment_attempt = db diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 94dcba750af..0e57540e0ea 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -454,6 +454,8 @@ async fn payments_create_core() { connector_mandate_id: None, shipping_cost: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, }; let expected_response = services::ApplicationResponse::JsonWithHeaders((expected_response, vec![])); @@ -721,6 +723,8 @@ async fn payments_create_core_adyen_no_redirect() { connector_mandate_id: None, shipping_cost: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, }, vec![], )); diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 66cd41dbc74..19281b45019 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -215,6 +215,8 @@ async fn payments_create_core() { connector_mandate_id: None, shipping_cost: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, }; let expected_response = @@ -491,6 +493,8 @@ async fn payments_create_core_adyen_no_redirect() { connector_mandate_id: None, shipping_cost: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, }, vec![], )); diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 1e4efb2b350..2a637a77e23 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -229,6 +229,8 @@ impl PaymentAttemptInterface for MockDb { capture_before: payment_attempt.capture_before, card_discovery: payment_attempt.card_discovery, charges: None, + issuer_error_code: None, + issuer_error_message: None, }; 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 076b120c2d0..aaa709e7fa7 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -647,6 +647,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { capture_before: payment_attempt.capture_before, card_discovery: payment_attempt.card_discovery, charges: None, + issuer_error_code: None, + issuer_error_message: None, }; let field = format!("pa_{}", created_attempt.attempt_id); @@ -1648,6 +1650,8 @@ impl DataModelExt for PaymentAttempt { processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, + issuer_error_code: self.issuer_error_code, + issuer_error_message: self.issuer_error_message, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, } @@ -1731,6 +1735,8 @@ impl DataModelExt for PaymentAttempt { capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, charges: storage_model.charges, + issuer_error_code: storage_model.issuer_error_code, + issuer_error_message: storage_model.issuer_error_message, } } } diff --git a/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/down.sql b/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/down.sql new file mode 100644 index 00000000000..06abb6aefbd --- /dev/null +++ b/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/down.sql @@ -0,0 +1,7 @@ +ALTER TABLE payment_attempt +DROP COLUMN IF EXISTS issuer_error_code, +DROP COLUMN IF EXISTS issuer_error_message; + +ALTER TABLE refund +DROP COLUMN IF EXISTS issuer_error_code, +DROP COLUMN IF EXISTS issuer_error_message; \ No newline at end of file diff --git a/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/up.sql b/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/up.sql new file mode 100644 index 00000000000..80c1bc3742e --- /dev/null +++ b/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/up.sql @@ -0,0 +1,7 @@ +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS issuer_error_code VARCHAR(64) DEFAULT NULL, +ADD COLUMN IF NOT EXISTS issuer_error_message TEXT DEFAULT NULL; + +ALTER TABLE refund +ADD COLUMN IF NOT EXISTS issuer_error_code VARCHAR(64) DEFAULT NULL, +ADD COLUMN IF NOT EXISTS issuer_error_message TEXT DEFAULT NULL; \ No newline at end of file diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index b0a3f007eee..cbb2b264d45 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -89,7 +89,9 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id, DROP COLUMN authentication_data, DROP COLUMN payment_method_billing_address_id, DROP COLUMN connector_mandate_detail, - DROP COLUMN charge_id; + DROP COLUMN charge_id, + DROP COLUMN issuer_error_code, + DROP COLUMN issuer_error_message; ALTER TABLE payment_methods @@ -113,7 +115,9 @@ DROP TYPE IF EXISTS "PaymentMethodIssuerCode"; -- Run below queries only when V1 is deprecated ALTER TABLE refund DROP COLUMN connector_refund_data, - DROP COLUMN connector_transaction_data; + DROP COLUMN connector_transaction_data, + DROP COLUMN issuer_error_code, + DROP COLUMN issuer_error_message; -- Run below queries only when V1 is deprecated ALTER TABLE captures DROP COLUMN connector_capture_data;
2025-03-16T14:34:27Z
## Description This PR introduces - - Core functionality to read and store raw acquirer responses for `payment` and `refund` operations. - Read raw acquirer response from connector integration - Store in `PaymentAttempt` and `Refund` tables - Updates Adyen connector integration to read raw acquirer response. - Exposes these fields in `/payments` and `/refunds` API response. Described in #7467 ## Motivation and Context Helps HS consumer look at issuer specific error responses - these can be enabled on demand from connector's end. #
c39ecda79a9b1df1ccb4e469111e0dfb92a3d82c
Not possible to test raw acquirer codes in connector sandbox env. Can only be enabled and tested in production.
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payments.rs", "crates/api_models/src/refunds.rs", "crates/diesel_models/src/payment_attempt.rs", "crates/diesel_models/src/refund.rs", "crates/diesel_models/src/schema.rs", "crates/hyperswitch_connectors/src/connectors/aci.rs", "crates/hyperswitch_connectors/src/connectors/adyen.rs", "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", "crates/hyperswitch_connectors/src/connectors/airwallex.rs", "crates/hyperswitch_connectors/src/connectors/amazonpay.rs", "crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs", "crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs", "crates/hyperswitch_connectors/src/connectors/bambora.rs", "crates/hyperswitch_connectors/src/connectors/bamboraapac.rs", "crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs", "crates/hyperswitch_connectors/src/connectors/bankofamerica.rs", "crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs", "crates/hyperswitch_connectors/src/connectors/billwerk.rs", "crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs", "crates/hyperswitch_connectors/src/connectors/bitpay.rs", "crates/hyperswitch_connectors/src/connectors/bluesnap.rs", "crates/hyperswitch_connectors/src/connectors/boku.rs", "crates/hyperswitch_connectors/src/connectors/braintree.rs", "crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs", "crates/hyperswitch_connectors/src/connectors/cashtocode.rs", "crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs", "crates/hyperswitch_connectors/src/connectors/chargebee.rs", "crates/hyperswitch_connectors/src/connectors/checkout.rs", "crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs", "crates/hyperswitch_connectors/src/connectors/coinbase.rs", "crates/hyperswitch_connectors/src/connectors/coingate.rs", "crates/hyperswitch_connectors/src/connectors/cryptopay.rs", "crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/cybersource.rs", "crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs", "crates/hyperswitch_connectors/src/connectors/datatrans.rs", "crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs", "crates/hyperswitch_connectors/src/connectors/deutschebank.rs", "crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs", "crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs", "crates/hyperswitch_connectors/src/connectors/dlocal.rs", "crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs", "crates/hyperswitch_connectors/src/connectors/fiserv.rs", "crates/hyperswitch_connectors/src/connectors/fiservemea.rs", "crates/hyperswitch_connectors/src/connectors/fiuu.rs", "crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs", "crates/hyperswitch_connectors/src/connectors/forte.rs", "crates/hyperswitch_connectors/src/connectors/getnet.rs", "crates/hyperswitch_connectors/src/connectors/globalpay.rs", "crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/globepay.rs", "crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/gocardless.rs", "crates/hyperswitch_connectors/src/connectors/helcim.rs", "crates/hyperswitch_connectors/src/connectors/hipay.rs", "crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/iatapay.rs", "crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/inespay.rs", "crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/itaubank.rs", "crates/hyperswitch_connectors/src/connectors/jpmorgan.rs", "crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs", "crates/hyperswitch_connectors/src/connectors/klarna.rs", "crates/hyperswitch_connectors/src/connectors/mifinity.rs", "crates/hyperswitch_connectors/src/connectors/mollie.rs", "crates/hyperswitch_connectors/src/connectors/moneris.rs", "crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/nexinets.rs", "crates/hyperswitch_connectors/src/connectors/nexixpay.rs", "crates/hyperswitch_connectors/src/connectors/nomupay.rs", "crates/hyperswitch_connectors/src/connectors/noon.rs", "crates/hyperswitch_connectors/src/connectors/noon/transformers.rs", "crates/hyperswitch_connectors/src/connectors/novalnet.rs", "crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs", "crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs", "crates/hyperswitch_connectors/src/connectors/opayo.rs", "crates/hyperswitch_connectors/src/connectors/opennode.rs", "crates/hyperswitch_connectors/src/connectors/paybox.rs", "crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs", "crates/hyperswitch_connectors/src/connectors/payeezy.rs", "crates/hyperswitch_connectors/src/connectors/payme.rs", "crates/hyperswitch_connectors/src/connectors/payme/transformers.rs", "crates/hyperswitch_connectors/src/connectors/paypal.rs", "crates/hyperswitch_connectors/src/connectors/paystack.rs", "crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs", "crates/hyperswitch_connectors/src/connectors/payu.rs", "crates/hyperswitch_connectors/src/connectors/placetopay.rs", "crates/hyperswitch_connectors/src/connectors/powertranz.rs", "crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs", "crates/hyperswitch_connectors/src/connectors/prophetpay.rs", "crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/rapyd.rs", "crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs", "crates/hyperswitch_connectors/src/connectors/razorpay.rs", "crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/recurly.rs", "crates/hyperswitch_connectors/src/connectors/redsys.rs", "crates/hyperswitch_connectors/src/connectors/shift4.rs", "crates/hyperswitch_connectors/src/connectors/square.rs", "crates/hyperswitch_connectors/src/connectors/stax.rs", "crates/hyperswitch_connectors/src/connectors/stripebilling.rs", "crates/hyperswitch_connectors/src/connectors/taxjar.rs", "crates/hyperswitch_connectors/src/connectors/thunes.rs", "crates/hyperswitch_connectors/src/connectors/trustpay.rs", "crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs", "crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs", "crates/hyperswitch_connectors/src/connectors/volt.rs", "crates/hyperswitch_connectors/src/connectors/volt/transformers.rs", "crates/hyperswitch_connectors/src/connectors/wellsfargo.rs", "crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs", "crates/hyperswitch_connectors/src/connectors/worldpay.rs", "crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/xendit.rs", "crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs", "crates/hyperswitch_connectors/src/connectors/zen.rs", "crates/hyperswitch_connectors/src/connectors/zen/transformers.rs", "crates/hyperswitch_connectors/src/connectors/zsl.rs", "crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs", "crates/hyperswitch_connectors/src/utils.rs", "crates/hyperswitch_domain_models/src/errors/api_error_response.rs", "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs", "crates/hyperswitch_domain_models/src/router_data.rs", "crates/hyperswitch_interfaces/src/api.rs", "crates/hyperswitch_interfaces/src/connector_integration_v2.rs", "crates/router/src/connector/adyenplatform.rs", "crates/router/src/connector/dummyconnector.rs", "crates/router/src/connector/ebanx.rs", "crates/router/src/connector/gpayments.rs", "crates/router/src/connector/netcetera.rs", "crates/router/src/connector/netcetera/transformers.rs", "crates/router/src/connector/nmi.rs", "crates/router/src/connector/nmi/transformers.rs", "crates/router/src/connector/payone.rs", "crates/router/src/connector/plaid.rs", "crates/router/src/connector/plaid/transformers.rs", "crates/router/src/connector/riskified.rs", "crates/router/src/connector/signifyd.rs", "crates/router/src/connector/stripe.rs", "crates/router/src/connector/stripe/transformers.rs", "crates/router/src/connector/threedsecureio.rs", "crates/router/src/connector/threedsecureio/transformers.rs", "crates/router/src/connector/utils.rs", "crates/router/src/connector/wellsfargopayout.rs", "crates/router/src/connector/wise.rs", "crates/router/src/core/payments/access_token.rs", "crates/router/src/core/payments/operations/payment_response.rs", "crates/router/src/core/payments/retry.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/core/payouts/access_token.rs", "crates/router/src/core/refunds.rs", "crates/router/src/db/refund.rs", "crates/router/src/services/api.rs", "crates/router/src/utils.rs", "crates/router/src/workflows/payment_sync.rs", "crates/router/tests/payments.rs", "crates/router/tests/payments2.rs", "crates/storage_impl/src/mock_db/payment_attempt.rs", "crates/storage_impl/src/payments/payment_attempt.rs", "migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/down.sql", "migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/up.sql", "v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7522
Bug: [BUG] Incorrect mapping of attempt status in AuthorizeDotNet connector ### Bug Description When the `capture_method` is `automatic`, AuthorizeDotNet connector first sends a `CapturedPendingSettlement` status which is mapped to `ChargeInitiated` in our codebase. That results in `processing` transaction status in the Hyperswitch's response (in production environment). ### Expected Behavior It should show the status of "succeeded". ### Actual Behavior When the `capture_method` is `automatic`, AuthorizeDotNet connector first sends a `CapturedPendingSettlement` status which is mapped to `ChargeInitiated` in our codebase. That results in `processing` transaction status in the Hyperswitch's response (in production environment). ### Steps To Reproduce Bug can only be seen in production environment. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: MacOS 2. Rust version (output of `rustc --version`): `rustc 1.83.0 (90b35a623 2024-11-26)` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index d7f50aa7405..3ba9e76cc7d 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -1587,8 +1587,9 @@ pub struct AuthorizedotnetRSyncResponse { impl From<SyncStatus> for enums::AttemptStatus { fn from(transaction_status: SyncStatus) -> Self { match transaction_status { - SyncStatus::SettledSuccessfully => Self::Charged, - SyncStatus::CapturedPendingSettlement => Self::CaptureInitiated, + SyncStatus::SettledSuccessfully | SyncStatus::CapturedPendingSettlement => { + Self::Charged + } SyncStatus::AuthorizedPendingCapture => Self::Authorized, SyncStatus::Declined => Self::AuthenticationFailed, SyncStatus::Voided => Self::Voided,
2025-03-13T19:39:20Z
## Description <!-- Describe your changes in detail --> Changed the attempt status mapping of `CapturedPendingSettlement` given by AuthorizeDotNet from `ChargeInitiated` to `Charged` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> When the capture_method is automatic, AuthorizeDotNet connector first sends a `CapturedPendingSettlement` status which is mapped to `ChargeInitiated` in our codebase. That results in `processing` transaction status in the Hyperswitch's response (in production environment). #
3e7db573211ed61eadde3b601575f3472bda2b1f
Postman tests are not valid since AuthorizeDotNet directly sends `SettledSuccessfully` status in local/sandbox environment.
[ "crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7518
Bug: feat(router): Add `psp_tokenization_enabled` field in Customer Saved Payment Methods List Required to show whether `psp_tokenization` is enabled for a saved payment method
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index dbe13e3776e..0ae089c5ea0 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -2834,7 +2834,7 @@ } }, "/v2/customers/{id}/saved-payment-methods": { - "delete": { + "get": { "tags": [ "Payment Methods" ], @@ -7666,6 +7666,7 @@ "prophetpay", "rapyd", "razorpay", + "recurly", "shift4", "square", "stax", @@ -8651,7 +8652,8 @@ "recurring_enabled", "created", "requires_cvv", - "is_default" + "is_default", + "psp_tokenization_enabled" ], "properties": { "id": { @@ -8730,6 +8732,10 @@ } ], "nullable": true + }, + "psp_tokenization_enabled": { + "type": "boolean", + "description": "Whether psp_tokenization is enabled for the payment_method, this will be true when at least\none multi-use token with status `Active` is available for the payment method" } } }, @@ -11603,7 +11609,7 @@ "product_type": { "allOf": [ { - "$ref": "#/components/schemas/api_enums.MerchantProductType" + "$ref": "#/components/schemas/MerchantProductType" } ], "nullable": true @@ -11745,7 +11751,7 @@ "product_type": { "allOf": [ { - "$ref": "#/components/schemas/api_enums.MerchantProductType" + "$ref": "#/components/schemas/MerchantProductType" } ], "nullable": true @@ -12359,6 +12365,17 @@ }, "additionalProperties": false }, + "MerchantProductType": { + "type": "string", + "enum": [ + "orchestration", + "vault", + "recon", + "recovery", + "cost_observability", + "dynamic_routing" + ] + }, "MerchantRecipientData": { "oneOf": [ { @@ -12581,6 +12598,69 @@ } } }, + "NetworkTokenDetailsPaymentMethod": { + "type": "object", + "properties": { + "last4_digits": { + "type": "string", + "nullable": true + }, + "issuer_country": { + "type": "string", + "nullable": true + }, + "network_token_expiry_month": { + "type": "string", + "nullable": true + }, + "network_token_expiry_year": { + "type": "string", + "nullable": true + }, + "nick_name": { + "type": "string", + "nullable": true + }, + "card_holder_name": { + "type": "string", + "nullable": true + }, + "card_isin": { + "type": "string", + "nullable": true + }, + "card_issuer": { + "type": "string", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "nullable": true + }, + "saved_to_locker": { + "type": "boolean" + } + } + }, + "NetworkTokenResponse": { + "type": "object", + "required": [ + "payment_method_data" + ], + "properties": { + "payment_method_data": { + "$ref": "#/components/schemas/NetworkTokenDetailsPaymentMethod" + } + } + }, "NetworkTokenization": { "type": "object", "description": "The network tokenization configuration for creating the payment method session", @@ -13968,7 +14048,7 @@ "PaymentConnectorTransmission": { "type": "string", "enum": [ - "ConnectorCallFailed", + "ConnectorCallUnsuccessful", "ConnectorCallSucceeded" ] }, @@ -20385,6 +20465,7 @@ "prophetpay", "rapyd", "razorpay", + "recurly", "riskified", "shift4", "signifyd", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index b6f1e0a8b96..b3d21c5a0b6 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -113,7 +113,7 @@ pub struct MerchantAccountCreate { pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account - #[schema(value_type = Option<api_enums::MerchantProductType>)] + #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } @@ -198,6 +198,7 @@ pub struct MerchantAccountCreateWithoutOrgId { #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, + #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } @@ -560,7 +561,7 @@ pub struct MerchantAccountResponse { pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account - #[schema(value_type = Option<api_enums::MerchantProductType>)] + #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } @@ -596,7 +597,7 @@ pub struct MerchantAccountResponse { pub recon_status: api_enums::ReconStatus, /// Product Type of this merchant account - #[schema(value_type = Option<api_enums::MerchantProductType>)] + #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 6b9b35ac2c0..d665337fda0 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -980,16 +980,21 @@ pub struct CardDetailsPaymentMethod { pub saved_to_locker: bool, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<String>, + #[schema(value_type = Option<String>)] pub network_token_expiry_month: Option<masking::Secret<String>>, + #[schema(value_type = Option<String>)] pub network_token_expiry_year: Option<masking::Secret<String>>, + #[schema(value_type = Option<String>)] pub nick_name: Option<masking::Secret<String>>, + #[schema(value_type = Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, + #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] @@ -2019,6 +2024,10 @@ pub struct CustomerPaymentMethod { ///The network token details for the payment method pub network_tokenization: Option<NetworkTokenResponse>, + + /// Whether psp_tokenization is enabled for the payment_method, this will be true when at least + /// one multi-use token with status `Active` is available for the payment method + pub psp_tokenization_enabled: bool, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 1109c0ca75e..20d1aa64745 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -320,6 +320,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::PaymentLinkDetailsLayout, api_models::enums::PaymentMethodStatus, api_models::enums::UIWidgetFormLayout, + api_models::enums::MerchantProductType, api_models::enums::PaymentConnectorCategory, api_models::enums::CardDiscovery, api_models::enums::FeatureStatus, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 8a122b5fe8b..5bbd8dee4b4 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -259,6 +259,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::PaymentMethod, api_models::enums::PaymentMethodIssuerCode, api_models::enums::MandateStatus, + api_models::enums::MerchantProductType, api_models::enums::PaymentExperience, api_models::enums::BankNames, api_models::enums::BankType, @@ -527,6 +528,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodSessionRequest, api_models::payment_methods::PaymentMethodSessionResponse, api_models::payment_methods::PaymentMethodsSessionUpdateRequest, + api_models::payment_methods::NetworkTokenResponse, + api_models::payment_methods::NetworkTokenDetailsPaymentMethod, api_models::payment_methods::TokenizeCardRequest, api_models::payment_methods::TokenizeDataRequest, api_models::payment_methods::TokenizePaymentMethodRequest, diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs index 9304afc69d3..cf1cd15346f 100644 --- a/crates/openapi/src/routes/payment_method.rs +++ b/crates/openapi/src/routes/payment_method.rs @@ -326,7 +326,7 @@ pub async fn payment_method_delete_api() {} /// /// List the payment methods saved for a customer #[utoipa::path( - delete, + get, path = "/v2/customers/{id}/saved-payment-methods", params ( ("id" = String, Path, description = "The unique identifier for the customer"), diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 87f7e38c935..a7817329607 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -985,6 +985,15 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for api::CustomerPaymen // TODO: check how we can get this field let recurring_enabled = true; + let psp_tokenization_enabled = item.connector_mandate_details.and_then(|details| { + details.payments.map(|payments| { + payments.values().any(|connector_token_reference| { + connector_token_reference.connector_token_status + == api_enums::ConnectorTokenStatus::Active + }) + }) + }); + Ok(Self { id: item.id, customer_id: item.customer_id, @@ -999,6 +1008,7 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for api::CustomerPaymen is_default: false, billing: payment_method_billing, network_tokenization: network_token_resp, + psp_tokenization_enabled: psp_tokenization_enabled.unwrap_or(false), }) } }
2025-03-13T11:04:43Z
## Description <!-- Describe your changes in detail --> Added `psp_tokenization_enabled` field to `CustomerPaymentMethod` that denotes whether `psp_tokenization` is enabled for a saved payment method ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #7518 #
f8a8d2a0300034c8e6ab36d011f9180993dc5e5f
- Create a Payment Method Session NOTE: `psp_tokenization` field is required to generate token (Set `psp_tokenization_enabled` to `true`). Its value can either be `multi_use` or `single_use`. ``` curl --location 'http://localhost:8080/v2/payment-methods-session' \ --header 'x-profile-id: pro_piGRXWnlda2RVykbLnUU' \ --header 'Authorization: api-key=dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --data-raw '{ "customer_id": "12345_cus_0195ae660fb270e28ea754519806b702", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "multi_use" } }' ``` - Confirm the Payment Method Session ``` curl --location 'http://localhost:8080/v2/payment-methods-session/12345_pms_0195ae661bbc7d60a35f95ab5d29fe52/confirm' \ --header 'x-profile-id: pro_piGRXWnlda2RVykbLnUU' \ --header 'Authorization: publishable-key=pk_dev_04fccc9893564ead968e58bff3b8068b,client-secret=cs_0195ae661bbd70e39efd4f332f062b35' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" }' ``` Response: ```json { "id": "12345_pms_0195ae661bbc7d60a35f95ab5d29fe52", "customer_id": "12345_cus_0195ae660fb270e28ea754519806b702", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "multi_use", "connector_id": null }, "network_tokenization": null, "expires_at": "2025-03-19T12:49:42.237Z", "client_secret": "CLIENT_SECRET_REDACTED", "return_url": null, "next_action": null, "authentication_details": { "status": "succeeded", "error": null }, "associated_payment_methods": null } ``` - Retrieve Payment Method: ``` curl --location 'http://localhost:8080/v2/payment-methods/12345_pm_0195ae669d8476d1bdcb54a3b266b5a6' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_piGRXWnlda2RVykbLnUU' \ --header 'X-Resource-Type: payment_method' \ --header 'api-key: dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --header 'Authorization: api-key=dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' ``` Response: ```json { "id": "12345_pm_0195ae669d8476d1bdcb54a3b266b5a6", "merchant_id": "cloth_seller_ofmnd07CcVEfqVvCSgAJ", "customer_id": "12345_cus_0195ae660fb270e28ea754519806b702", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": false, "created": "2025-03-19T12:35:15.461Z", "last_used_at": "2025-03-19T12:35:15.461Z", "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "05", "expiry_year": "25", "card_holder_name": "John Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "connector_tokens": [ { "connector_id": "mca_8nVPkBONTcH6HgSf3u2W", "token_type": "multi_use", "status": "active", "connector_token_request_reference_id": "jRkI9KrD9ndJsl4YUi", "original_payment_authorized_amount": 0, "original_payment_authorized_currency": "USD", "metadata": null, "token": "pm_1R4Lq4D5R7gDAGffpqWfb9lx" } ], "network_token": null } ``` Customer Payment Methods List: ``` curl --location 'http://localhost:8080/v2/customers/12345_cus_0195ae660fb270e28ea754519806b702/saved-payment-methods' \ --header 'api-key: dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_piGRXWnlda2RVykbLnUU' \ --header 'Authorization: api-key=dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' ``` Response: ```json { "customer_payment_methods": [ { "id": "12345_pm_0195ae669d8476d1bdcb54a3b266b5a6", "customer_id": "12345_cus_0195ae660fb270e28ea754519806b702", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": true, "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "05", "expiry_year": "25", "card_holder_name": "John Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "created": "2025-03-19T12:35:15.461Z", "requires_cvv": true, "last_used_at": "2025-03-19T12:35:15.461Z", "is_default": false, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "network_tokenization": null, "psp_tokenization_enabled": true } ] } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/admin.rs", "crates/api_models/src/payment_methods.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/openapi_v2.rs", "crates/openapi/src/routes/payment_method.rs", "crates/router/src/core/payment_methods/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7510
Bug: [FEATURE] add functionality to enable payment link form button only when form is filled ### Feature Description Payment link renders a submit button for submitting the payment form data. This button is always enabled, and displays any errors in case an incomplete form was tried to submit. This feature takes care of enabling the button only when the form is complete. ### Possible Implementation Since payment link already has a defined behavior today - to keep the button enabled, but display validation errors in case an incomplete form was submitted, this new feature can be added behind a payment link config flag. `enable_button_only_on_form_ready` - default will be false This will control the behavior of enabling / disabling for incomplete forms. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index d93208fb665..1ffd5a880b5 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -11583,6 +11583,14 @@ "type": "object", "description": "Metadata is useful for storing additional, unstructured information about the merchant account.", "nullable": true + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } }, "additionalProperties": false @@ -11717,6 +11725,14 @@ }, "recon_status": { "$ref": "#/components/schemas/ReconStatus" + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } } }, @@ -14036,7 +14052,8 @@ "display_sdk_only", "enabled_saved_payment_method", "hide_card_nickname_field", - "show_card_form_by_default" + "show_card_form_by_default", + "enable_button_only_on_form_ready" ], "properties": { "theme": { @@ -14160,6 +14177,10 @@ } }, "nullable": true + }, + "enable_button_only_on_form_ready": { + "type": "boolean", + "description": "Flag to enable the button only when the payment form is ready for submission" } } }, @@ -14297,6 +14318,11 @@ } }, "nullable": true + }, + "enable_button_only_on_form_ready": { + "type": "boolean", + "description": "Flag to enable the button only when the payment form is ready for submission", + "nullable": true } } }, diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 61bb7c009e3..b6f1e0a8b96 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2839,6 +2839,8 @@ pub struct PaymentLinkConfigRequest { pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + /// Flag to enable the button only when the payment form is ready for submission + pub enable_button_only_on_form_ready: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] @@ -2924,6 +2926,8 @@ pub struct PaymentLinkConfig { pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + /// Flag to enable the button only when the payment form is ready for submission + pub enable_button_only_on_form_ready: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index f9540fd08fc..8f5e5fc8b48 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7883,6 +7883,7 @@ pub struct PaymentLinkDetails { pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] @@ -7900,6 +7901,7 @@ pub struct SecurePaymentLinkDetails { pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 9d47ed7b594..384f7c7df24 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -653,6 +653,7 @@ pub struct PaymentLinkConfigRequest { pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub enable_button_only_on_form_ready: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index e51d8daa791..4f2f4c49ea1 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -193,6 +193,8 @@ pub struct PaymentLinkConfigRequestForPayments { /// Payment link configuration rules pub payment_link_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, + /// Flag to enable the button only when the payment form is ready for submission + pub enable_button_only_on_form_ready: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index fac251d8b68..65372d9f053 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -417,6 +417,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, + enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, } } fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest { @@ -440,6 +441,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, + enable_button_only_on_form_ready, } = self; api_models::admin::PaymentLinkConfigRequest { theme, @@ -467,6 +469,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, + enable_button_only_on_form_ready, } } } diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 57ec34227b0..247693864da 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -158,6 +158,9 @@ pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false; /// Default bool to enable saved payment method pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false; +/// [PaymentLink] Default bool for enabling button only when form is ready +pub const DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY: bool = false; + /// Default Merchant Logo Link pub const DEFAULT_MERCHANT_LOGO: &str = "https://live.hyperswitch.io/payment-link-assets/Merchant_placeholder.png"; diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 292f582df9a..c13e087947b 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -23,8 +23,9 @@ use super::{ use crate::{ consts::{ self, DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY, - DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_HIDE_CARD_NICKNAME_FIELD, - DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM, + DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, + DEFAULT_HIDE_CARD_NICKNAME_FIELD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, + DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM, }, errors::RouterResponse, get_payment_link_config_value, get_payment_link_config_value_based_on_priority, @@ -137,6 +138,7 @@ pub async fn form_payment_link_data( payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, + enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; @@ -290,6 +292,7 @@ pub async fn form_payment_link_data( payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), + enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, }; Ok(( @@ -348,6 +351,8 @@ pub async fn initiate_secure_payment_link_flow( payment_button_text_colour: payment_link_config.payment_button_text_colour, sdk_ui_rules: payment_link_config.sdk_ui_rules, payment_link_ui_rules: payment_link_config.payment_link_ui_rules, + enable_button_only_on_form_ready: payment_link_config + .enable_button_only_on_form_ready, }; let js_script = format!( "window.__PAYMENT_DETAILS = {}", @@ -634,6 +639,7 @@ pub fn get_payment_link_config_based_on_priority( enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, + enable_button_only_on_form_ready, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, @@ -647,7 +653,11 @@ pub fn get_payment_link_config_based_on_priority( DEFAULT_ENABLE_SAVED_PAYMENT_METHOD ), (hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD), - (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM) + (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM), + ( + enable_button_only_on_form_ready, + DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY + ) ); let ( @@ -702,6 +712,7 @@ pub fn get_payment_link_config_based_on_priority( payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, + enable_button_only_on_form_ready, }; Ok((payment_link_config, domain_name)) @@ -812,6 +823,7 @@ pub async fn get_payment_link_status( payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, + enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css index 7b347306809..f58617261d6 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css @@ -652,6 +652,10 @@ body { cursor: not-allowed; } +#submit.not-ready { + background-color: #C2C2C2 !important; +} + #submit-spinner { width: 28px; height: 28px; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html index 9abcc440068..ac04479e44c 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html @@ -290,9 +290,9 @@ <div></div> </div> </div> - <form id="payment-form" onclick="handleSubmit(); return false;"> + <form id="payment-form"> <div id="unified-checkout"></div> - <button id="submit" class="hidden"> + <button type="submit" id="submit" class="hidden"> <span id="submit-spinner" class="hidden"></span> <span id="submit-button-text"></span> </button> diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index 5b8267c57a9..e73e23076a9 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -257,7 +257,7 @@ function boot() { // Update payment link styles var paymentLinkUiRules = paymentDetails.payment_link_ui_rules; - if (paymentLinkUiRules !== null && typeof paymentLinkUiRules === "object" && Object.getPrototypeOf(paymentLinkUiRules) === Object.prototype) { + if (isObject(paymentLinkUiRules)) { updatePaymentLinkUi(paymentLinkUiRules); } @@ -279,7 +279,18 @@ function boot() { boot(); /** - * Use - add event listeners for changing UI on screen resize + * Use - checks if a given value is an object + * @param {any} val + * @returns {boolean} + */ +function isObject(val) { + return val !== null && typeof val === "object" && Object.getPrototypeOf(val) === Object.prototype +} + +/** + * Use - add event listeners for changing UI on + * - Screen resize + * - Form inputs * @param {PaymentDetails} paymentDetails */ function initializeEventListeners(paymentDetails) { @@ -384,17 +395,58 @@ function initializeEventListeners(paymentDetails) { // @ts-ignore window.state.isMobileView = currentWidth <= 1199; }); + + var paymentForm = document.getElementById("payment-form"); + if (paymentForm instanceof HTMLFormElement) { + paymentForm.addEventListener("submit", function (event) { + event.preventDefault(); + handleSubmit(event); + }) + } + + if (paymentDetails.enable_button_only_on_form_ready) { + handleFormReadyForSubmission(); + } +} + +function handleFormReadyForSubmission() { + window.addEventListener("message", function (event) { + // Event listener for updating the button rules + if (isObject(event.data) && event.data["isFormReadyForSubmission"] !== null) { + let isFormReadyForSubmission = event.data["isFormReadyForSubmission"]; + var submitButtonNode = document.getElementById("submit"); + if (submitButtonNode instanceof HTMLButtonElement) { + if (isFormReadyForSubmission === false) { + submitButtonNode.disabled = true; + addClass("#submit", "not-ready"); + addClass("#submit", "disabled"); + } else if (isFormReadyForSubmission === true) { + submitButtonNode.disabled = false; + removeClass("#submit", "not-ready"); + removeClass("#submit", "disabled"); + } + } + } + }); } /** * Trigger - post mounting SDK * Use - set relevant classes to elements in the doc for showing SDK **/ -function showSDK(display_sdk_only) { +function showSDK(display_sdk_only, enable_button_only_on_form_ready) { if (!display_sdk_only) { show("#hyper-checkout-details"); } show("#hyper-checkout-sdk"); + if (enable_button_only_on_form_ready) { + addClass("#submit", "not-ready"); + addClass("#submit", "disabled"); + var submitButtonNode = document.getElementById("submit"); + if (submitButtonNode instanceof HTMLButtonElement) { + submitButtonNode.disabled = true; + } + } show("#submit"); show("#unified-checkout"); hide("#sdk-spinner"); @@ -426,10 +478,11 @@ function handleSubmit(e) { // Update button loader hide("#submit-button-text"); show("#submit-spinner"); + addClass("#submit", "processing"); + addClass("#submit", "disabled"); var submitButtonNode = document.getElementById("submit"); if (submitButtonNode instanceof HTMLButtonElement) { submitButtonNode.disabled = true; - submitButtonNode.classList.add("disabled"); } hyper @@ -472,11 +525,12 @@ function handleSubmit(e) { console.error("Error confirming payment_intent", error); }) .finally(() => { + removeClass("#submit", "processing"); hide("#submit-spinner"); show("#submit-button-text"); + removeClass("#submit", "disabled"); if (submitButtonNode instanceof HTMLButtonElement) { submitButtonNode.disabled = false; - submitButtonNode.classList.remove("disabled"); } }); } diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js index ca6a944baaa..f9b0fe892cf 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -75,7 +75,7 @@ function initializeSDK() { // @ts-ignore mountUnifiedCheckout("#unified-checkout"); // @ts-ignore - showSDK(paymentDetails.display_sdk_only); + showSDK(paymentDetails.display_sdk_only, paymentDetails.enable_button_only_on_form_ready); let shimmer = document.getElementById("payment-details-shimmer"); shimmer.classList.add("reduce-opacity"); diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index 9b5a144d29a..12ae76a2085 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -98,7 +98,7 @@ if (!isFramed) { // @ts-ignore mountUnifiedCheckout("#unified-checkout"); // @ts-ignore - showSDK(paymentDetails.display_sdk_only); + showSDK(paymentDetails.display_sdk_only, paymentDetails.enable_button_only_on_form_ready); let shimmer = document.getElementById("payment-details-shimmer"); shimmer.classList.add("reduce-opacity"); diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index a34c137dbda..d6bb8f9bf0c 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4492,6 +4492,7 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour: config.payment_button_text_colour, sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, + enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, } } } @@ -4562,6 +4563,7 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> payment_button_text_colour: config.payment_button_text_colour, sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, + enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, } } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 5baf491cb33..f2f48a26f19 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -2174,6 +2174,7 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, + enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, } } } @@ -2204,6 +2205,7 @@ impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest> payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, + enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, } } }
2025-03-13T08:48:56Z
## Description This PR adds a payment link config for controlling the behavior or Submit button on payment links (`enable_button_only_on_form_ready`) - If `enable_button_only_on_form_ready` is true - disallow incomplete form submission - [DEFAULT and CURRENT] If false - allow incomplete form submission and throw validation errors ## Motivation and Context This helps add more granular control of the payment links UX. # #### Things to validate 1. Confirm button is greyed out and disabled if form is incomplete <img width="611" alt="Screenshot 2025-03-13 at 2 37 23 PM" src="https://github.com/user-attachments/assets/ffb1b4f2-6c78-4f9c-9080-f74e2bf4223d" /> 2. Confirm button is enabled once form is completely filled <img width="627" alt="Screenshot 2025-03-13 at 2 37 36 PM" src="https://github.com/user-attachments/assets/d4312682-0283-481f-9dfa-de6f0b525810" /> </details>
13c621ae62cda8f03ebd3958825b28a66b885234
Locally using local SDK changes <details> <summary>1. Update business profile to enable confirm button only when form is ready for submission</summary> cURL curl --location --request POST 'http://localhost:8080/account/merchant_1741692513/business_profile/pro_0pSrloAVzi0xbnpnP0mY' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{"is_connector_agnostic_mit_enabled":true,"is_network_tokenization_enabled":true,"payment_link_config":{"allowed_domains":["*"],"custom_message_for_card_terms":"Hello","enabled_saved_payment_method":true,"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","payment_button_text":"Proceed to Payment!","sdk_ui_rules":{".Label":{"fontWeight":"700 !important","fontSize":"13px !important","color":"#003264 !important","backgroundColor":"red !important","opacity":"1 !important"}},"branding_visibility":false,"business_specific_configs":{"style1":{"enabled_saved_payment_method":true,"theme":"#003264","logo":"https://hyperswitch.io/favicon.ico","display_sdk_only":true,"payment_button_text":"Confirmer","enable_button_only_on_form_ready":true,"custom_message_for_card_terms":"Pour vérifier votre compte, un montant de 0,00 € sera débité lorsque vous aurez cliqué sur le bouton « Confirmer »","sdk_ui_rules":{".Label":{"fontWeight":"600 !important","fontSize":"14px !important","color":"#003264 !important","opacity":"1 !important"},".Input":{"border":"1px solid #003264"},".Input::placeholder":{"fontWeight":"400","fontSize":"16px","color":"#00326480"},".TermsTextLabel":{"color":"#003264 !important","opacity":"1 !important"},".SaveWalletDetailsLabel":{"fontSize":"13px !important","color":"#003264 !important","opacity":"1 !important"},":has(> .TermsTextLabel)":{"opacity":"1 !important"},".SaveWalletDetailsLabel em":{"fontStyle":"normal"}},"payment_link_ui_rules":{"#submit":{"color":"#003264","fontWeight":"700","fontSize":"19px","padding":"25px 0","borderRadius":"5px","backgroundColor":"#FFA445"},"#hyper-checkout-sdk":{"backgroundColor":"#FFFFFF"}}},"style2":{"enabled_saved_payment_method":true,"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico"},"au":{"theme":"#2167AE","enable_button_only_on_form_ready":true,"payment_button_text":"Pay now","display_sdk_only":true,"payment_link_ui_rules":{"#submit":{"height":"48px","width":"max-content","borderRadius":"50px","padding":"0 20px","marginTop":"24px"},"#submit.processing":{"paddingLeft":"50px !important","paddingRight":"50px !important"}},"sdk_ui_rules":{".Tab":{"display":"none"},".Input, .Input:focus, .Input--invalid, .Input--empty":{"border":"none","boxShadow":"none","borderRadius":"0","padding":"0 !important","paddingBottom":"4px !important"},".Input, .Input:focus, .Input--empty":{"borderBottom":"1px solid #23366F !important","color":"#23366F"},".Input--invalid":{"borderBottom":"1px solid #CB4B40 !important"},".Label":{"marginLeft":"0","color":"#2167AE","opacity":"1 !important","fontSize":"12px !important"},".Label--invalid, .Input--invalid, .Error":{"color":"#CB4B40 !important","opacity":"1 !important"},".InputLogo--empty":{"color":"#979797"},".InputLogo":{"color":"#23366F","margin":"-30px"},".InputLogo--invalid":{"color":"#CB4B40"},".OrPayUsingLabel, .SaveWalletDetailsLabel, .CheckboxLabel, .TermsTextLabel, .InfoElement":{"color":"#003264 !important","opacity":"1 !important"},".OrPayUsingLine":{"backgroundColor":"#003264"}}}}}}' Response {"merchant_id":"merchant_1741692513","profile_id":"pro_0pSrloAVzi0xbnpnP0mY","profile_name":"IN_default","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"kFqRl8UUlHycFDeV4xy9ibEW1bDKgNa7vfd2iYfzgfzc6x3grTHhCb2V2IoMc9uL","redirect_to_merchant_with_http_post":false,"webhook_details":{"webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","webhook_url":"https://webhook.site/0728473e-e0aa-4bb6-9eea-85435cf54380","payment_created_enabled":true,"payment_succeeded_enabled":true,"payment_failed_enabled":true},"metadata":null,"routing_algorithm":null,"intent_fulfillment_time":900,"frm_routing_algorithm":null,"payout_routing_algorithm":null,"applepay_verified_domains":null,"session_expiry":900,"payment_link_config":{"domain_name":null,"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Proceed to Payment!","custom_message_for_card_terms":"Hello","payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Label":{"opacity":"1 !important","fontSize":"13px !important","backgroundColor":"red !important","color":"#003264 !important","fontWeight":"700 !important"}},"payment_link_ui_rules":null,"enable_button_only_on_form_ready":null,"business_specific_configs":{"style2":{"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":null,"custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":null,"payment_link_ui_rules":null,"enable_button_only_on_form_ready":null},"au":{"theme":"#2167AE","logo":null,"seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":null,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Pay now","custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Input, .Input:focus, .Input--invalid, .Input--empty":{"border":"none","padding":"0 !important","boxShadow":"none","borderRadius":"0","paddingBottom":"4px !important"},".Input--invalid":{"borderBottom":"1px solid #CB4B40 !important"},".Tab":{"display":"none"},".Input, .Input:focus, .Input--empty":{"color":"#23366F","borderBottom":"1px solid #23366F !important"},".OrPayUsingLabel, .SaveWalletDetailsLabel, .CheckboxLabel, .TermsTextLabel, .InfoElement":{"opacity":"1 !important","color":"#003264 !important"},".OrPayUsingLine":{"backgroundColor":"#003264"},".Label--invalid::after":{"color":"#CB4B40","content":"' *'"},".Label":{"opacity":"1 !important","color":"#2167AE","marginLeft":"0","fontSize":"12px !important"},".InputLogo":{"color":"#23366F","margin":"-30px"},".Label::after":{"content":"' *'","color":"#23366F"},".InputLogo--empty":{"color":"#979797"},".InputLogo--invalid":{"color":"#CB4B40"},".Label--invalid, .Input--invalid, .Error":{"opacity":"1 !important","color":"#CB4B40 !important"}},"payment_link_ui_rules":{"#submit":{"borderRadius":"50px","height":"48px","width":"max-content","padding":"0 20px","marginTop":"24px"},"#submit.processing":{"paddingLeft":"50px !important","paddingRight":"50px !important"}},"enable_button_only_on_form_ready":true},"style1":{"theme":"#003264","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Confirmer","custom_message_for_card_terms":"Pour vérifier votre compte, un montant de 0,00 € sera débité lorsque vous aurez cliqué sur le bouton « Confirmer »","payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".TermsTextLabel":{"opacity":"1 !important","color":"#003264 !important"},".Input":{"border":"1px solid #003264"},".Label":{"opacity":"1 !important","color":"#003264 !important","fontSize":"14px !important","fontWeight":"600 !important"},".Input::placeholder":{"color":"#00326480","fontSize":"16px","fontWeight":"400"},".SaveWalletDetailsLabel":{"fontSize":"13px !important","color":"#003264 !important","opacity":"1 !important"},":has(> .TermsTextLabel)":{"opacity":"1 !important"},".SaveWalletDetailsLabel em":{"fontStyle":"normal"}},"payment_link_ui_rules":{"#submit":{"color":"#003264","padding":"25px 0","fontSize":"19px","fontWeight":"700","borderRadius":"5px","backgroundColor":"#FFA445"},"#hyper-checkout-sdk":{"backgroundColor":"#FFFFFF"}},"enable_button_only_on_form_ready":true}},"allowed_domains":["*"],"branding_visibility":false},"authentication_connector_details":null,"use_billing_as_payment_method_billing":true,"extended_card_info_config":null,"collect_shipping_details_from_wallet_connector":false,"collect_billing_details_from_wallet_connector":false,"always_collect_shipping_details_from_wallet_connector":false,"always_collect_billing_details_from_wallet_connector":false,"is_connector_agnostic_mit_enabled":true,"payout_link_config":null,"outgoing_webhook_custom_http_headers":null,"tax_connector_id":null,"is_tax_connector_enabled":false,"is_network_tokenization_enabled":true,"is_auto_retries_enabled":false,"max_auto_retries_enabled":null,"always_request_extended_authorization":null,"is_click_to_pay_enabled":false,"authentication_product_ids":null,"card_testing_guard_config":{"card_ip_blocking_status":"disabled","card_ip_blocking_threshold":3,"guest_user_card_blocking_status":"disabled","guest_user_card_blocking_threshold":10,"customer_id_blocking_status":"disabled","customer_id_blocking_threshold":5,"card_testing_guard_expiry":3600},"is_clear_pan_retries_enabled":false,"force_3ds_challenge":false} </details> <details> <summary>2. Create payment link</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sI7y2RBalVSE3nYh5k4Gs2WGws277uoKwu3Y7gM9y2U2dmDSVymbHUAqPt3zDsHr' \ --data-raw '{"customer_id":"cus_t0I7DMr69stOdG3QaLZP","profile_id":"pro_0pSrloAVzi0xbnpnP0mY","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":100,"currency":"USD","payment_link":true,"capture_method":"automatic","email":"[email protected]","session_expiry":100000,"return_url":"https://example.com"}' Response {"payment_id":"pay_ufjEW9U5WAea89stlSED","merchant_id":"merchant_1741692513","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_ufjEW9U5WAea89stlSED_secret_eg6sZLpO9LH60crrsV0I","created":"2025-03-13T08:47:48.496Z","currency":"USD","customer_id":"cus_t0I7DMr69stOdG3QaLZP","customer":{"id":"cus_t0I7DMr69stOdG3QaLZP","name":"John Nether","email":"[email protected]","phone":"6168205362","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Nether","phone":"6168205362","return_url":"https://example.com/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_t0I7DMr69stOdG3QaLZP","created_at":1741855668,"expires":1741859268,"secret":"epk_3ccf7b98c7c54188ba5d9230c3bd21fe"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1741692513/pay_ufjEW9U5WAea89stlSED?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1741692513/pay_ufjEW9U5WAea89stlSED?locale=en","payment_link_id":"plink_fW4Nnwl7EcbrmjmOQ1pi"},"profile_id":"pro_0pSrloAVzi0xbnpnP0mY","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-03-14T12:34:28.493Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-03-13T08:47:48.504Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null} #### Things to validate 1. Confirm button is greyed out and disabled if form is incomplete <img width="611" alt="Screenshot 2025-03-13 at 2 37 23 PM" src="https://github.com/user-attachments/assets/ffb1b4f2-6c78-4f9c-9080-f74e2bf4223d" /> 2. Confirm button is enabled once form is completely filled <img width="627" alt="Screenshot 2025-03-13 at 2 37 36 PM" src="https://github.com/user-attachments/assets/d4312682-0283-481f-9dfa-de6f0b525810" /> </details>
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/admin.rs", "crates/api_models/src/payments.rs", "crates/diesel_models/src/business_profile.rs", "crates/diesel_models/src/payment_intent.rs", "crates/hyperswitch_domain_models/src/lib.rs", "crates/router/src/consts.rs", "crates/router/src/core/payment_link.rs", "crates/router/src/core/payment_link/payment_link_initiate/payment_link.css", "crates/router/src/core/payment_link/payment_link_initiate/payment_link.html", "crates/router/src/core/payment_link/payment_link_initiate/payment_link.js", "crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js", "crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js", "crates/router/src/core/payments/transformers.rs", "crates/router/src/types/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7511
Bug: [CHORE] Update Globalpay configs with the countries and currencies that it supports The connector has been untouched for long. The connector is not supported supported everywhere. So, it is better for us to restrict it to certain countries that it supports.
diff --git a/config/config.example.toml b/config/config.example.toml index ad910ef415a..115dd4554a3 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -614,6 +614,14 @@ direct_carrier_billing = {country = "MA, CM, ZA, EG, SN, DZ, TN, ML, GN, GH, LY, credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [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 = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 47b65efabc4..a6e531b2aa6 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -322,6 +322,14 @@ debit.currency = "USD" credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.globepay] ali_pay.currency = "GBP,CNY" we_chat_pay.currency = "GBP,CNY" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index fc4bca222a9..959d2bf7fe9 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -372,6 +372,14 @@ debit.currency = "USD" credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC"} +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC"} +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.globepay] ali_pay.currency = "GBP,CNY" we_chat_pay.currency = "GBP,CNY" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 37346fc3467..e919a0fa566 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -374,6 +374,14 @@ debit.currency = "USD" credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC"} +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.globepay] ali_pay.currency = "GBP,CNY" we_chat_pay.currency = "GBP,CNY" diff --git a/config/development.toml b/config/development.toml index eab89187a46..57e0ebef051 100644 --- a/config/development.toml +++ b/config/development.toml @@ -587,6 +587,14 @@ paypal = { currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,N credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.jpmorgan] debit = { country = "CA, GB, US, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE", currency = "USD, EUR, GBP, AUD, NZD, SGD, CAD, JPY, HKD, KRW, TWD, MXN, BRL, DKK, NOK, ZAR, SEK, CHF, CZK, PLN, TRY, AFN, ALL, DZD, AOA, ARS, AMD, AWG, AZN, BSD, BDT, BBD, BYN, BZD, BMD, BOB, BAM, BWP, BND, BGN, BIF, BTN, XOF, XAF, XPF, KHR, CVE, KYD, CLP, CNY, COP, KMF, CDF, CRC, HRK, DJF, DOP, XCD, EGP, ETB, FKP, FJD, GMD, GEL, GHS, GIP, GTQ, GYD, HTG, HNL, HUF, ISK, INR, IDR, ILS, JMD, KZT, KES, LAK, LBP, LSL, LRD, MOP, MKD, MGA, MWK, MYR, MVR, MRU, MUR, MDL, MNT, MAD, MZN, MMK, NAD, NPR, ANG, PGK, NIO, NGN, PKR, PAB, PYG, PEN, PHP, QAR, RON, RWF, SHP, WST, STN, SAR, RSD, SCR, SLL, SBD, SOS, LKR, SRD, SZL, TJS, TZS, THB, TOP, TTD, UGX, UAH, AED, UYU, UZS, VUV, VND, YER, ZMW" } credit = { country = "CA, GB, US, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE", currency = "USD, EUR, GBP, AUD, NZD, SGD, CAD, JPY, HKD, KRW, TWD, MXN, BRL, DKK, NOK, ZAR, SEK, CHF, CZK, PLN, TRY, AFN, ALL, DZD, AOA, ARS, AMD, AWG, AZN, BSD, BDT, BBD, BYN, BZD, BMD, BOB, BAM, BWP, BND, BGN, BIF, BTN, XOF, XAF, XPF, KHR, CVE, KYD, CLP, CNY, COP, KMF, CDF, CRC, HRK, DJF, DOP, XCD, EGP, ETB, FKP, FJD, GMD, GEL, GHS, GIP, GTQ, GYD, HTG, HNL, HUF, ISK, INR, IDR, ILS, JMD, KZT, KES, LAK, LBP, LSL, LRD, MOP, MKD, MGA, MWK, MYR, MVR, MRU, MUR, MDL, MNT, MAD, MZN, MMK, NAD, NPR, ANG, PGK, NIO, NGN, PKR, PAB, PYG, PEN, PHP, QAR, RON, RWF, SHP, WST, STN, SAR, RSD, SCR, SLL, SBD, SOS, LKR, SRD, SZL, TJS, TZS, THB, TOP, TTD, UGX, UAH, AED, UYU, UZS, VUV, VND, YER, ZMW" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9a24adcd5e9..8982fbb5bd4 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -557,6 +557,14 @@ paypal = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,B credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [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 = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 296bdbd9ddc..ef291f169c1 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -501,10 +501,12 @@ pub enum Currency { CAD, CDF, CHF, + CLF, CLP, CNY, COP, CRC, + CUC, CUP, CVE, CZK, @@ -600,6 +602,7 @@ pub enum Currency { SOS, SRD, SSP, + STD, STN, SVC, SYP, @@ -711,9 +714,11 @@ impl Currency { Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", + Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", + Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", @@ -810,6 +815,7 @@ impl Currency { Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", + Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", @@ -889,9 +895,11 @@ impl Currency { | Self::CAD | Self::CDF | Self::CHF + | Self::CLF | Self::CNY | Self::COP | Self::CRC + | Self::CUC | Self::CUP | Self::CVE | Self::CZK @@ -978,6 +986,7 @@ impl Currency { | Self::SOS | Self::SRD | Self::SSP + | Self::STD | Self::STN | Self::SVC | Self::SYP @@ -1037,10 +1046,12 @@ impl Currency { | Self::CAD | Self::CDF | Self::CHF + | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC + | Self::CUC | Self::CUP | Self::CVE | Self::CZK @@ -1131,6 +1142,7 @@ impl Currency { | Self::SOS | Self::SRD | Self::SSP + | Self::STD | Self::STN | Self::SVC | Self::SYP @@ -1163,11 +1175,178 @@ impl Currency { } } + pub fn is_four_decimal_currency(self) -> bool { + match self { + Self::CLF => true, + Self::AED + | Self::AFN + | Self::ALL + | Self::AMD + | Self::AOA + | Self::ANG + | Self::ARS + | Self::AUD + | Self::AWG + | Self::AZN + | Self::BAM + | Self::BBD + | Self::BDT + | Self::BGN + | Self::BHD + | Self::BIF + | Self::BMD + | Self::BND + | Self::BOB + | Self::BRL + | Self::BSD + | Self::BTN + | Self::BWP + | Self::BYN + | Self::BZD + | Self::CAD + | Self::CDF + | Self::CHF + | Self::CLP + | Self::CNY + | Self::COP + | Self::CRC + | Self::CUC + | Self::CUP + | Self::CVE + | Self::CZK + | Self::DJF + | Self::DKK + | Self::DOP + | Self::DZD + | Self::EGP + | Self::ERN + | Self::ETB + | Self::EUR + | Self::FJD + | Self::FKP + | Self::GBP + | Self::GEL + | Self::GHS + | Self::GIP + | Self::GMD + | Self::GNF + | Self::GTQ + | Self::GYD + | Self::HKD + | Self::HNL + | Self::HRK + | Self::HTG + | Self::HUF + | Self::IDR + | Self::ILS + | Self::INR + | Self::IQD + | Self::IRR + | Self::ISK + | Self::JMD + | Self::JOD + | Self::JPY + | Self::KES + | Self::KGS + | Self::KHR + | Self::KMF + | Self::KPW + | Self::KRW + | Self::KWD + | Self::KYD + | Self::KZT + | Self::LAK + | Self::LBP + | Self::LKR + | Self::LRD + | Self::LSL + | Self::LYD + | Self::MAD + | Self::MDL + | Self::MGA + | Self::MKD + | Self::MMK + | Self::MNT + | Self::MOP + | Self::MRU + | Self::MUR + | Self::MVR + | Self::MWK + | Self::MXN + | Self::MYR + | Self::MZN + | Self::NAD + | Self::NGN + | Self::NIO + | Self::NOK + | Self::NPR + | Self::NZD + | Self::OMR + | Self::PAB + | Self::PEN + | Self::PGK + | Self::PHP + | Self::PKR + | Self::PLN + | Self::PYG + | Self::QAR + | Self::RON + | Self::RSD + | Self::RUB + | Self::RWF + | Self::SAR + | Self::SBD + | Self::SCR + | Self::SDG + | Self::SEK + | Self::SGD + | Self::SHP + | Self::SLE + | Self::SLL + | Self::SOS + | Self::SRD + | Self::SSP + | Self::STD + | Self::STN + | Self::SVC + | Self::SYP + | Self::SZL + | Self::THB + | Self::TJS + | Self::TMT + | Self::TND + | Self::TOP + | Self::TRY + | Self::TTD + | Self::TWD + | Self::TZS + | Self::UAH + | Self::UGX + | Self::USD + | Self::UYU + | Self::UZS + | Self::VES + | Self::VND + | Self::VUV + | Self::WST + | Self::XAF + | Self::XCD + | Self::XPF + | Self::XOF + | Self::YER + | Self::ZAR + | Self::ZMW + | Self::ZWL => false, + } + } + pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 + } else if self.is_four_decimal_currency() { + 4 } else { 2 } diff --git a/crates/currency_conversion/src/types.rs b/crates/currency_conversion/src/types.rs index 2001495b2db..587c36ffe6c 100644 --- a/crates/currency_conversion/src/types.rs +++ b/crates/currency_conversion/src/types.rs @@ -105,10 +105,12 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::CAD => iso::CAD, Currency::CDF => iso::CDF, Currency::CHF => iso::CHF, + Currency::CLF => iso::CLF, Currency::CLP => iso::CLP, Currency::CNY => iso::CNY, Currency::COP => iso::COP, Currency::CRC => iso::CRC, + Currency::CUC => iso::CUC, Currency::CUP => iso::CUP, Currency::CVE => iso::CVE, Currency::CZK => iso::CZK, @@ -204,6 +206,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::SOS => iso::SOS, Currency::SRD => iso::SRD, Currency::SSP => iso::SSP, + Currency::STD => iso::STD, Currency::STN => iso::STN, Currency::SVC => iso::SVC, Currency::SYP => iso::SYP, diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 0479753d8d0..94faa4847df 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -370,10 +370,12 @@ impl IntoDirValue for api_enums::Currency { Self::CAD => Ok(dirval!(PaymentCurrency = CAD)), Self::CDF => Ok(dirval!(PaymentCurrency = CDF)), Self::CHF => Ok(dirval!(PaymentCurrency = CHF)), + Self::CLF => Ok(dirval!(PaymentCurrency = CLF)), Self::CLP => Ok(dirval!(PaymentCurrency = CLP)), Self::CNY => Ok(dirval!(PaymentCurrency = CNY)), Self::COP => Ok(dirval!(PaymentCurrency = COP)), Self::CRC => Ok(dirval!(PaymentCurrency = CRC)), + Self::CUC => Ok(dirval!(PaymentCurrency = CUC)), Self::CUP => Ok(dirval!(PaymentCurrency = CUP)), Self::CVE => Ok(dirval!(PaymentCurrency = CVE)), Self::CZK => Ok(dirval!(PaymentCurrency = CZK)), @@ -469,6 +471,7 @@ impl IntoDirValue for api_enums::Currency { Self::SOS => Ok(dirval!(PaymentCurrency = SOS)), Self::SRD => Ok(dirval!(PaymentCurrency = SRD)), Self::SSP => Ok(dirval!(PaymentCurrency = SSP)), + Self::STD => Ok(dirval!(PaymentCurrency = STD)), Self::STN => Ok(dirval!(PaymentCurrency = STN)), Self::SVC => Ok(dirval!(PaymentCurrency = SVC)), Self::SYP => Ok(dirval!(PaymentCurrency = SYP)), diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index bdf46a8ee40..edc62676154 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -342,6 +342,14 @@ pix = { country = "BR", currency = "BRL" } red_compra = { country = "CL", currency = "CLP" } red_pagos = { country = "UY", currency = "UYU" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.rapyd] apple_pay = { country = "AL,AS,AD,AR,AM,AU,AT,AZ,BH,BE,BM,BA,BR,BG,CA,KH,KY,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GI,GR,GL,GU,GT,GG,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KG,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NI,MK,MP,NO,PA,PY,PR,PE,PL,PT,QA,RO,SM,RS,SG,SK,SI,ZA,ES,SE,CH,TW,TJ,TH,UA,AE,GB,US,UY,VI,VN", currency = "EUR,GBP,ISK,USD" } google_pay = { country = "AM,AT,AU,AZ,BA,BE,BG,BY,CA,CH,CL,CN,CO,CR,CY,CZ,DE,DK,DO,EC,EE,EG,ES,FI,FR,GB,GE,GL,GR,GT,HK,HN,HR,HU,IE,IL,IM,IS,IT,JE,JP,JO,KZ,KW,LA,LI,LT,LU,LV,MA,MC,MD,ME,MO,MN,MT,MX,MY,NC,NL,NO,NZ,OM,PA,PE,PL,PR,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,SV,TH,TW,UA,US,UY,VA,VN,ZA", currency = "EUR,GBP,ISK,USD" }
2025-03-13T07:57:41Z
## Description <!-- Describe your changes in detail --> This PR adds necessary payment method configs to the GlobalPay connector. For wallets (Paypal, Apple Pay and Google Pay), their developer docs does not mention about them being support while their main page says it to be supported. Have got in touch with the team asking for clarification on this topic. Will update the wallet configs accordingly in upcoming PRs. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes https://github.com/juspay/hyperswitch/issues/7511 Refer to the parent issue of the attached issue to learn more about supported currencies and countries. Supported payment types: https://github.com/juspay/hyperswitch/issues/7502#issuecomment-2718463863 #
13c621ae62cda8f03ebd3958825b28a66b885234
Payments via GlobalPay should fail if currencies or countries that are not supported is used to make transactions: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_fO6IOJVOk6dmWoDhkHnw3EzJHjZytuOfViMDKpi1eOasWTqrXIcUuuoGNUDafqGZ' \ --data-raw '{ "amount": 1000, "currency": "XPS", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4263970000005262", "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": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } } }' ``` ```json { "error": { "error_type": "invalid_request", "message": "Json deserialize error: unknown variant `XPS`, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLF`, `CLP`, `CNY`, `COP`, `CRC`, `CUC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STD`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL` at line 3 column 19", "code": "IR_06" } } ``` bank redirect: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_fO6IOJVOk6dmWoDhkHnw3EzJHjZytuOfViMDKpi1eOasWTqrXIcUuuoGNUDafqGZ' \ --data-raw '{ "amount": 1000, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_data": { "bank_redirect": { "ideal": { "bank_name": "ing" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "PiX" } } }' ``` ```json { "error": { "type": "invalid_request", "message": "No eligible connector was found for the current payment method configuration", "code": "IR_39" } } ``` without this change, the payment would fail and the connector would throw `INVALID_REQUEST_DATA`
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/common_enums/src/enums.rs", "crates/currency_conversion/src/types.rs", "crates/kgraph_utils/src/transformers.rs", "loadtest/config/development.toml" ]
juspay/hyperswitch
juspay__hyperswitch-7520
Bug: [FEATURE]: Add diesel model support as a part of refunds implementation for v2 apis. Add diesel model and storage impl support as a part of refunds implementation for v2 apis.
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index 4f02cc4aea8..94913571396 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -14,6 +14,7 @@ v1 = ["common_utils/v1"] v2 = ["common_utils/v2"] customer_v2 = [] payment_methods_v2 = [] +refunds_v2 = [] [dependencies] async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index 54e60891532..260b0e4c86a 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -133,9 +133,14 @@ impl DBOperation { ) .await?, )), + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?)) } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + Updateable::RefundUpdate(a) => { + DBResult::Refund(Box::new(a.orig.update_with_id(conn, a.update_data).await?)) + } Updateable::AddressUpdate(a) => { DBResult::Address(Box::new(a.orig.update(conn, a.update_data).await?)) } diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs index 902916bf98f..adae21c413f 100644 --- a/crates/diesel_models/src/query/refund.rs +++ b/crates/diesel_models/src/query/refund.rs @@ -3,10 +3,19 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, T use super::generics; use crate::{ errors, - refund::{Refund, RefundNew, RefundUpdate, RefundUpdateInternal}, - schema::refund::dsl, + refund::{RefundUpdate, RefundUpdateInternal}, PgPooledConn, StorageResult, }; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +use crate::{ + refund::{Refund, RefundNew}, + schema::refund::dsl, +}; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use crate::{ + refund::{Refund, RefundNew}, + schema_v2::refund::dsl, +}; impl RefundNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Refund> { @@ -14,6 +23,7 @@ impl RefundNew { } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl Refund { pub async fn update(self, conn: &PgPooledConn, refund: RefundUpdate) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< @@ -127,3 +137,37 @@ impl Refund { .await } } + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl Refund { + pub async fn update_with_id( + self, + conn: &PgPooledConn, + refund: RefundUpdate, + ) -> StorageResult<Self> { + match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( + conn, + self.id.to_owned(), + RefundUpdateInternal::from(refund), + ) + .await + { + Err(error) => match error.current_context() { + errors::DatabaseError::NoFieldsToUpdate => Ok(self), + _ => Err(error), + }, + result => result, + } + } + + pub async fn find_by_global_id( + conn: &PgPooledConn, + id: &common_utils::id_type::GlobalRefundId, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::id.eq(id.to_owned()), + ) + .await + } +} diff --git a/crates/diesel_models/src/query/user/sample_data.rs b/crates/diesel_models/src/query/user/sample_data.rs index b97ea39b82d..8ef4b1e9303 100644 --- a/crates/diesel_models/src/query/user/sample_data.rs +++ b/crates/diesel_models/src/query/user/sample_data.rs @@ -6,16 +6,16 @@ use router_env::logger; #[cfg(feature = "v1")] use crate::schema::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, + refund::dsl as refund_dsl, }; #[cfg(feature = "v2")] use crate::schema_v2::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, + refund::dsl as refund_dsl, }; use crate::{ - errors, - schema::{dispute::dsl as dispute_dsl, refund::dsl as refund_dsl}, - user, Dispute, DisputeNew, PaymentAttempt, PaymentIntent, PaymentIntentNew, PgPooledConn, - Refund, RefundNew, StorageResult, + errors, schema::dispute::dsl as dispute_dsl, user, Dispute, DisputeNew, PaymentAttempt, + PaymentIntent, PaymentIntentNew, PgPooledConn, Refund, RefundNew, StorageResult, }; #[cfg(feature = "v1")] diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index ee598bebd2f..6a40baba9dd 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -6,8 +6,13 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums as storage_enums, schema::refund}; +use crate::enums as storage_enums; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +use crate::schema::refund; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use crate::schema_v2::refund; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive( Clone, Debug, @@ -64,6 +69,58 @@ pub struct Refund { pub issuer_error_message: Option<String>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive( + Clone, + Debug, + Eq, + Identifiable, + Queryable, + Selectable, + PartialEq, + serde::Serialize, + serde::Deserialize, +)] +#[diesel(table_name = refund, primary_key(id), check_for_backend(diesel::pg::Pg))] +pub struct Refund { + pub payment_id: common_utils::id_type::GlobalPaymentId, + pub merchant_id: common_utils::id_type::MerchantId, + pub connector_transaction_id: ConnectorTransactionId, + pub connector: String, + pub connector_refund_id: Option<ConnectorTransactionId>, + pub external_reference_id: Option<String>, + pub refund_type: storage_enums::RefundType, + pub total_amount: MinorUnit, + pub currency: storage_enums::Currency, + pub refund_amount: MinorUnit, + pub refund_status: storage_enums::RefundStatus, + pub sent_to_gateway: bool, + pub refund_error_message: Option<String>, + pub metadata: Option<pii::SecretSerdeValue>, + pub refund_arn: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, + pub description: Option<String>, + pub attempt_id: common_utils::id_type::GlobalAttemptId, + pub refund_reason: Option<String>, + pub refund_error_code: Option<String>, + pub profile_id: Option<common_utils::id_type::ProfileId>, + pub updated_by: String, + pub charges: Option<ChargeRefunds>, + pub organization_id: common_utils::id_type::OrganizationId, + 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>, + pub id: common_utils::id_type::GlobalRefundId, + pub merchant_reference_id: common_utils::id_type::RefundReferenceId, + pub connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive( Clone, Debug, @@ -110,6 +167,54 @@ pub struct RefundNew { pub processor_transaction_data: Option<String>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive( + Clone, + Debug, + Eq, + PartialEq, + Insertable, + router_derive::DebugAsDisplay, + serde::Serialize, + serde::Deserialize, + router_derive::Setter, +)] +#[diesel(table_name = refund)] +pub struct RefundNew { + pub merchant_reference_id: common_utils::id_type::RefundReferenceId, + pub payment_id: common_utils::id_type::GlobalPaymentId, + pub merchant_id: common_utils::id_type::MerchantId, + pub id: common_utils::id_type::GlobalRefundId, + pub external_reference_id: Option<String>, + pub connector_transaction_id: ConnectorTransactionId, + pub connector: String, + pub connector_refund_id: Option<ConnectorTransactionId>, + pub refund_type: storage_enums::RefundType, + pub total_amount: MinorUnit, + pub currency: storage_enums::Currency, + pub refund_amount: MinorUnit, + pub refund_status: storage_enums::RefundStatus, + pub sent_to_gateway: bool, + pub metadata: Option<pii::SecretSerdeValue>, + pub refund_arn: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, + pub description: Option<String>, + pub attempt_id: common_utils::id_type::GlobalAttemptId, + pub refund_reason: Option<String>, + pub profile_id: Option<common_utils::id_type::ProfileId>, + pub updated_by: String, + pub connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub charges: Option<ChargeRefunds>, + pub organization_id: common_utils::id_type::OrganizationId, + pub split_refunds: Option<common_types::refunds::SplitRefund>, + pub processor_refund_data: Option<String>, + pub processor_transaction_data: Option<String>, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { @@ -153,6 +258,49 @@ pub enum RefundUpdate { }, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum RefundUpdate { + Update { + connector_refund_id: ConnectorTransactionId, + refund_status: storage_enums::RefundStatus, + sent_to_gateway: bool, + refund_error_message: Option<String>, + refund_arn: String, + updated_by: String, + processor_refund_data: Option<String>, + }, + MetadataAndReasonUpdate { + metadata: Option<pii::SecretSerdeValue>, + reason: Option<String>, + updated_by: String, + }, + StatusUpdate { + connector_refund_id: Option<ConnectorTransactionId>, + sent_to_gateway: bool, + refund_status: storage_enums::RefundStatus, + updated_by: String, + processor_refund_data: Option<String>, + }, + ErrorUpdate { + refund_status: Option<storage_enums::RefundStatus>, + refund_error_message: Option<String>, + refund_error_code: Option<String>, + updated_by: String, + connector_refund_id: Option<ConnectorTransactionId>, + processor_refund_data: Option<String>, + unified_code: Option<String>, + unified_message: Option<String>, + }, + ManualUpdate { + refund_status: Option<storage_enums::RefundStatus>, + refund_error_message: Option<String>, + refund_error_code: Option<String>, + updated_by: String, + }, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { @@ -173,6 +321,48 @@ pub struct RefundUpdateInternal { issuer_error_message: Option<String>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[diesel(table_name = refund)] +pub struct RefundUpdateInternal { + connector_refund_id: Option<ConnectorTransactionId>, + refund_status: Option<storage_enums::RefundStatus>, + sent_to_gateway: Option<bool>, + refund_error_message: Option<String>, + refund_arn: Option<String>, + metadata: Option<pii::SecretSerdeValue>, + refund_reason: Option<String>, + refund_error_code: Option<String>, + updated_by: String, + modified_at: PrimitiveDateTime, + processor_refund_data: Option<String>, + unified_code: Option<String>, + unified_message: Option<String>, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +impl RefundUpdateInternal { + pub fn create_refund(self, source: Refund) -> Refund { + Refund { + connector_refund_id: self.connector_refund_id, + refund_status: self.refund_status.unwrap_or_default(), + sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), + refund_error_message: self.refund_error_message, + refund_arn: self.refund_arn, + metadata: self.metadata, + refund_reason: self.refund_reason, + refund_error_code: self.refund_error_code, + updated_by: self.updated_by, + modified_at: self.modified_at, + processor_refund_data: self.processor_refund_data, + unified_code: self.unified_code, + unified_message: self.unified_message, + ..source + } + } +} + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] impl RefundUpdateInternal { pub fn create_refund(self, source: Refund) -> Refund { Refund { @@ -194,6 +384,7 @@ impl RefundUpdateInternal { } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update { @@ -320,6 +511,122 @@ impl From<RefundUpdate> for RefundUpdateInternal { } } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl From<RefundUpdate> for RefundUpdateInternal { + fn from(refund_update: RefundUpdate) -> Self { + match refund_update { + RefundUpdate::Update { + connector_refund_id, + refund_status, + sent_to_gateway, + refund_error_message, + refund_arn, + updated_by, + processor_refund_data, + } => Self { + connector_refund_id: Some(connector_refund_id), + refund_status: Some(refund_status), + sent_to_gateway: Some(sent_to_gateway), + refund_error_message, + refund_arn: Some(refund_arn), + updated_by, + processor_refund_data, + metadata: None, + refund_reason: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), + unified_code: None, + unified_message: None, + }, + RefundUpdate::MetadataAndReasonUpdate { + metadata, + reason, + updated_by, + } => Self { + metadata, + refund_reason: reason, + updated_by, + connector_refund_id: None, + refund_status: None, + sent_to_gateway: None, + refund_error_message: None, + refund_arn: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), + processor_refund_data: None, + unified_code: None, + unified_message: None, + }, + RefundUpdate::StatusUpdate { + connector_refund_id, + sent_to_gateway, + refund_status, + updated_by, + processor_refund_data, + } => Self { + connector_refund_id, + sent_to_gateway: Some(sent_to_gateway), + refund_status: Some(refund_status), + updated_by, + processor_refund_data, + refund_error_message: None, + refund_arn: None, + metadata: None, + refund_reason: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), + unified_code: None, + unified_message: None, + }, + RefundUpdate::ErrorUpdate { + refund_status, + refund_error_message, + refund_error_code, + unified_code, + unified_message, + updated_by, + connector_refund_id, + processor_refund_data, + } => Self { + refund_status, + refund_error_message, + refund_error_code, + updated_by, + connector_refund_id, + processor_refund_data, + sent_to_gateway: None, + refund_arn: None, + metadata: None, + refund_reason: None, + modified_at: common_utils::date_time::now(), + unified_code, + unified_message, + }, + RefundUpdate::ManualUpdate { + refund_status, + refund_error_message, + refund_error_code, + updated_by, + } => Self { + refund_status, + refund_error_message, + refund_error_code, + updated_by, + connector_refund_id: None, + sent_to_gateway: None, + refund_arn: None, + metadata: None, + refund_reason: None, + modified_at: common_utils::date_time::now(), + processor_refund_data: None, + unified_code: None, + unified_message: None, + }, + } + } +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl RefundUpdate { pub fn apply_changeset(self, source: Refund) -> Refund { let RefundUpdateInternal { @@ -360,6 +667,43 @@ impl RefundUpdate { } } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl RefundUpdate { + pub fn apply_changeset(self, source: Refund) -> Refund { + let RefundUpdateInternal { + connector_refund_id, + refund_status, + sent_to_gateway, + refund_error_message, + refund_arn, + metadata, + refund_reason, + refund_error_code, + updated_by, + modified_at: _, + processor_refund_data, + unified_code, + unified_message, + } = self.into(); + Refund { + connector_refund_id: connector_refund_id.or(source.connector_refund_id), + refund_status: refund_status.unwrap_or(source.refund_status), + sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway), + refund_error_message: refund_error_message.or(source.refund_error_message), + refund_error_code: refund_error_code.or(source.refund_error_code), + refund_arn: refund_arn.or(source.refund_arn), + metadata: metadata.or(source.metadata), + refund_reason: refund_reason.or(source.refund_reason), + updated_by, + modified_at: common_utils::date_time::now(), + 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 + } + } +} + #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, @@ -379,6 +723,16 @@ impl common_utils::events::ApiEventMetric for Refund { } } +#[cfg(feature = "v2")] +impl common_utils::events::ApiEventMetric for Refund { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Refund { + payment_id: self.payment_id.clone(), + refund_id: self.id.clone(), + }) + } +} + impl ConnectorTransactionIdTrait for Refund { fn get_optional_connector_refund_id(&self) -> Option<&String> { match self diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 5d028ad5214..d97d4fec68a 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1160,11 +1160,7 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - refund (merchant_id, refund_id) { - #[max_length = 64] - internal_reference_id -> Varchar, - #[max_length = 64] - refund_id -> Varchar, + refund (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] @@ -1200,8 +1196,6 @@ diesel::table! { profile_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, - #[max_length = 32] - merchant_connector_id -> Nullable<Varchar>, charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, @@ -1212,6 +1206,12 @@ diesel::table! { unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + merchant_reference_id -> Varchar, + #[max_length = 64] + connector_id -> Nullable<Varchar>, } } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 2012028169c..780d4509db7 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,12 +33,13 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] -v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","scheduler/v2"] +v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","refunds_v2","scheduler/v2"] v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1","scheduler/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery","hyperswitch_connectors/revenue_recovery"] +refunds_v2 = ["diesel_models/refunds_v2", "storage_impl/refunds_v2"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request. diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index d06d13a3123..9b72ba26c26 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2647,6 +2647,7 @@ impl CaptureInterface for KafkaStore { #[async_trait::async_trait] impl RefundInterface for KafkaStore { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, @@ -2662,6 +2663,7 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -2673,6 +2675,7 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &id_type::MerchantId, @@ -2684,6 +2687,7 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &id_type::MerchantId, @@ -2722,6 +2726,7 @@ impl RefundInterface for KafkaStore { Ok(refund) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &id_type::MerchantId, @@ -2737,6 +2742,17 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn find_refund_by_id( + &self, + id: &id_type::GlobalRefundId, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Refund, errors::StorageError> { + self.diesel_store + .find_refund_by_id(id, storage_scheme) + .await + } + async fn insert_refund( &self, new: storage::RefundNew, @@ -2754,7 +2770,11 @@ impl RefundInterface for KafkaStore { Ok(refund) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_constraints( &self, merchant_id: &id_type::MerchantId, @@ -2774,7 +2794,11 @@ impl RefundInterface for KafkaStore { .await } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &id_type::MerchantId, @@ -2786,7 +2810,11 @@ impl RefundInterface for KafkaStore { .await } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_refund_status_with_count( &self, merchant_id: &id_type::MerchantId, @@ -2799,7 +2827,11 @@ impl RefundInterface for KafkaStore { .await } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_total_count_of_refunds( &self, merchant_id: &id_type::MerchantId, diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 1f54eeb5fdc..211f8ddbc48 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -17,6 +17,7 @@ const MAX_LIMIT: usize = 100; #[async_trait::async_trait] pub trait RefundInterface { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, @@ -24,6 +25,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, @@ -31,6 +33,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -38,6 +41,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -53,6 +57,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -60,13 +65,24 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError>; + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn find_refund_by_id( + &self, + id: &common_utils::id_type::GlobalRefundId, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError>; + async fn insert_refund( &self, new: storage_types::RefundNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -76,7 +92,11 @@ pub trait RefundInterface { offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -84,7 +104,11 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>; - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -93,7 +117,11 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>; - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -320,6 +348,7 @@ mod storage { }; #[async_trait::async_trait] impl RefundInterface for Store { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, @@ -376,6 +405,7 @@ mod storage { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn insert_refund( &self, @@ -529,6 +559,20 @@ mod storage { } } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn insert_refund( + &self, + new: storage_types::RefundNew, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + new.insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, @@ -588,6 +632,7 @@ mod storage { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn update_refund( &self, @@ -652,6 +697,21 @@ mod storage { } } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn update_refund( + &self, + this: storage_types::Refund, + refund: storage_types::RefundUpdate, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + this.update_with_id(&conn, refund) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, @@ -702,6 +762,7 @@ mod storage { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, @@ -760,6 +821,7 @@ mod storage { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, @@ -807,7 +869,24 @@ mod storage { } } - #[cfg(feature = "olap")] + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn find_refund_by_id( + &self, + id: &common_utils::id_type::GlobalRefundId, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage_types::Refund::find_by_global_id(&conn, id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, @@ -829,7 +908,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, @@ -843,7 +926,11 @@ mod storage { .map_err(|error|report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, @@ -858,7 +945,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, @@ -880,6 +971,7 @@ mod storage { #[async_trait::async_trait] impl RefundInterface for MockDb { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, @@ -899,6 +991,7 @@ impl RefundInterface for MockDb { }) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn insert_refund( &self, new: storage_types::RefundNew, @@ -950,6 +1043,56 @@ impl RefundInterface for MockDb { refunds.push(refund.clone()); Ok(refund) } + + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn insert_refund( + &self, + new: storage_types::RefundNew, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let mut refunds = self.refunds.lock().await; + let current_time = common_utils::date_time::now(); + + let refund = storage_types::Refund { + id: new.id, + merchant_reference_id: new.merchant_reference_id, + payment_id: new.payment_id, + merchant_id: new.merchant_id, + attempt_id: new.attempt_id, + connector_transaction_id: new.connector_transaction_id, + connector: new.connector, + connector_refund_id: new.connector_refund_id, + external_reference_id: new.external_reference_id, + refund_type: new.refund_type, + total_amount: new.total_amount, + currency: new.currency, + refund_amount: new.refund_amount, + refund_status: new.refund_status, + sent_to_gateway: new.sent_to_gateway, + refund_error_message: None, + refund_error_code: None, + metadata: new.metadata, + refund_arn: new.refund_arn.clone(), + created_at: new.created_at, + modified_at: current_time, + description: new.description, + refund_reason: new.refund_reason.clone(), + profile_id: new.profile_id, + updated_by: new.updated_by, + connector_id: new.connector_id, + charges: new.charges, + split_refunds: new.split_refunds, + organization_id: new.organization_id, + unified_code: None, + unified_message: None, + processor_refund_data: new.processor_refund_data.clone(), + processor_transaction_data: new.processor_transaction_data.clone(), + }; + refunds.push(refund.clone()); + Ok(refund) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -968,6 +1111,7 @@ impl RefundInterface for MockDb { .collect::<Vec<_>>()) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn update_refund( &self, this: storage_types::Refund, @@ -990,6 +1134,30 @@ impl RefundInterface for MockDb { }) } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn update_refund( + &self, + this: storage_types::Refund, + refund: storage_types::RefundUpdate, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + self.refunds + .lock() + .await + .iter_mut() + .find(|refund| this.merchant_reference_id == refund.merchant_reference_id) + .map(|r| { + let refund_updated = RefundUpdateInternal::from(refund).create_refund(r.clone()); + *r = refund_updated.clone(); + refund_updated + }) + .ok_or_else(|| { + errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) + .into() + }) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -1007,6 +1175,7 @@ impl RefundInterface for MockDb { }) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -1032,6 +1201,7 @@ impl RefundInterface for MockDb { }) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, @@ -1047,7 +1217,28 @@ impl RefundInterface for MockDb { .collect::<Vec<_>>()) } - #[cfg(feature = "olap")] + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn find_refund_by_id( + &self, + id: &common_utils::id_type::GlobalRefundId, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let refunds = self.refunds.lock().await; + + refunds + .iter() + .find(|refund| refund.id == *id) + .cloned() + .ok_or_else(|| { + errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() + }) + } + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -1162,7 +1353,11 @@ impl RefundInterface for MockDb { Ok(filtered_refunds) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_meta_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -1209,7 +1404,11 @@ impl RefundInterface for MockDb { Ok(refund_meta_data) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_refund_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -1255,7 +1454,11 @@ impl RefundInterface for MockDb { Ok(result) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs index a7e37930cf2..19635b2d8c2 100644 --- a/crates/router/src/services/kafka/refund.rs +++ b/crates/router/src/services/kafka/refund.rs @@ -5,6 +5,9 @@ use common_utils::{ use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; +use crate::events; + +#[cfg(feature = "v1")] #[derive(serde::Serialize, Debug)] pub struct KafkaRefund<'a> { pub internal_reference_id: &'a String, @@ -35,6 +38,7 @@ pub struct KafkaRefund<'a> { pub organization_id: &'a id_type::OrganizationId, } +#[cfg(feature = "v1")] impl<'a> KafkaRefund<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { @@ -66,6 +70,70 @@ impl<'a> KafkaRefund<'a> { } } +#[cfg(feature = "v2")] +#[derive(serde::Serialize, Debug)] +pub struct KafkaRefund<'a> { + pub id: &'a id_type::GlobalRefundId, + pub merchant_reference_id: &'a id_type::RefundReferenceId, + pub payment_id: &'a id_type::GlobalPaymentId, + pub merchant_id: &'a id_type::MerchantId, + pub connector_transaction_id: &'a String, + pub connector: &'a String, + pub connector_refund_id: Option<&'a String>, + pub external_reference_id: Option<&'a String>, + pub refund_type: &'a storage_enums::RefundType, + pub total_amount: &'a MinorUnit, + pub currency: &'a storage_enums::Currency, + pub refund_amount: &'a MinorUnit, + pub refund_status: &'a storage_enums::RefundStatus, + pub sent_to_gateway: &'a bool, + pub refund_error_message: Option<&'a String>, + pub refund_arn: Option<&'a String>, + #[serde(default, with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + pub description: Option<&'a String>, + pub attempt_id: &'a id_type::GlobalAttemptId, + pub refund_reason: Option<&'a String>, + pub refund_error_code: Option<&'a String>, + pub profile_id: Option<&'a id_type::ProfileId>, + pub organization_id: &'a id_type::OrganizationId, +} + +#[cfg(feature = "v2")] +impl<'a> KafkaRefund<'a> { + pub fn from_storage(refund: &'a Refund) -> Self { + Self { + id: &refund.id, + merchant_reference_id: &refund.merchant_reference_id, + payment_id: &refund.payment_id, + merchant_id: &refund.merchant_id, + connector_transaction_id: refund.get_connector_transaction_id(), + connector: &refund.connector, + connector_refund_id: refund.get_optional_connector_refund_id(), + external_reference_id: refund.external_reference_id.as_ref(), + refund_type: &refund.refund_type, + total_amount: &refund.total_amount, + currency: &refund.currency, + refund_amount: &refund.refund_amount, + refund_status: &refund.refund_status, + sent_to_gateway: &refund.sent_to_gateway, + refund_error_message: refund.refund_error_message.as_ref(), + refund_arn: refund.refund_arn.as_ref(), + created_at: refund.created_at.assume_utc(), + modified_at: refund.modified_at.assume_utc(), + description: refund.description.as_ref(), + attempt_id: &refund.attempt_id, + refund_reason: refund.refund_reason.as_ref(), + refund_error_code: refund.refund_error_code.as_ref(), + profile_id: refund.profile_id.as_ref(), + organization_id: &refund.organization_id, + } + } +} + +#[cfg(feature = "v1")] impl super::KafkaMessage for KafkaRefund<'_> { fn key(&self) -> String { format!( @@ -77,7 +145,24 @@ impl super::KafkaMessage for KafkaRefund<'_> { ) } - fn event_type(&self) -> crate::events::EventType { - crate::events::EventType::Refund + fn event_type(&self) -> events::EventType { + events::EventType::Refund + } +} + +#[cfg(feature = "v2")] +impl super::KafkaMessage for KafkaRefund<'_> { + fn key(&self) -> String { + format!( + "{}_{}_{}_{}", + self.merchant_id.get_string_repr(), + self.payment_id.get_string_repr(), + self.attempt_id.get_string_repr(), + self.merchant_reference_id.get_string_repr() + ) + } + + fn event_type(&self) -> events::EventType { + events::EventType::Refund } } diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index b9b3db17b58..34ed0b85c55 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -5,6 +5,9 @@ use common_utils::{ use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; +use crate::events; + +#[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaRefundEvent<'a> { @@ -36,6 +39,7 @@ pub struct KafkaRefundEvent<'a> { pub organization_id: &'a id_type::OrganizationId, } +#[cfg(feature = "v1")] impl<'a> KafkaRefundEvent<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { @@ -67,6 +71,71 @@ impl<'a> KafkaRefundEvent<'a> { } } +#[cfg(feature = "v2")] +#[serde_with::skip_serializing_none] +#[derive(serde::Serialize, Debug)] +pub struct KafkaRefundEvent<'a> { + pub id: &'a id_type::GlobalRefundId, + pub merchant_reference_id: &'a id_type::RefundReferenceId, + pub payment_id: &'a id_type::GlobalPaymentId, + pub merchant_id: &'a id_type::MerchantId, + pub connector_transaction_id: &'a String, + pub connector: &'a String, + pub connector_refund_id: Option<&'a String>, + pub external_reference_id: Option<&'a String>, + pub refund_type: &'a storage_enums::RefundType, + pub total_amount: &'a MinorUnit, + pub currency: &'a storage_enums::Currency, + pub refund_amount: &'a MinorUnit, + pub refund_status: &'a storage_enums::RefundStatus, + pub sent_to_gateway: &'a bool, + pub refund_error_message: Option<&'a String>, + pub refund_arn: Option<&'a String>, + #[serde(default, with = "time::serde::timestamp::nanoseconds")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::nanoseconds")] + pub modified_at: OffsetDateTime, + pub description: Option<&'a String>, + pub attempt_id: &'a id_type::GlobalAttemptId, + pub refund_reason: Option<&'a String>, + pub refund_error_code: Option<&'a String>, + pub profile_id: Option<&'a id_type::ProfileId>, + pub organization_id: &'a id_type::OrganizationId, +} + +#[cfg(feature = "v2")] +impl<'a> KafkaRefundEvent<'a> { + pub fn from_storage(refund: &'a Refund) -> Self { + Self { + id: &refund.id, + merchant_reference_id: &refund.merchant_reference_id, + payment_id: &refund.payment_id, + merchant_id: &refund.merchant_id, + connector_transaction_id: refund.get_connector_transaction_id(), + connector: &refund.connector, + connector_refund_id: refund.get_optional_connector_refund_id(), + external_reference_id: refund.external_reference_id.as_ref(), + refund_type: &refund.refund_type, + total_amount: &refund.total_amount, + currency: &refund.currency, + refund_amount: &refund.refund_amount, + refund_status: &refund.refund_status, + sent_to_gateway: &refund.sent_to_gateway, + refund_error_message: refund.refund_error_message.as_ref(), + refund_arn: refund.refund_arn.as_ref(), + created_at: refund.created_at.assume_utc(), + modified_at: refund.modified_at.assume_utc(), + description: refund.description.as_ref(), + attempt_id: &refund.attempt_id, + refund_reason: refund.refund_reason.as_ref(), + refund_error_code: refund.refund_error_code.as_ref(), + profile_id: refund.profile_id.as_ref(), + organization_id: &refund.organization_id, + } + } +} + +#[cfg(feature = "v1")] impl super::KafkaMessage for KafkaRefundEvent<'_> { fn key(&self) -> String { format!( @@ -77,8 +146,23 @@ impl super::KafkaMessage for KafkaRefundEvent<'_> { self.refund_id ) } + fn event_type(&self) -> events::EventType { + events::EventType::Refund + } +} - fn event_type(&self) -> crate::events::EventType { - crate::events::EventType::Refund +#[cfg(feature = "v2")] +impl super::KafkaMessage for KafkaRefundEvent<'_> { + fn key(&self) -> String { + format!( + "{}_{}_{}_{}", + self.merchant_id.get_string_repr(), + self.payment_id.get_string_repr(), + self.attempt_id.get_string_repr(), + self.merchant_reference_id.get_string_repr() + ) + } + fn event_type(&self) -> events::EventType { + events::EventType::Refund } } diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs index e46fc1a3f47..646b2742d5b 100644 --- a/crates/router/src/types/storage/refund.rs +++ b/crates/router/src/types/storage/refund.rs @@ -18,6 +18,7 @@ use crate::{connection::PgPooledConn, logger}; #[async_trait::async_trait] pub trait RefundDbExt: Sized { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -26,18 +27,21 @@ pub trait RefundDbExt: Sized { offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &common_utils::types::TimeRange, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, ) -> CustomResult<i64, errors::DatabaseError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -48,6 +52,7 @@ pub trait RefundDbExt: Sized { #[async_trait::async_trait] impl RefundDbExt for Refund { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -159,6 +164,7 @@ impl RefundDbExt for Refund { .attach_printable_lazy(|| "Error filtering records by predicate") } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -214,6 +220,7 @@ impl RefundDbExt for Refund { Ok(meta) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -302,6 +309,7 @@ impl RefundDbExt for Refund { .attach_printable_lazy(|| "Error filtering count of refunds") } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index ac3598cea58..06b551d8312 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -17,6 +17,7 @@ v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "comm v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "common_utils/v2"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"] payment_methods_v2 = ["diesel_models/payment_methods_v2", "api_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2"] +refunds_v2 = ["diesel_models/refunds_v2"] [dependencies] # First Party dependencies diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 13b4671e863..657114d1067 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -346,6 +346,7 @@ impl UniqueConstraints for diesel_models::PaymentAttempt { } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { vec![format!( @@ -359,6 +360,16 @@ impl UniqueConstraints for diesel_models::Refund { } } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl UniqueConstraints for diesel_models::Refund { + fn unique_constraints(&self) -> Vec<String> { + vec![self.id.get_string_repr().to_owned()] + } + fn table_name(&self) -> &str { + "Refund" + } +} + impl UniqueConstraints for diesel_models::ReverseLookup { fn unique_constraints(&self) -> Vec<String> { vec![format!("reverselookup_{}", self.lookup_id)] diff --git a/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql index 92f74b1d9ac..e3c87773716 100644 --- a/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql +++ b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql @@ -52,4 +52,9 @@ ALTER TABLE merchant_connector_account ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_fingerprint_id, DROP COLUMN IF EXISTS payment_method_type_v2, - DROP COLUMN IF EXISTS payment_method_subtype; \ No newline at end of file + DROP COLUMN IF EXISTS payment_method_subtype; + +ALTER TABLE refund + DROP COLUMN IF EXISTS id, + DROP COLUMN IF EXISTS merchant_reference_id, + DROP COLUMN IF EXISTS connector_id; \ No newline at end of file diff --git a/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql index 3094cdb3320..1dcedbff563 100644 --- a/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql +++ b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql @@ -62,4 +62,9 @@ ALTER TABLE merchant_connector_account ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64), - ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); \ No newline at end of file + ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); + +ALTER TABLE refund + ADD COLUMN IF NOT EXISTS id VARCHAR(64), + ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), + ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64); \ No newline at end of file diff --git a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql index 10fd9adfa55..c0b0efbd385 100644 --- a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql +++ b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql @@ -37,3 +37,7 @@ ALTER TABLE payment_attempt ---------------------- Payment Methods ---------------------- ALTER TABLE payment_methods ADD PRIMARY KEY (payment_method_id); + +---------------------- Refunds ---------------------- +ALTER TABLE refund + ADD PRIMARY KEY (refund_id,merchant_id); \ No newline at end of file diff --git a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql index e348f2e1cbb..731d488297e 100644 --- a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql +++ b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql @@ -37,3 +37,7 @@ ALTER TABLE payment_attempt ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey, ALTER COLUMN payment_method_id DROP NOT NULL; + +ALTER TABLE refund + DROP CONSTRAINT refund_pkey, + ALTER COLUMN refund_id DROP NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/down.sql b/v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/down.sql similarity index 87% rename from v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/down.sql rename to v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/down.sql index 1941d9c1b8e..06b78440d17 100644 --- a/v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/down.sql +++ b/v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/down.sql @@ -24,4 +24,7 @@ ALTER TABLE payment_attempt ALTER COLUMN net_amount DROP NOT NULL, ALTER COLUMN authentication_type DROP NOT NULL, ALTER COLUMN payment_method_type_v2 DROP NOT NULL, - ALTER COLUMN payment_method_subtype DROP NOT NULL; \ No newline at end of file + ALTER COLUMN payment_method_subtype DROP NOT NULL; + +ALTER TABLE refund + ALTER COLUMN merchant_reference_id DROP NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/up.sql b/v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/up.sql similarity index 83% rename from v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/up.sql rename to v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/up.sql index 36fc7d2893d..3641d2bdab6 100644 --- a/v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/up.sql +++ b/v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/up.sql @@ -23,4 +23,8 @@ ALTER TABLE payment_attempt ALTER COLUMN net_amount SET NOT NULL, ALTER COLUMN authentication_type SET NOT NULL, ALTER COLUMN payment_method_type_v2 SET NOT NULL, - ALTER COLUMN payment_method_subtype SET NOT NULL; \ No newline at end of file + ALTER COLUMN payment_method_subtype SET NOT NULL; + +-- This migration is to make fields mandatory in refund table +ALTER TABLE refund + ALTER COLUMN merchant_reference_id SET NOT NULL; \ No newline at end of file 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 9b04dd6d3f5..a48c2b660f5 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 @@ -65,3 +65,7 @@ ALTER TABLE payment_attempt ALTER COLUMN id DROP NOT NULL; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey; ALTER TABLE payment_methods ALTER COLUMN id DROP NOT NULL; + +------------------------ Refunds ----------------------- +ALTER TABLE refund DROP CONSTRAINT refund_pkey; +ALTER TABLE refund ALTER COLUMN id DROP NOT NULL; \ No newline at end of file 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 3b155115119..df0c434d68f 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 @@ -76,3 +76,8 @@ ADD PRIMARY KEY (id); -- Add primary key constraint ALTER TABLE payment_methods ADD PRIMARY KEY (id); + +------------------------ Refunds ----------------------- +-- Add primary key constraint +ALTER TABLE refund +ADD PRIMARY KEY (id); \ No newline at end of file diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql index efcb56101f9..483ef12a276 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql @@ -130,4 +130,9 @@ ALTER TABLE payment_methods ALTER TABLE refund ADD COLUMN connector_refund_data VARCHAR(512), ADD COLUMN connector_transaction_data VARCHAR(512); -ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); \ No newline at end of file +ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); + +ALTER TABLE refund + ADD COLUMN IF NOT EXISTS internal_reference_id VARCHAR(64), + ADD COLUMN IF NOT EXISTS refund_id VARCHAR(64), + ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(64); \ No newline at end of file diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index cbb2b264d45..69357bb04ac 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -121,3 +121,9 @@ ALTER TABLE refund DROP COLUMN connector_refund_data, -- Run below queries only when V1 is deprecated ALTER TABLE captures DROP COLUMN connector_capture_data; + +-- Run below queries only when V1 is deprecated +ALTER TABLE refund + DROP COLUMN IF EXISTS internal_reference_id, + DROP COLUMN IF EXISTS refund_id, + DROP COLUMN IF EXISTS merchant_connector_id;
2025-03-12T16:18:08Z
## Description This PR is a part of v2 implementation of refunds. This PR contains the necessary database schema refactoring as well as handling this in the storage_impl crate. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Merging this PR would add db support for refunds in v2 apis. #
afca506369685ab63d1b6bccd5f2e2dbae50ebf9
Cannot be tested because the core flow is not implemented for the refunds in V2 APIs, will be taking that in upcoming PRs.
[ "crates/diesel_models/Cargo.toml", "crates/diesel_models/src/kv.rs", "crates/diesel_models/src/query/refund.rs", "crates/diesel_models/src/query/user/sample_data.rs", "crates/diesel_models/src/refund.rs", "crates/diesel_models/src/schema_v2.rs", "crates/router/Cargo.toml", "crates/router/src/db/kafka_store.rs", "crates/router/src/db/refund.rs", "crates/router/src/services/kafka/refund.rs", "crates/router/src/services/kafka/refund_event.rs", "crates/router/src/types/storage/refund.rs", "crates/storage_impl/Cargo.toml", "crates/storage_impl/src/lib.rs", "v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql", "v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql", "v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql", "v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql", "v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/down.sql", "v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/up.sql", "v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql", "v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql", "v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql", "v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql", "v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/down.sql", "v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-7506
Bug: [BUG] [BRAINTREE] Fix picking of creds identifier during Complete Authorize Flow ### Bug Description When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow fails. ### Expected Behavior When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow should not fail. ### Actual Behavior When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow fails. ### Steps To Reproduce When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow fails. ### Context For The Bug _No response_ ### Environment Integ, Sandbox, Production ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d072463020a..6ebc5266eba 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2328,6 +2328,12 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), + merchant_connector_details: req.creds_identifier.map(|creds_id| { + api::MerchantConnectorDetailsWrap { + creds_identifier: creds_id, + encoded_data: None, + } + }), feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index cdbda13997b..82c9eca97c4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1262,13 +1262,18 @@ pub fn create_complete_authorize_url( router_base_url: &String, payment_attempt: &PaymentAttempt, connector_name: impl std::fmt::Display, + creds_identifier: Option<&str>, ) -> String { + let creds_identifier = creds_identifier.map_or_else(String::new, |creds_identifier| { + format!("/{}", creds_identifier) + }); format!( - "{}/payments/{}/{}/redirect/complete/{}", + "{}/payments/{}/{}/redirect/complete/{}{}", router_base_url, payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), - connector_name + connector_name, + creds_identifier ) } 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 d95e92115ad..7befdfc91d3 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -305,6 +305,14 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> id: profile_id.get_string_repr().to_owned(), })?; + let creds_identifier = + request + .merchant_connector_details + .as_ref() + .map(|merchant_connector_details| { + merchant_connector_details.creds_identifier.to_owned() + }); + let payment_data = PaymentData { flow: PhantomData, payment_intent, @@ -336,7 +344,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> attempts: None, sessions_token: vec![], card_cvc: request.card_cvc.clone(), - creds_identifier: None, + creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 9647a277b0e..f1577f6e10f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -223,6 +223,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( router_base_url, attempt, connector_id, + None, )); let webhook_url = Some(helpers::create_webhook_url( @@ -887,6 +888,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( router_base_url, attempt, connector_id, + None, )); let webhook_url = Some(helpers::create_webhook_url( @@ -3115,7 +3117,9 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz router_base_url, attempt, connector_name, + payment_data.creds_identifier.as_deref(), )); + let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id @@ -4084,6 +4088,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz router_base_url, attempt, connector_name, + payment_data.creds_identifier.as_deref(), )); let braintree_metadata = payment_data .payment_intent @@ -4198,6 +4203,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce router_base_url, attempt, connector_name, + payment_data.creds_identifier.as_deref(), )); let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index de5593703d0..5d364d9b923 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -747,6 +747,11 @@ impl Payments { .route(web::get().to(payments::payments_redirect_response)) .route(web::post().to(payments::payments_redirect_response)) ) + .service( + web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}/{creds_identifier}") + .route(web::get().to(payments::payments_complete_authorize_redirect_with_creds_identifier)) + .route(web::post().to(payments::payments_complete_authorize_redirect_with_creds_identifier)) + ) .service( web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}") .route(web::get().to(payments::payments_complete_authorize_redirect)) diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 9708f34c53c..cd136ff784f 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1084,6 +1084,58 @@ pub async fn payments_complete_authorize_redirect( .await } +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))] +pub async fn payments_complete_authorize_redirect_with_creds_identifier( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: Option<web::Form<serde_json::Value>>, + path: web::Path<( + common_utils::id_type::PaymentId, + common_utils::id_type::MerchantId, + String, + String, + )>, +) -> impl Responder { + let flow = Flow::PaymentsRedirect; + let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner(); + let param_string = req.query_string(); + + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); + + let payload = payments::PaymentsRedirectResponseData { + resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), + merchant_id: Some(merchant_id.clone()), + param: Some(param_string.to_string()), + json_payload: json_payload.map(|s| s.0), + force_sync: false, + connector: Some(connector), + creds_identifier: Some(creds_identifier), + }; + let locking_action = payload.get_locking_input(flow.clone()); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, req, req_state| { + + <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response( + &payments::PaymentRedirectCompleteAuthorize {}, + state, + req_state, + auth.merchant_account, + auth.key_store, + req, + auth.platform_merchant_account, + ) + }, + &auth::MerchantIdAuth(merchant_id), + locking_action, + )) + .await +} + #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow =? Flow::PaymentsCompleteAuthorize, payment_id))] pub async fn payments_complete_authorize(
2025-03-12T14:27:12Z
## Description <!-- Describe your changes in detail --> When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow fails. This PR is for fixing that. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Issue Link: https://github.com/juspay/hyperswitch/issues/7506 #
13a274909962872f1d663d082af33fc44205d419
**Postman Tests** **1. Payment Intent Create (Without Braintree MCA Create)** -Request ``` curl --location 'http://localhost:8080/vs/v1/payment_intents' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'User-Agent: helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \ --header 'api-key: dev_cAhKiY0z6BCPtxdTZKiuoGXNfbk49QwuMRPJudoj4P5gWR24zvL1BniBwqBBP7SL' \ --data-urlencode 'amount=1200' \ --data-urlencode 'currency=USD' \ --data-urlencode 'confirm=true' \ --data-urlencode 'payment_method_data%5Btype%5D=card' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bnumber%5D=5200000000001096' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_month%5D=10' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_year%5D=26' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bcvc%5D=123' \ --data-urlencode 'connector%5B%5D=braintree' \ --data-urlencode 'capture_method=automatic' \ --data-urlencode 'customer=sahkal' \ --data-urlencode 'statementDescriptorSuffix=merchant_101' \ --data-urlencode 'metadata%5BorderId%5D=1677581650' \ --data-urlencode 'payment_method_options%5Bcard%5D%5Brequest_three_d_secure%5D=any' \ --data-urlencode 'description=Card Payment' \ --data-urlencode 'return_url=https://google.com' \ --data-urlencode 'merchant_connector_details%5Bencoded_data%5D=eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.2Ef5oJ8MdVY9wdMdVVYHhrjUfY-NzgUc5oN7rKR3IG9jzYWkc9my0bMVQ31H2GjHQGBRuNzR0y-OfzFBHpmpSxA6qt5c-PFs2HaIEV69tXml6u6FcKtPvsMxVTRIiMMN1dJTwxKm9kqBMsXE6rpokDkKOJTU1-33Lz7v0VAT2KsZo7zNc4Tp0SI_tLaBwos4N-Ihws4PGbNy6CkEId0tTArJMg2y7utl759DAnUwwjgNNebMNUa9qAAIX6zCrn0U4n7NGyrpBbKqOu4Cd7sYeysP_jKjE12FexXHcEwHwUZTa453q-DvvvKlbfoACgGjE9ceBMr8kF1d1EnyS2J4DA.Wp1spmaGnWhvvCqY.X5I79LC8PC5AHQy6bT0JCNPrsvqc51iVWu1O5487ihDmCCkwC4eBXgm5STkYtNfttbMHD6-SimAVmtqD0AmhCUoJ7h0qQbcZt4XdB89gH5pdZvaSsmozlYxMG64jvGkXfp22aQZf-SwpcRWslP5CmFGTJDT7OgJTNBOZuoA6tbFIyxoXUh1L6Km4DuJA2dbKPRsw_Cg_5O869Wg5ghQmEtqHToirWLbwtZN32phRLt6L.GooLyxP-9xhU-vvi2vRGdA' \ --data-urlencode 'merchant_connector_details%5Bcreds_identifier%5D=azharamin_noon_1efwedxqwd' \ --data-urlencode 'id=154107184321542' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Bname%5D=Joseph Doe' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Bemail%[email protected]' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bcity%5D=siliguri' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bcountry%5D=IN' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bstate%5D=westbengal' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bline1%5D=pritilata' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bzip%5D=734006' \ --data-urlencode 'metadata%5Bmerchant_id%5D=sahkal' \ --data-urlencode 'metadata%5Beuler_merchant_id%5D=global_installment' \ --data-urlencode 'connector_metadata%5Bnoon%5D%5Border_category%5D=pay' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bholder_name%5D=Joseph Doe' \ --data-urlencode 'connector_metadata%5Bbraintree%5D%5Bmerchant_account_id%5D=juspay' \ --data-urlencode 'connector_metadata%5Bbraintree%5D%5Bmerchant_config_currency%5D=USD' ``` -Response ``` { "id": "154107184321542", "object": "payment_intent", "amount": 1200, "amount_received": null, "amount_capturable": 1200, "currency": "usd", "status": "requires_action", "client_secret": "154107184321542_secret_HE2P7xcJNdGJr061tYZh", "created": 1741828281, "customer": "sahkal", "refunds": null, "mandate": null, "metadata": { "orderId": "1677581650", "merchant_id": "sahkal", "euler_merchant_id": "global_installment" }, "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "http://placeholder" }, "connector": "braintree", "description": "Card Payment", "mandate_data": null, "setup_future_usage": null, "off_session": null, "authentication_type": "three_ds", "next_action": { "type": "redirect_to_url", "redirect_to_url": { "return_url": "https://google.com/", "url": "http://localhost:8080/payments/redirect/154107184321542/postman_merchant_GHAction_174568/154107184321542_1" } }, "cancellation_reason": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "26", "card_holder_name": "Joseph Doe", "payment_checks": null, "authentication_data": null } }, "shipping": null, "billing": { "address": { "city": "siliguri", "country": "IN", "line1": "pritilata", "line2": null, "line3": null, "zip": null, "state": "westbengal", "first_name": null, "last_name": null }, "phone": { "number": null, "country_code": "IN" }, "email": "[email protected]" }, "capture_on": null, "payment_token": null, "email": null, "phone": null, "statement_descriptor_suffix": null, "statement_descriptor_name": null, "capture_method": "automatic", "name": null, "last_payment_error": null, "connector_transaction_id": null } ``` **2. Payment Create (Normal Hyperswitch Flow)** -Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cAhKiY0z6BCPtxdTZKiuoGXNfbk49QwuMRPJudoj4P5gWR24zvL1BniBwqBBP7SL' \ --data-raw '{ "amount": 2500, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 2500, "customer_id": "abcdef", "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_type": "credit", "payment_method_data": { "card": { "card_number": "5200000000001096", "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" } }' ``` -Response ``` { "payment_id": "pay_QLFSd62pZGRWHmzJl9V1", "merchant_id": "postman_merchant_GHAction_174568", "status": "requires_customer_action", "amount": 2500, "net_amount": 2500, "shipping_cost": null, "amount_capturable": 2500, "amount_received": null, "connector": "braintree", "client_secret": "pay_QLFSd62pZGRWHmzJl9V1_secret_1lRAyjj7PewghQLE5bMm", "created": "2025-03-13T01:13:16.662Z", "currency": "USD", "customer_id": "abcdef", "customer": { "id": "abcdef", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_QLFSd62pZGRWHmzJl9V1/postman_merchant_GHAction_174568/pay_QLFSd62pZGRWHmzJl9V1_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "abcdef", "created_at": 1741828396, "expires": 1741831996, "secret": "epk_beff18305e9f49bda8a0b9e2a77b249e" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_1tsuB1vmUFHSgf5OavLc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_iQuV3uVZfTRA8dJJg53p", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-13T01:28:16.662Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-13T01:13:18.053Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` **2. PSync** -Request ``` curl --location 'http://localhost:8080/payments/pay_QLFSd62pZGRWHmzJl9V1' \ --header 'Accept: application/json' \ --header 'api-key: dev_cAhKiY0z6BCPtxdTZKiuoGXNfbk49QwuMRPJudoj4P5gWR24zvL1BniBwqBBP7SL' ``` -Response ``` { "payment_id": "pay_QLFSd62pZGRWHmzJl9V1", "merchant_id": "postman_merchant_GHAction_174568", "status": "succeeded", "amount": 2500, "net_amount": 2500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 2500, "connector": "braintree", "client_secret": "pay_QLFSd62pZGRWHmzJl9V1_secret_1lRAyjj7PewghQLE5bMm", "created": "2025-03-13T01:13:16.662Z", "currency": "USD", "customer_id": "abcdef", "customer": { "id": "abcdef", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "dHJhbnNhY3Rpb25fNGMyNnRlN3I", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_1tsuB1vmUFHSgf5OavLc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_iQuV3uVZfTRA8dJJg53p", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-13T01:28:16.662Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-13T01:14:51.291Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ```
[ "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_complete_authorize.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7498
Bug: feat(analytics): modify authentication queries and add generate report for authentications hotfix Need to modify the authentication analytics queries to differentiate between frictionless flow and challenge flow through the authentication_type field. Introduce support for authentication report generation, similar to the existing reports for payments, refunds, and disputes.
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index a2640be6ead..bdcbdd86a94 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -165,6 +165,7 @@ pub async fn get_filters( .filter_map(|fil: AuthEventFilterRow| match dim { AuthEventDimensions::AuthenticationStatus => fil.authentication_status.map(|i| i.as_ref().to_string()), AuthEventDimensions::TransactionStatus => fil.trans_status.map(|i| i.as_ref().to_string()), + AuthEventDimensions::AuthenticationType => fil.authentication_type.map(|i| i.as_ref().to_string()), AuthEventDimensions::ErrorMessage => fil.error_message, AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index da8e0b7cfa3..5f65eeaa279 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -1,4 +1,5 @@ use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange}; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use diesel_models::enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use error_stack::ResultExt; @@ -54,6 +55,7 @@ where pub struct AuthEventFilterRow { pub authentication_status: Option<DBEnumWrapper<AuthenticationStatus>>, pub trans_status: Option<DBEnumWrapper<TransactionStatus>>, + pub authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>>, pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index fd94aac614c..a3d0fe7b683 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -41,6 +41,7 @@ pub struct AuthEventMetricRow { pub count: Option<i64>, pub authentication_status: Option<DBEnumWrapper<storage_enums::AuthenticationStatus>>, pub trans_status: Option<DBEnumWrapper<storage_enums::TransactionStatus>>, + pub authentication_type: Option<DBEnumWrapper<storage_enums::DecoupledAuthenticationType>>, pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 32c76385409..b82d1ef4c35 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -70,7 +70,10 @@ where .switch()?; query_builder - .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending) + .add_filter_in_range_clause( + "authentication_status", + &[AuthenticationStatus::Success, AuthenticationStatus::Failed], + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -103,6 +106,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 39df41f53aa..682e8a07f6b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -96,6 +96,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index cdb89b796dd..047511d477c 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -12,8 +12,8 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ query::{ - Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, - Window, + Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, + ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -45,11 +45,9 @@ where for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } + query_builder - .add_select_column(Aggregate::Count { - field: None, - alias: Some("count"), - }) + .add_select_column("sum(sign_flag) AS count") .switch()?; query_builder @@ -94,6 +92,11 @@ where .switch()?; } + query_builder + .add_order_by_clause("count", Order::Descending) + .attach_printable("Error adding order by clause") + .switch()?; + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) @@ -112,6 +115,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 37f9dfd1c1f..9342e9047e0 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -107,6 +107,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 039ef00dd6e..984350efe6b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -101,6 +101,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index beccc093b19..5a2a9400b20 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,11 +68,17 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; query_builder - .add_negative_filter_clause("authentication_status", "pending") + .add_filter_in_range_clause( + "authentication_status", + &[AuthenticationStatus::Success, AuthenticationStatus::Failed], + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -104,6 +111,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 4d07cffba94..279844388f2 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -99,6 +103,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 310a45f0530..91e8cc54289 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::AuthenticationStatus; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -72,7 +72,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -105,6 +108,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index 24857bfb840..b08edb10113 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "Y".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Frictionless, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -100,6 +104,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 79fef8a16d0..80417ac64bf 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::AuthenticationStatus; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -68,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "Y".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Frictionless, + ) .switch()?; query_builder @@ -105,6 +108,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index f698b1161a0..89f5cbd5b9c 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -1123,6 +1123,7 @@ pub struct ReportConfig { pub payment_function: String, pub refund_function: String, pub dispute_function: String, + pub authentication_function: String, pub region: String, } @@ -1151,6 +1152,7 @@ pub enum AnalyticsFlow { GeneratePaymentReport, GenerateDisputeReport, GenerateRefundReport, + GenerateAuthenticationReport, GetApiEventMetrics, GetApiEventFilters, GetConnectorEvents, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index d483ce43605..5effd9e70a7 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -19,7 +19,9 @@ use api_models::{ }, refunds::RefundStatus, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, @@ -506,6 +508,7 @@ impl_to_sql_for_to_string!( TransactionStatus, AuthenticationStatus, AuthenticationConnectors, + DecoupledAuthenticationType, Flow, &String, &bool, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index a6db92e753f..6a6237e6783 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -4,7 +4,9 @@ use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, @@ -100,6 +102,7 @@ db_type!(DisputeStatus); db_type!(AuthenticationStatus); db_type!(TransactionStatus); db_type!(AuthenticationConnectors); +db_type!(DecoupledAuthenticationType); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where @@ -208,6 +211,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -237,6 +245,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow Ok(Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, @@ -259,6 +268,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -277,6 +291,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow Ok(Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 5c2d4ed2064..2360e564642 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -3,7 +3,9 @@ use std::{ hash::{Hash, Hasher}, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use super::{NameDescription, TimeRange}; @@ -14,6 +16,8 @@ pub struct AuthEventFilters { #[serde(default)] pub trans_status: Vec<TransactionStatus>, #[serde(default)] + pub authentication_type: Vec<DecoupledAuthenticationType>, + #[serde(default)] pub error_message: Vec<String>, #[serde(default)] pub authentication_connector: Vec<AuthenticationConnectors>, @@ -42,6 +46,7 @@ pub enum AuthEventDimensions { #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, + AuthenticationType, ErrorMessage, AuthenticationConnector, MessageVersion, @@ -101,6 +106,7 @@ pub mod metric_behaviour { pub struct ChallengeAttemptCount; pub struct ChallengeSuccessCount; pub struct AuthenticationErrorMessage; + pub struct AuthenticationFunnel; } impl From<AuthEventMetrics> for NameDescription { @@ -125,6 +131,7 @@ impl From<AuthEventDimensions> for NameDescription { pub struct AuthEventMetricsBucketIdentifier { pub authentication_status: Option<AuthenticationStatus>, pub trans_status: Option<TransactionStatus>, + pub authentication_type: Option<DecoupledAuthenticationType>, pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, @@ -140,6 +147,7 @@ impl AuthEventMetricsBucketIdentifier { pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, + authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, @@ -148,6 +156,7 @@ impl AuthEventMetricsBucketIdentifier { Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, @@ -161,6 +170,7 @@ impl Hash for AuthEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.authentication_status.hash(state); self.trans_status.hash(state); + self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); self.error_message.hash(state); diff --git a/crates/api_models/src/analytics/sdk_events.rs b/crates/api_models/src/analytics/sdk_events.rs index b2abbbe00e1..9a749f1144e 100644 --- a/crates/api_models/src/analytics/sdk_events.rs +++ b/crates/api_models/src/analytics/sdk_events.rs @@ -114,6 +114,10 @@ pub enum SdkEventNames { ThreeDsMethod, LoaderChanged, DisplayThreeDsSdk, + ThreeDsSdkInit, + AreqParamsGeneration, + ChallengePresented, + ChallengeComplete, } pub mod metric_behaviour { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 858c16d052f..cc242f86a5b 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -90,6 +90,10 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) + .service( + web::resource("report/authentications") + .route(web::post().to(generate_merchant_authentication_report)), + ) .service( web::resource("metrics/sdk_events") .route(web::post().to(get_sdk_event_metrics)), @@ -190,6 +194,11 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) + .service( + web::resource("report/authentications").route( + web::post().to(generate_merchant_authentication_report), + ), + ) .service( web::resource("metrics/api_events") .route(web::post().to(get_merchant_api_events_metrics)), @@ -252,6 +261,10 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_org_payment_report)), ) + .service( + web::resource("report/authentications") + .route(web::post().to(generate_org_authentication_report)), + ) .service( web::resource("metrics/sankey") .route(web::post().to(get_org_sankey)), @@ -306,6 +319,11 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_profile_payment_report)), ) + .service( + web::resource("report/authentications").route( + web::post().to(generate_profile_authentication_report), + ), + ) .service( web::resource("api_event_logs") .route(web::get().to(get_profile_api_events)), @@ -1746,6 +1764,7 @@ pub mod routes { )) .await } + #[cfg(feature = "v1")] pub async fn generate_org_payment_report( state: web::Data<AppState>, @@ -1850,6 +1869,161 @@ pub mod routes { .await } + #[cfg(feature = "v1")] + pub async fn generate_merchant_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: Some(merchant_id.clone()), + auth: AuthInfo::MerchantLevel { + org_id: org_id.clone(), + merchant_ids: vec![merchant_id.clone()], + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::MerchantReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn generate_org_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let org_id = auth.merchant_account.get_org_id(); + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: None, + auth: AuthInfo::OrgLevel { + org_id: org_id.clone(), + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::OrganizationReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn generate_profile_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let profile_id = auth + .profile_id + .ok_or(report!(UserErrors::JwtProfileIdMissing)) + .change_context(AnalyticsError::AccessForbiddenError)?; + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: Some(merchant_id.clone()), + auth: AuthInfo::ProfileLevel { + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + profile_ids: vec![profile_id.clone()], + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::ProfileReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + /// # Panics /// /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
2025-03-12T12:08:14Z
## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7483](https://github.com/juspay/hyperswitch/pull/7483) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
b8b3bfa77055648345ba827ec03e213e66539e7f
[ "crates/analytics/src/auth_events/core.rs", "crates/analytics/src/auth_events/filters.rs", "crates/analytics/src/auth_events/metrics.rs", "crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs", "crates/analytics/src/auth_events/metrics/authentication_count.rs", "crates/analytics/src/auth_events/metrics/authentication_error_message.rs", "crates/analytics/src/auth_events/metrics/authentication_funnel.rs", "crates/analytics/src/auth_events/metrics/authentication_success_count.rs", "crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs", "crates/analytics/src/auth_events/metrics/challenge_flow_count.rs", "crates/analytics/src/auth_events/metrics/challenge_success_count.rs", "crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs", "crates/analytics/src/auth_events/metrics/frictionless_success_count.rs", "crates/analytics/src/lib.rs", "crates/analytics/src/query.rs", "crates/analytics/src/sqlx.rs", "crates/api_models/src/analytics/auth_events.rs", "crates/api_models/src/analytics/sdk_events.rs", "crates/router/src/analytics.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7495
Bug: refactor(connector): [BILLWERK, FISERVEMEA, TSYS] use LazyLock instead of lazy_static! Use LazyLock instead of lazy_static!
diff --git a/crates/hyperswitch_connectors/src/connectors/billwerk.rs b/crates/hyperswitch_connectors/src/connectors/billwerk.rs index 4d76dcd5706..4d5e324b39f 100644 --- a/crates/hyperswitch_connectors/src/connectors/billwerk.rs +++ b/crates/hyperswitch_connectors/src/connectors/billwerk.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use base64::Engine; use common_enums::enums; @@ -44,7 +46,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; -use lazy_static::lazy_static; use masking::{Mask, PeekInterface}; use transformers::{ self as billwerk, BillwerkAuthType, BillwerkCaptureRequest, BillwerkErrorResponse, @@ -808,8 +809,8 @@ impl IncomingWebhook for Billwerk { } } -lazy_static! { - static ref BILLWERK_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { +static BILLWERK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, @@ -833,7 +834,7 @@ lazy_static! { billwerk_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, - PaymentMethodDetails{ + PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), @@ -846,13 +847,13 @@ lazy_static! { } }), ), - } + }, ); billwerk_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, - PaymentMethodDetails{ + PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), @@ -865,24 +866,23 @@ lazy_static! { } }), ), - } + }, ); billwerk_supported_payment_methods - }; + }); - static ref BILLWERK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Billwerk", - description: "Billwerk+ Pay is an acquirer independent payment gateway that's easy to setup with more than 50 recurring and non-recurring payment methods.", - connector_type: enums::PaymentConnectorCategory::PaymentGateway, - }; +static BILLWERK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Billwerk", + description: "Billwerk+ Pay is an acquirer independent payment gateway that's easy to setup with more than 50 recurring and non-recurring payment methods.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; - static ref BILLWERK_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); -} +static BILLWERK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Billwerk { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*BILLWERK_CONNECTOR_INFO) + Some(&BILLWERK_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -890,6 +890,6 @@ impl ConnectorSpecifications for Billwerk { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*BILLWERK_SUPPORTED_WEBHOOK_FLOWS) + Some(&BILLWERK_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs index cb00c66a4fd..95c252cb685 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use base64::Engine; use common_enums::enums; use common_utils::{ @@ -41,7 +43,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -use lazy_static::lazy_static; use masking::{ExposeInterface, Mask, PeekInterface}; use ring::hmac; use time::OffsetDateTime; @@ -784,8 +785,8 @@ impl webhooks::IncomingWebhook for Fiservemea { } } -lazy_static! { - static ref FISERVEMEA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { +static FISERVEMEA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, @@ -809,7 +810,7 @@ lazy_static! { fiservemea_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, - PaymentMethodDetails{ + PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), @@ -822,13 +823,13 @@ lazy_static! { } }), ), - } + }, ); fiservemea_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, - PaymentMethodDetails{ + PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), @@ -841,24 +842,23 @@ lazy_static! { } }), ), - } + }, ); fiservemea_supported_payment_methods - }; + }); - static ref FISERVEMEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Fiservemea", - description: "Fiserv powers over 6+ million merchants and 10,000+ financial institutions enabling them to accept billions of payments a year.", - connector_type: enums::PaymentConnectorCategory::BankAcquirer, - }; +static FISERVEMEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Fiservemea", + description: "Fiserv powers over 6+ million merchants and 10,000+ financial institutions enabling them to accept billions of payments a year.", + connector_type: enums::PaymentConnectorCategory::BankAcquirer, +}; - static ref FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); -} +static FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Fiservemea { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*FISERVEMEA_CONNECTOR_INFO) + Some(&FISERVEMEA_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -866,6 +866,6 @@ impl ConnectorSpecifications for Fiservemea { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS) + Some(&FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/tsys.rs b/crates/hyperswitch_connectors/src/connectors/tsys.rs index 7a0fe0bdc93..d5a6fd834e2 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use common_enums::enums; use common_utils::{ errors::CustomResult, @@ -43,7 +45,6 @@ use hyperswitch_interfaces::{ }, webhooks, }; -use lazy_static::lazy_static; use transformers as tsys; use crate::{constants::headers, types::ResponseRouterData, utils}; @@ -645,78 +646,76 @@ impl webhooks::IncomingWebhook for Tsys { } } -lazy_static! { - static ref TSYS_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { - let supported_capture_methods = vec![ - enums::CaptureMethod::Automatic, - enums::CaptureMethod::Manual, - enums::CaptureMethod::SequentialAutomatic, - ]; - - let supported_card_network = vec![ - common_enums::CardNetwork::Mastercard, - common_enums::CardNetwork::Visa, - common_enums::CardNetwork::AmericanExpress, - common_enums::CardNetwork::Discover, - common_enums::CardNetwork::JCB, - common_enums::CardNetwork::UnionPay, - ]; - - let mut tsys_supported_payment_methods = SupportedPaymentMethods::new(); - - tsys_supported_payment_methods.add( - enums::PaymentMethod::Card, - enums::PaymentMethodType::Credit, - 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::NotSupported, - no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), - } - }), - ), - } - ); - - tsys_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::NotSupported, - no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), - } - }), - ), - } - ); - - tsys_supported_payment_methods - }; - - static ref TSYS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Tsys", - description: "TSYS, a Global Payments company, is the payment stack for the future, powered by unmatched expertise.", - connector_type: enums::PaymentConnectorCategory::BankAcquirer, - }; - - static ref TSYS_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); -} +static TSYS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::UnionPay, + ]; + + let mut tsys_supported_payment_methods = SupportedPaymentMethods::new(); + + tsys_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + 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::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + tsys_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::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + tsys_supported_payment_methods +}); + +static TSYS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Tsys", + description: "TSYS, a Global Payments company, is the payment stack for the future, powered by unmatched expertise.", + connector_type: enums::PaymentConnectorCategory::BankAcquirer, +}; + +static TSYS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Tsys { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*TSYS_CONNECTOR_INFO) + Some(&TSYS_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -724,6 +723,6 @@ impl ConnectorSpecifications for Tsys { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*TSYS_SUPPORTED_WEBHOOK_FLOWS) + Some(&TSYS_SUPPORTED_WEBHOOK_FLOWS) } }
2025-03-12T08:31:27Z
## Description <!-- Describe your changes in detail --> Refactored the feature matrix PR by using `LazyLock` instead of `lazy_static!` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
662e45f0037c0aa039c1de72500c6004322f3ffb
Postman Test Feature API curl: ``` curl --location 'http://localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api_key}}' ``` Response: ``` { "connector_count": 3, "connectors": [ { "name": "BILLWERK", "display_name": "Billwerk", "description": "Billwerk+ Pay is an acquirer independent payment gateway that's easy to setup with more than 50 recurring and non-recurring payment methods.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay", "DinersClub", "Interac", "CartesBancaires" ], "supported_countries": [ "DK", "DE", "FR", "SE" ], "supported_currencies": [ "DKK", "NOK" ] }, { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay", "DinersClub", "Interac", "CartesBancaires" ], "supported_countries": [ "SE", "FR", "DE", "DK" ], "supported_currencies": [ "NOK", "DKK" ] } ], "supported_webhook_flows": [] }, { "name": "FISERVEMEA", "display_name": "Fiservemea", "description": "Fiserv powers over 6+ million merchants and 10,000+ financial institutions enabling them to accept billions of payments a year.", "category": "bank_acquirer", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay", "DinersClub", "Interac", "CartesBancaires" ], "supported_countries": [ "AE", "PL", "FR", "ES", "GB", "ZA", "DE", "NL", "IT" ], "supported_currencies": [ "SSP", "BIF", "MOP", "KMF", "HNL", "SYP", "CVE", "SGD", "KHR", "MXN", "NPR", "RUB", "TMT", "BRL", "MRU", "SHP", "KPW", "KZT", "SLE", "CZK", "CAD", "VUV", "PYG", "SOS", "AFN", "MVR", "YER", "ZAR", "TTD", "CHF", "AMD", "NGN", "KYD", "ERN", "PKR", "MZN", "TJS", "BTN", "IDR", "SCR", "AED", "MUR", "CLP", "XPF", "TOP", "PHP", "THB", "AZN", "RON", "DZD", "SBD", "PAB", "HRK", "KRW", "SEK", "BOB", "LKR", "SAR", "KGS", "NIO", "RSD", "PLN", "NZD", "BYN", "SVC", "GYD", "SZL", "USD", "ISK", "BMD", "COP", "SDG", "TZS", "KWD", "UYU", "JOD", "CUP", "LYD", "LAK", "DOP", "AUD", "VES", "FJD", "CRC", "FKP", "HKD", "IRR", "BDT", "BBD", "EUR", "BHD", "UAH", "MGA", "CNY", "HTG", "ALL", "INR", "GHS", "MAD", "TWD", "MYR", "BND", "NAD", "QAR", "GIP", "GEL", "AOA", "UGX", "LSL", "XAF", "LBP", "DJF", "ETB", "TND", "XCD", "SRD", "GNF", "BGN", "GTQ", "MWK", "ZMW", "MKD", "HUF", "PEN", "RWF", "DKK", "BZD", "IQD", "ANG", "ARS", "GBP", "WST", "ZWL", "PGK", "TRY", "KES", "MDL", "MNT", "CDF", "BAM", "LRD", "JPY", "GMD", "STN", "VND", "BWP", "OMR", "NOK", "SLL", "JMD", "XOF", "MMK", "EGP", "AWG", "ILS", "UZS", "BSD" ] }, { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay", "DinersClub", "Interac", "CartesBancaires" ], "supported_countries": [ "NL", "ES", "DE", "PL", "IT", "AE", "GB", "ZA", "FR" ], "supported_currencies": [ "JOD", "AED", "ALL", "BOB", "ERN", "LBP", "PAB", "HNL", "AZN", "TMT", "DKK", "AWG", "PKR", "LAK", "PGK", "JMD", "CUP", "PHP", "BAM", "THB", "FKP", "HRK", "UYU", "KZT", "BYN", "PLN", "SDG", "VND", "NZD", "KWD", "CDF", "SCR", "VUV", "CHF", "USD", "GYD", "ANG", "DOP", "MKD", "STN", "SAR", "QAR", "PEN", "RSD", "BRL", "KGS", "SGD", "TWD", "BHD", "KHR", "MOP", "GHS", "UGX", "XPF", "SSP", "CAD", "TOP", "OMR", "MXN", "BGN", "RUB", "MDL", "GNF", "PYG", "SRD", "AFN", "MNT", "NOK", "XAF", "BWP", "NGN", "GIP", "CZK", "MGA", "DZD", "YER", "DJF", "SBD", "CNY", "ZAR", "LYD", "BMD", "MUR", "NIO", "UZS", "GBP", "VES", "SVC", "CVE", "NPR", "RON", "KMF", "BZD", "KPW", "SLL", "LKR", "AUD", "LSL", "XCD", "TJS", "KYD", "UAH", "ARS", "NAD", "SEK", "GTQ", "BSD", "IDR", "WST", "AMD", "BTN", "HUF", "ZMW", "COP", "BIF", "FJD", "INR", "IRR", "GEL", "HTG", "SOS", "CLP", "ISK", "MVR", "RWF", "BBD", "KRW", "BDT", "LRD", "AOA", "MMK", "MWK", "SLE", "XOF", "MRU", "KES", "MYR", "MZN", "SYP", "SZL", "TRY", "SHP", "TTD", "GMD", "TZS", "ETB", "ILS", "IQD", "CRC", "BND", "HKD", "EGP", "JPY", "MAD", "TND", "EUR", "ZWL" ] } ], "supported_webhook_flows": [] }, { "name": "TSYS", "display_name": "Tsys", "description": "TSYS, a Global Payments company, is the payment stack for the future, powered by unmatched expertise.", "category": "bank_acquirer", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay" ], "supported_countries": [ "NA" ], "supported_currencies": [ "CUP", "SZL", "GMD", "AMD", "MRU", "BWP", "SSP", "QAR", "XOF", "VES", "XAF", "BBD", "BSD", "ETB", "GBP", "BHD", "UYU", "XCD", "JPY", "VUV", "SAR", "ZAR", "MOP", "MDL", "IRR", "SGD", "MVR", "BIF", "BTN", "STN", "AED", "TTD", "TWD", "UZS", "KZT", "ALL", "UGX", "DOP", "BMD", "FJD", "KGS", "KPW", "ZMW", "IQD", "HRK", "KMF", "GTQ", "LSL", "NOK", "MWK", "CDF", "KRW", "ERN", "RUB", "GEL", "MGA", "OMR", "HUF", "HTG", "PYG", "MUR", "HKD", "BZD", "LRD", "SRD", "THB", "IDR", "TJS", "TRY", "VND", "JOD", "PKR", "GNF", "LKR", "TND", "BDT", "DJF", "SDG", "AOA", "SVC", "PEN", "KYD", "BRL", "JMD", "ISK", "COP", "BAM", "BOB", "CVE", "INR", "RWF", "SCR", "YER", "LYD", "MYR", "LBP", "CZK", "NIO", "SEK", "DKK", "UAH", "USD", "AZN", "RON", "HNL", "SYP", "CHF", "PAB", "NGN", "NPR", "AFN", "CAD", "ANG", "GYD", "MXN", "BND", "LAK", "PGK", "PLN", "SHP", "ARS", "KWD", "ILS", "TMT", "XPF", "ZWL", "FKP", "CLP", "AUD", "DZD", "GHS", "PHP", "NAD", "TZS", "CNY", "MAD", "NZD", "MNT", "WST", "KHR", "CRC", "SLE", "AWG", "GIP", "BGN", "RSD", "SOS", "MKD", "MMK", "TOP", "MZN", "BYN", "KES", "EGP", "EUR", "SBD" ] }, { "payment_method": "card", "payment_method_type": "debit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay" ], "supported_countries": [ "NA" ], "supported_currencies": [ "AZN", "SAR", "ZWL", "MRU", "SZL", "TRY", "TOP", "YER", "LKR", "ISK", "NIO", "TTD", "BMD", "PAB", "MNT", "BTN", "SYP", "HUF", "CHF", "UAH", "DJF", "DOP", "XPF", "MVR", "WST", "ZMW", "TMT", "TWD", "LBP", "PGK", "XOF", "ARS", "PLN", "MUR", "MZN", "NGN", "MDL", "SDG", "SLE", "VND", "STN", "KZT", "THB", "SGD", "HRK", "AUD", "NAD", "KHR", "BSD", "GEL", "NOK", "KPW", "GNF", "GHS", "MWK", "RUB", "MAD", "GMD", "BWP", "VUV", "GTQ", "BZD", "MYR", "BND", "KMF", "CVE", "SSP", "BBD", "ALL", "UZS", "ERN", "GYD", "CUP", "TJS", "CZK", "OMR", "GIP", "XCD", "CNY", "SBD", "RON", "KES", "HKD", "IQD", "BDT", "CDF", "SEK", "JPY", "HNL", "ETB", "GBP", "VES", "TZS", "MXN", "XAF", "CLP", "AMD", "LAK", "EGP", "NZD", "SCR", "SHP", "ILS", "KRW", "SOS", "MGA", "JMD", "ZAR", "NPR", "BAM", "BIF", "EUR", "UYU", "CRC", "RSD", "TND", "PKR", "SRD", "AED", "BOB", "INR", "MOP", "USD", "PEN", "LRD", "UGX", "MMK", "KGS", "BRL", "SVC", "FKP", "ANG", "MKD", "BGN", "BHD", "PHP", "IRR", "KYD", "RWF", "LSL", "QAR", "DKK", "IDR", "DZD", "LYD", "AWG", "AFN", "KWD", "BYN", "JOD", "AOA", "HTG", "COP", "FJD", "CAD", "PYG" ] } ], "supported_webhook_flows": [] }, ] } ```
[ "crates/hyperswitch_connectors/src/connectors/billwerk.rs", "crates/hyperswitch_connectors/src/connectors/fiservemea.rs", "crates/hyperswitch_connectors/src/connectors/tsys.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7492
Bug: ci: paypal ci failing ref: https://developer.paypal.com/docs/multiparty/checkout/advanced/customize/3d-secure/test/ replacing visa card with the mastercard fixed it upon testing. also fixe the assertion. 65 != 60
2025-03-12T06:39:17Z
## Description <!-- Describe your changes in detail --> <img width="861" alt="image" src="https://github.com/user-attachments/assets/d85ea702-cd5d-444b-86bd-1f5f50363d40" /> connector throws above error when using VISA card. Replacing that with MasterCard fixes it: <img width="1206" alt="image" src="https://github.com/user-attachments/assets/de44fa13-695b-4198-ba82-d603a9bafbe1" /> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> paypal ci is failing. #
833da1c3c5a0f006a689b05554c547205774c823
`CYPRESS_CONNECTOR=paypal npm run cypress:payments` ![image](https://github.com/user-attachments/assets/d8f52cc9-3bbb-45f3-97fc-6cdd713f6dc1)
[]
juspay/hyperswitch
juspay__hyperswitch-7488
Bug: feat(core): Add V2 Authentication to all available endpoints Introduces V2 authentication mechanisms for various admin and client-side APIs : - [ ] Add V2AdminApiAuth and modified AdminApiAuthWithMerchantIdFromRoute for V2 - [ ] Add V2ApiKeyAuth , V2AdminApiAuth and V2ClientAuth to the endpoints - [ ] Refactor functions to support V2 Auth as well as V1 Auth
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index b32fe76f5ec..d82bef27d1f 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -483,6 +483,6 @@ pub enum RevenueRecoveryError { PaymentIntentCreateFailed, #[error("Source verification failed for billing connector")] WebhookAuthenticationFailed, - #[error("Payment merchant connector account not found using acccount reference id")] + #[error("Payment merchant connector account not found using account reference id")] PaymentMerchantConnectorAccountNotFound, } diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index a38a9df72be..3cd959838a5 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -8,7 +8,7 @@ use crate::{ types::api::admin, }; -#[cfg(feature = "olap")] +#[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationCreate))] pub async fn organization_create( state: web::Data<AppState>, @@ -27,8 +27,26 @@ pub async fn organization_create( )) .await } - -#[cfg(feature = "olap")] +#[cfg(all(feature = "olap", feature = "v2"))] +#[instrument(skip_all, fields(flow = ?Flow::OrganizationCreate))] +pub async fn organization_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<admin::OrganizationCreateRequest>, +) -> HttpResponse { + let flow = Flow::OrganizationCreate; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _, req, _| create_organization(state, req), + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} +#[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationUpdate))] pub async fn organization_update( state: web::Data<AppState>, @@ -59,8 +77,38 @@ pub async fn organization_update( )) .await } - -#[cfg(feature = "olap")] +#[cfg(all(feature = "olap", feature = "v2"))] +#[instrument(skip_all, fields(flow = ?Flow::OrganizationUpdate))] +pub async fn organization_update( + state: web::Data<AppState>, + req: HttpRequest, + org_id: web::Path<common_utils::id_type::OrganizationId>, + json_payload: web::Json<admin::OrganizationUpdateRequest>, +) -> HttpResponse { + let flow = Flow::OrganizationUpdate; + let organization_id = org_id.into_inner(); + let org_id = admin::OrganizationId { + organization_id: organization_id.clone(), + }; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _, req, _| update_organization(state, org_id.clone(), req), + auth::auth_type( + &auth::V2AdminApiAuth, + &auth::JWTAuthOrganizationFromRoute { + organization_id, + required_permission: Permission::OrganizationAccountWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} +#[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationRetrieve))] pub async fn organization_retrieve( state: web::Data<AppState>, @@ -92,6 +140,38 @@ pub async fn organization_retrieve( .await } +#[cfg(all(feature = "olap", feature = "v2"))] +#[instrument(skip_all, fields(flow = ?Flow::OrganizationRetrieve))] +pub async fn organization_retrieve( + state: web::Data<AppState>, + req: HttpRequest, + org_id: web::Path<common_utils::id_type::OrganizationId>, +) -> HttpResponse { + let flow = Flow::OrganizationRetrieve; + let organization_id = org_id.into_inner(); + let payload = admin::OrganizationId { + organization_id: organization_id.clone(), + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, _, req, _| get_organization(state, req), + auth::auth_type( + &auth::V2AdminApiAuth, + &auth::JWTAuthOrganizationFromRoute { + organization_id, + required_permission: Permission::OrganizationAccountRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))] pub async fn merchant_account_create( @@ -144,15 +224,51 @@ pub async fn merchant_account_create( &req, new_request_payload_with_org_id, |state, _, req, _| create_merchant_account(state, req), - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))] +pub async fn retrieve_merchant_account( + state: web::Data<AppState>, + req: HttpRequest, + mid: web::Path<common_utils::id_type::MerchantId>, +) -> HttpResponse { + let flow = Flow::MerchantsAccountRetrieve; + let merchant_id = mid.into_inner(); + let payload = admin::MerchantId { + merchant_id: merchant_id.clone(), + }; + api::server_wrap( + flow, + state, + &req, + payload, + |state, _, req, _| get_merchant_account(state, req, None), + auth::auth_type( + &auth::AdminApiAuth, + &auth::JWTAuthMerchantFromRoute { + merchant_id, + // This should ideally be MerchantAccountRead, but since FE is calling this API for + // profile level users currently keeping this as ProfileAccountRead. FE is removing + // this API call for profile level users. + // TODO: Convert this to MerchantAccountRead once FE changes are done. + required_permission: Permission::ProfileAccountRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + ) + .await +} + /// Merchant Account - Retrieve /// /// Retrieve a merchant account details. +#[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))] pub async fn retrieve_merchant_account( state: web::Data<AppState>, @@ -171,7 +287,7 @@ pub async fn retrieve_merchant_account( payload, |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be MerchantAccountRead, but since FE is calling this API for @@ -207,7 +323,7 @@ pub async fn merchant_account_list( organization_id, |state, _, request, _| list_merchant_account(state, request), auth::auth_type( - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, @@ -248,6 +364,35 @@ pub async fn merchant_account_list( /// Merchant Account - Update /// /// To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))] +pub async fn update_merchant_account( + state: web::Data<AppState>, + req: HttpRequest, + mid: web::Path<common_utils::id_type::MerchantId>, + json_payload: web::Json<admin::MerchantAccountUpdate>, +) -> HttpResponse { + let flow = Flow::MerchantsAccountUpdate; + let merchant_id = mid.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), + auth::auth_type( + &auth::V2AdminApiAuth, + &auth::JWTAuthMerchantFromRoute { + merchant_id: merchant_id.clone(), + required_permission: Permission::MerchantAccountWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} +#[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))] pub async fn update_merchant_account( state: web::Data<AppState>, @@ -279,6 +424,30 @@ pub async fn update_merchant_account( /// Merchant Account - Delete /// /// To delete a merchant account +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))] +pub async fn delete_merchant_account( + state: web::Data<AppState>, + req: HttpRequest, + mid: web::Path<common_utils::id_type::MerchantId>, +) -> HttpResponse { + let flow = Flow::MerchantsAccountDelete; + let mid = mid.into_inner(); + + let payload = web::Json(admin::MerchantId { merchant_id: mid }).into_inner(); + api::server_wrap( + flow, + state, + &req, + payload, + |state, _, req, _| merchant_account_delete(state, req.merchant_id), + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} + +#[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))] pub async fn delete_merchant_account( state: web::Data<AppState>, @@ -712,7 +881,7 @@ pub async fn connector_update( payload, |state, _, req, _| update_connector(state, &merchant_id, None, &id, req), auth::auth_type( - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorWrite, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 8c0b7137662..911617753d4 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -268,7 +268,7 @@ pub async fn api_key_revoke( (&merchant_id, &key_id), |state, _, (merchant_id, key_id), _| api_keys::revoke_api_key(state, merchant_id, key_id), auth::auth_type( - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyWrite, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index c793e3c85e5..c9ff466af00 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -8,7 +8,34 @@ use crate::{ services::{api, authentication as auth, authorization::permissions::Permission}, types::api::customers, }; - +#[cfg(all(feature = "v2", feature = "customer_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))] +pub async fn customers_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<customers::CustomerRequest>, +) -> HttpResponse { + let flow = Flow::CustomersCreate; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, req, _| { + create_customer(state, auth.merchant_account, auth.key_store, req) + }, + auth::auth_type( + &auth::V2ApiKeyAuth, + &auth::JWTAuth { + permission: Permission::MerchantCustomerWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))] pub async fn customers_create( state: web::Data<AppState>, @@ -115,7 +142,42 @@ pub async fn customers_retrieve( )) .await } +#[cfg(all(feature = "v2", feature = "customer_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::CustomersList))] +pub async fn customers_list( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<customers::CustomerListRequest>, +) -> HttpResponse { + let flow = Flow::CustomersList; + let payload = query.into_inner(); + api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, request, _| { + list_customers( + state, + auth.merchant_account.get_id().to_owned(), + None, + auth.key_store, + request, + ) + }, + auth::auth_type( + &auth::V2ApiKeyAuth, + &auth::JWTAuth { + permission: Permission::MerchantCustomerRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + ) + .await +} +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::CustomersList))] pub async fn customers_list( state: web::Data<AppState>, @@ -219,7 +281,7 @@ pub async fn customers_update( ) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, @@ -249,7 +311,7 @@ pub async fn customers_delete( delete_customer(state, auth.merchant_account, id, auth.key_store) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index 64b46eb2f55..5a802cb4c5a 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -78,7 +78,7 @@ pub async fn client_secret_create( req.headers(), ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -99,7 +99,7 @@ pub async fn client_secret_delete( &req, payload, |state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req), - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 92f16b6c4c7..ec5e1dacf0a 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -95,7 +95,7 @@ pub async fn create_payment_method_api( )) .await }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -214,7 +214,7 @@ pub async fn payment_method_retrieve_api( auth.merchant_account, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -246,7 +246,7 @@ pub async fn payment_method_delete_api( auth.merchant_account, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -613,7 +613,7 @@ pub async fn list_customer_payment_method_api( ) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 9708f34c53c..4e670a594a5 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -147,9 +147,9 @@ pub async fn payments_create_intent( ) }, match env::which() { - env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth), + env::Env::Production => &auth::V2ApiKeyAuth, _ => auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, @@ -210,7 +210,7 @@ pub async fn payments_get_intent( auth.platform_merchant_account, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -249,9 +249,9 @@ pub async fn payments_create_and_confirm_intent( ) }, match env::which() { - env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth), + env::Env::Production => &auth::V2ApiKeyAuth, _ => auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, @@ -313,7 +313,7 @@ pub async fn payments_update_intent( auth.platform_merchant_account, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -825,7 +825,7 @@ pub async fn payments_connector_session( tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { - global_payment_id, + global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; @@ -868,7 +868,9 @@ pub async fn payments_connector_session( auth.platform_merchant_account, ) }, - &auth::HeaderAuth(auth::PublishableKeyAuth), + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), locking_action, )) .await @@ -1247,7 +1249,7 @@ pub async fn payments_list( payments::list_payments(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, @@ -2423,7 +2425,7 @@ pub async fn payment_confirm_intent( tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { - global_payment_id, + global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; @@ -2468,7 +2470,9 @@ pub async fn payment_confirm_intent( )) .await }, - &auth::PublishableKeyAuth, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), locking_action, )) .await @@ -2540,7 +2544,7 @@ pub async fn proxy_confirm_intent( header_payload.clone(), )) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, locking_action, )) .await @@ -2611,7 +2615,7 @@ pub async fn payment_status( .await }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, @@ -2657,7 +2661,7 @@ pub async fn payment_get_intent_using_merchant_reference_id( )) .await }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -2776,7 +2780,7 @@ pub async fn payments_capture( .await }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileAccountWrite, }, @@ -2802,7 +2806,7 @@ pub async fn list_payment_methods( tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { - global_payment_id, + global_payment_id: global_payment_id.clone(), payload, }; @@ -2829,7 +2833,9 @@ pub async fn list_payment_methods( &header_payload, ) }, - &auth::PublishableKeyAuth, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index ac0f997a278..04a0d331688 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -82,7 +82,7 @@ pub async fn routing_create_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, @@ -170,7 +170,7 @@ pub async fn routing_link_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::ApiKeyAuth, + &auth::V2ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::MerchantRoutingWrite, @@ -252,7 +252,7 @@ pub async fn routing_retrieve_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, @@ -373,7 +373,7 @@ pub async fn routing_unlink_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::ApiKeyAuth, + &auth::V2ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingWrite, @@ -459,7 +459,7 @@ pub async fn routing_update_default_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, @@ -535,7 +535,7 @@ pub async fn routing_retrieve_default_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingRead, @@ -749,7 +749,7 @@ pub async fn upsert_decision_manager_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, @@ -818,7 +818,7 @@ pub async fn retrieve_decision_manager_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, @@ -976,7 +976,7 @@ pub async fn routing_retrieve_linked_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 502ebb5099f..4eb91756661 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -1064,6 +1064,44 @@ where } } +#[derive(Debug, Default)] +pub struct V2AdminApiAuth; + +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for V2AdminApiAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let header_map_struct = HeaderMapStruct::new(request_headers); + let auth_string = header_map_struct.get_auth_string_from_header()?; + let request_admin_api_key = auth_string + .split(',') + .find_map(|part| part.trim().strip_prefix("admin-api-key=")) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Unable to parse admin_api_key") + })?; + if request_admin_api_key.is_empty() { + return Err(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Api key is empty"); + } + let conf = state.conf(); + + let admin_api_key = &conf.secrets.get_inner().admin_api_key; + + if request_admin_api_key != admin_api_key.peek() { + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure"))?; + } + + Ok(((), AuthenticationType::AdminApiKey)) + } +} #[derive(Debug)] pub struct AdminApiAuthWithMerchantIdFromRoute(pub id_type::MerchantId); @@ -1130,7 +1168,7 @@ where throw_error_if_platform_merchant_authentication_required(request_headers)?; } - AdminApiAuth + V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1194,7 +1232,7 @@ where throw_error_if_platform_merchant_authentication_required(request_headers)?; } - AdminApiAuth + V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1400,7 +1438,7 @@ where throw_error_if_platform_merchant_authentication_required(request_headers)?; } - AdminApiAuth + V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1465,7 +1503,7 @@ where throw_error_if_platform_merchant_authentication_required(request_headers)?; } - AdminApiAuth + V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?;
2025-03-12T04:05:17Z
## Description This commit introduces V2 authentication mechanisms for various admin and client-side APIs : - [x] Added V2AdminApiAuth and modified AdminApiAuthWithMerchantIdFromRoute for V2 - [x] Added V2ApiKeyAuth , V2AdminApiAuth and V2ClientAuth to the endpoints - [x] Refactored functions to support V2 Auth as well as V1 Auth ## Motivation and Context # #[async_trait] impl<A> AuthenticateAndFetch<(), A> for V2AdminApiAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let header_map_struct = HeaderMapStruct::new(&request_headers); let auth_string = header_map_struct.get_auth_string_from_header()?; let request_admin_api_key = auth_string .split(',') .find_map(|part| part.trim().strip_prefix("admin-api-key=")) .ok_or_else(|| { report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Unable to parse admin_api_key") })?; if request_admin_api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Api key is empty"); } let conf = state.conf(); let admin_api_key = &conf.secrets.get_inner().admin_api_key; if request_admin_api_key != admin_api_key.peek() { Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Authentication Failure"))?; } Ok(((), AuthenticationType::AdminApiKey)) } } ``` ### What changes are done in authorization header How it was earlier? ``` api-key = {{api-key}} client-secret={{client_secret}} api-key = {{admin_api_key}} ``` Changed version ``` Authorization = api-key={{api-key}} Authorization = admin-api-key={{admin_api_key}} Authorization = publishable-key={{publishable_key}},client-secret={{client_secret}} ```
4f6174d1bf6dd0713b0a3d8e005671c884555144
For `/v2/merchant-accounts` Request ``` curl --location 'http://localhost:8080/v2/merchant-accounts' \ --header 'x-organization-id: org_d2lZPiRPOGbIMmFcb59A' \ --header 'Content-Type: application/json' \ --header 'Authorization: admin-api-key=test_admin' \ --data '{ "merchant_name": "cloth_seller" }' ``` Response ``` { "id": "cloth_seller_KdjFPBxrxWyX09jri2VB", "merchant_name": "cloth_seller", "merchant_details": null, "publishable_key": "pk_dev_735cafe5f43446e88d22bedec15b0139", "metadata": null, "organization_id": "org_d2lZPiRPOGbIMmFcb59A", "recon_status": "not_requested", "product_type": "orchestration" } ``` For `/v2/organization` Request ``` curl --location 'http://localhost:8080/v2/organization' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'Content-Type: application/json' \ --data '{ "organization_name": "random_org_1741776562" }' ``` Response ``` { "id": "org_m4fLYdEFb7PNHynIfmZO", "organization_name": "random_org_1741776558", "organization_details": null, "metadata": null, "modified_at": "2025-03-12 10:49:18.475431", "created_at": "2025-03-12 10:49:18.475424" } ``` This is how V2AdminApiAuth looks like ``` pub struct V2AdminApiAuth; #[async_trait] impl<A> AuthenticateAndFetch<(), A> for V2AdminApiAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let header_map_struct = HeaderMapStruct::new(&request_headers); let auth_string = header_map_struct.get_auth_string_from_header()?; let request_admin_api_key = auth_string .split(',') .find_map(|part| part.trim().strip_prefix("admin-api-key=")) .ok_or_else(|| { report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Unable to parse admin_api_key") })?; if request_admin_api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Api key is empty"); } let conf = state.conf(); let admin_api_key = &conf.secrets.get_inner().admin_api_key; if request_admin_api_key != admin_api_key.peek() { Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Authentication Failure"))?; } Ok(((), AuthenticationType::AdminApiKey)) } } ``` ### What changes are done in authorization header How it was earlier? ``` api-key = {{api-key}} client-secret={{client_secret}} api-key = {{admin_api_key}} ``` Changed version ``` Authorization = api-key={{api-key}} Authorization = admin-api-key={{admin_api_key}} Authorization = publishable-key={{publishable_key}},client-secret={{client_secret}} ```
[ "crates/router/src/core/errors.rs", "crates/router/src/routes/admin.rs", "crates/router/src/routes/api_keys.rs", "crates/router/src/routes/customers.rs", "crates/router/src/routes/ephemeral_key.rs", "crates/router/src/routes/payment_methods.rs", "crates/router/src/routes/payments.rs", "crates/router/src/routes/routing.rs", "crates/router/src/services/authentication.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7600
Bug: [FEATURE] Single-Use PSP tokenization for making a payment ### Feature Description Have a single use PSP tokenisation feature which creates a token at PSP end for the payment methods service and return it to the user for using the same for using it to make payments ### Possible Implementation Add it to the confirm call of the payment method session call where we decided to create a Payment Method for the request given ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index a9de9611e56..9f641ddff62 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -19487,7 +19487,8 @@ "type": "object", "description": "The Payment Service Provider Configuration for payment methods that are created using the payment method session", "required": [ - "tokenization_type" + "tokenization_type", + "connector_id" ], "properties": { "tokenization_type": { @@ -19495,8 +19496,7 @@ }, "connector_id": { "type": "string", - "description": "The merchant connector id to be used for tokenization", - "nullable": true + "description": "The merchant connector id to be used for tokenization" } } }, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 56bffc02640..1dfa9ce9d42 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -455,6 +455,15 @@ impl PaymentMethodCreate { _ => false, } } + pub fn get_tokenize_connector_id( + &self, + ) -> Result<id_type::MerchantConnectorAccountId, error_stack::Report<errors::ValidationError>> + { + self.psp_tokenization + .clone() + .get_required_value("psp_tokenization") + .map(|psp| psp.connector_id) + } } #[cfg(all( diff --git a/crates/common_types/src/payment_methods.rs b/crates/common_types/src/payment_methods.rs index 79cf34e1103..c6b492a1030 100644 --- a/crates/common_types/src/payment_methods.rs +++ b/crates/common_types/src/payment_methods.rs @@ -162,6 +162,6 @@ pub struct PspTokenization { pub tokenization_type: common_enums::TokenizationType, /// The merchant connector id to be used for tokenization - #[schema(value_type = Option<String>)] - pub connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + #[schema(value_type = String)] + pub connector_id: common_utils::id_type::MerchantConnectorAccountId, } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 1f99e5cbfb5..f69b9dc6855 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -6,6 +6,8 @@ use api_models::{ }, }; use common_enums::enums as api_enums; +#[cfg(feature = "v2")] +use common_utils::ext_traits::OptionExt; use common_utils::{ id_type, new_type::{ @@ -16,7 +18,6 @@ use common_utils::{ use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::Date; - // We need to derive Serialize and Deserialize because some parts of payment method data are being // stored in the database as serde_json::Value #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] @@ -688,6 +689,40 @@ pub enum MobilePaymentData { }, } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData { + type Error = error_stack::Report<common_utils::errors::ValidationError>; + + fn try_from(value: payment_methods::PaymentMethodCreateData) -> Result<Self, Self::Error> { + match value { + payment_methods::PaymentMethodCreateData::Card(payment_methods::CardDetail { + card_number, + card_exp_month, + card_exp_year, + card_cvc, + card_issuer, + card_network, + card_type, + card_issuing_country, + nick_name, + card_holder_name, + }) => Ok(Self::Card(Card { + card_number, + card_exp_month, + card_exp_year, + card_cvc: card_cvc.get_required_value("card_cvc")?, + card_issuer, + card_network, + card_type: card_type.map(|card_type| card_type.to_string()), + card_issuing_country: card_issuing_country.map(|country| country.to_string()), + bank_code: None, + nick_name, + card_holder_name, + })), + } + } +} + impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self { match api_model_payment_method_data { @@ -1891,6 +1926,26 @@ impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod { } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct SingleUsePaymentMethodToken { + pub token: Secret<String>, + pub merchant_connector_id: id_type::MerchantConnectorAccountId, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl SingleUsePaymentMethodToken { + pub fn get_single_use_token_from_payment_method_token( + token: Secret<String>, + mca_id: id_type::MerchantConnectorAccountId, + ) -> Self { + Self { + token, + merchant_connector_id: mca_id, + } + } +} + impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDetailsPaymentMethod { fn from(item: NetworkTokenDetailsPaymentMethod) -> Self { Self { @@ -1908,3 +1963,19 @@ impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDet } } } + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct SingleUseTokenKey(String); + +#[cfg(feature = "v2")] +impl SingleUseTokenKey { + pub fn store_key(payment_method_id: &id_type::GlobalPaymentMethodId) -> Self { + let new_token = format!("single_use_token_{}", payment_method_id.get_string_repr()); + Self(new_token) + } + + pub fn get_store_key(&self) -> &str { + &self.0 + } +} diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index b6911f1f562..f06343ff9b4 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -464,6 +464,7 @@ pub struct MultibancoCreditTransferSourceRequest { #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripePaymentMethodData { + CardToken(StripeCardToken), Card(StripeCardData), PayLater(StripePayLaterData), Wallet(StripeWallet), @@ -472,6 +473,19 @@ pub enum StripePaymentMethodData { BankTransfer(StripeBankTransferData), } +// Struct to call the Stripe tokens API to create a PSP token for the card details provided +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct StripeCardToken { + #[serde(rename = "card[number]")] + pub token_card_number: cards::CardNumber, + #[serde(rename = "card[exp_month]")] + pub token_card_exp_month: Secret<String>, + #[serde(rename = "card[exp_year]")] + pub token_card_exp_year: Secret<String>, + #[serde(rename = "card[cvc]")] + pub token_card_cvc: Secret<String>, +} + #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(tag = "payment_method_data[type]")] pub enum BankDebitData { @@ -2094,15 +2108,30 @@ impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { impl TryFrom<&types::TokenizationRouterData> for TokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { - let payment_data = create_stripe_payment_method( - &item.request.payment_method_data, - item.auth_type, - item.payment_method_token.clone(), - None, - StripeBillingAddress::default(), - )?; + // Card flow for tokenization is handled seperately because of API contact difference + let request_payment_data = match &item.request.payment_method_data { + domain::PaymentMethodData::Card(card_details) => { + StripePaymentMethodData::CardToken(StripeCardToken { + token_card_number: card_details.card_number.clone(), + token_card_exp_month: card_details.card_exp_month.clone(), + token_card_exp_year: card_details.card_exp_year.clone(), + token_card_cvc: card_details.card_cvc.clone(), + }) + } + _ => { + create_stripe_payment_method( + &item.request.payment_method_data, + item.auth_type, + item.payment_method_token.clone(), + None, + StripeBillingAddress::default(), + )? + .0 + } + }; + Ok(Self { - token_data: payment_data.0, + token_data: request_payment_data, }) } } diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index e368a94b488..43041ef01b6 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -235,3 +235,12 @@ pub(crate) const SENDER_ID: &[u8] = b"Google"; /// Default value for the number of attempts to retry fetching forex rates pub const DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS: u64 = 3; + +/// Default payment intent id +pub const IRRELEVANT_PAYMENT_INTENT_ID: &str = "irrelevant_payment_intent_id"; + +/// Default payment attempt id +pub const IRRELEVANT_PAYMENT_ATTEMPT_ID: &str = "irrelevant_payment_attempt_id"; + +// Default payment method storing TTL in redis in seconds +pub const DEFAULT_PAYMENT_METHOD_STORE_TTL: i64 = 86400; // 1 day diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 27fb3959bfe..100b10012bc 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -15,7 +15,6 @@ pub mod transformers; pub mod utils; mod validator; pub mod vault; - use std::borrow::Cow; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use std::collections::HashSet; @@ -34,6 +33,7 @@ use common_utils::{consts::DEFAULT_LOCALE, id_type}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_utils::{ crypto::Encryptable, + errors::CustomResult, ext_traits::{AsyncExt, Encode, ValueExt}, fp_utils::when, generate_id, types as util_types, @@ -59,6 +59,8 @@ use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; use time::Duration; +#[cfg(feature = "v2")] +use super::payments::tokenization; use super::{ errors::{RouterResponse, StorageErrorExt}, pm_auth, @@ -67,24 +69,28 @@ use super::{ use crate::{ configs::settings, core::{payment_methods::transformers as pm_transforms, payments as payments_core}, + db::errors::ConnectorErrorExt, headers, logger, routes::{self, payment_methods as pm_routes}, services::encryption, types::{ + self, api::{self, payment_methods::PaymentMethodCreateExt}, domain::types as domain_types, payment_methods as pm_types, storage::{ephemeral_key, PaymentMethodListContext}, transformers::{ForeignFrom, ForeignTryFrom}, + Tokenizable, }, utils::ext_traits::OptionExt, }; use crate::{ consts, core::{ - errors::{self, RouterResult}, + errors::{ProcessTrackerError, RouterResult}, payments::helpers as payment_helpers, }, + errors, routes::{app::StorageInterface, SessionState}, services, types::{ @@ -206,7 +212,7 @@ pub async fn initiate_pm_collect_link( ) .await?; - // Create DB entries + // Create DB entrie let pm_collect_link = create_pm_collect_db_entry( &state, &merchant_account, @@ -466,7 +472,7 @@ pub async fn add_payment_method_status_update_task( prev_status: enums::PaymentMethodStatus, curr_status: enums::PaymentMethodStatus, merchant_id: &id_type::MerchantId, -) -> Result<(), errors::ProcessTrackerError> { +) -> Result<(), ProcessTrackerError> { let created_at = payment_method.created_at; let schedule_time = created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); @@ -988,7 +994,7 @@ pub async fn create_payment_method_core( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let resp = pm_transforms::generate_payment_method_response(&payment_method)?; + let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok((resp, payment_method)) } @@ -1033,7 +1039,7 @@ pub async fn network_tokenize_and_vault_the_pmd( network_tokenization_enabled_for_profile: bool, customer_id: &id_type::GlobalCustomerId, ) -> Option<NetworkTokenPaymentMethodDetails> { - let network_token_pm_details_result: errors::CustomResult< + let network_token_pm_details_result: CustomResult< NetworkTokenPaymentMethodDetails, errors::NetworkTokenizationError, > = async { @@ -1272,7 +1278,7 @@ 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)?; + let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok(services::ApplicationResponse::Json(resp)) } @@ -1523,7 +1529,7 @@ pub async fn create_payment_method_for_intent( payment_method_billing_address: Option< Encryptable<hyperswitch_domain_models::address::Address>, >, -) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { +) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*state.store; let current_time = common_utils::date_time::now(); @@ -1758,7 +1764,7 @@ fn get_pm_list_context( } Some(payment_methods::PaymentMethodsData::BankDetails(bank_details)) => { let get_bank_account_token_data = - || -> errors::CustomResult<payment_methods::BankAccountTokenData, errors::ApiErrorResponse> { + || -> CustomResult<payment_methods::BankAccountTokenData,errors::ApiErrorResponse> { let connector_details = bank_details .connector_details .first() @@ -1885,7 +1891,14 @@ pub async fn retrieve_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - transformers::generate_payment_method_response(&payment_method) + let single_use_token_in_cache = get_single_use_token_from_store( + &state.clone(), + payment_method_data::SingleUseTokenKey::store_key(&pm_id.clone()), + ) + .await + .unwrap_or_default(); + + transformers::generate_payment_method_response(&payment_method, &single_use_token_in_cache) .map(services::ApplicationResponse::Json) } @@ -2006,7 +2019,7 @@ pub async fn update_payment_method_core( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let response = pm_transforms::generate_payment_method_response(&payment_method)?; + let response = pm_transforms::generate_payment_method_response(&payment_method, &None)?; // Add a PT task to handle payment_method delete from vault @@ -2545,7 +2558,7 @@ pub async fn payment_methods_session_confirm( let payment_method = create_payment_method_core( &state, &req_state, - create_payment_method_request, + create_payment_method_request.clone(), &merchant_account, &key_store, &profile, @@ -2578,7 +2591,18 @@ pub async fn payment_methods_session_confirm( tokenization_type: common_enums::TokenizationType::SingleUse, .. }) => { - todo!("single use tokenization are not implemented") + Box::pin(create_single_use_tokenization_flow( + state.clone(), + req_state.clone(), + merchant_account.clone(), + profile.clone(), + key_store.clone(), + &create_payment_method_request.clone(), + &payment_method, + &payment_method_session, + )) + .await?; + None } None => None, }; @@ -2650,3 +2674,194 @@ impl pm_types::SavedPMLPaymentsInfo { Ok(()) } } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[allow(clippy::too_many_arguments)] +async fn create_single_use_tokenization_flow( + state: SessionState, + req_state: routes::app::ReqState, + merchant_account: domain::MerchantAccount, + profile: domain::Profile, + key_store: domain::MerchantKeyStore, + payment_method_create_request: &payment_methods::PaymentMethodCreate, + payment_method: &api::PaymentMethodResponse, + payment_method_session: &domain::payment_methods::PaymentMethodSession, +) -> RouterResult<()> { + let customer_id = payment_method_create_request.customer_id.to_owned(); + let connector_id = payment_method_create_request + .get_tokenize_connector_id() + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "psp_tokenization.connector_id", + }) + .attach_printable("Failed to get tokenize connector id")?; + + let db = &state.store; + + let merchant_connector_account_details = db + .find_merchant_connector_account_by_id(&(&state).into(), &connector_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: connector_id.get_string_repr().to_owned(), + }) + .attach_printable("error while fetching merchant_connector_account from connector_id")?; + let auth_type = merchant_connector_account_details + .get_connector_account_details() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while parsing value for ConnectorAuthType")?; + + let payment_method_data_request = types::PaymentMethodTokenizationData { + payment_method_data: payment_method_data::PaymentMethodData::try_from( + payment_method_create_request.payment_method_data.clone(), + ) + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "card_cvc", + }) + .attach_printable( + "Failed to convert type from Payment Method Create Data to Payment Method Data", + )?, + browser_info: None, + currency: api_models::enums::Currency::default(), + amount: None, + }; + + let payment_method_session_address = types::PaymentAddress::new( + None, + payment_method_session + .billing + .clone() + .map(|address| address.into_inner()), + None, + None, + ); + + let mut router_data = + types::RouterData::<api::PaymentMethodToken, _, types::PaymentsResponseData> { + flow: std::marker::PhantomData, + merchant_id: merchant_account.get_id().clone(), + customer_id: None, + connector_customer: None, + connector: merchant_connector_account_details + .connector_name + .to_string(), + payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_string(), //Static + attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), //Static + tenant_id: state.tenant.tenant_id.clone(), + status: common_enums::enums::AttemptStatus::default(), + payment_method: common_enums::enums::PaymentMethod::Card, + connector_auth_type: auth_type, + description: None, + address: payment_method_session_address, + auth_type: common_enums::enums::AuthenticationType::default(), + connector_meta_data: None, + connector_wallets_details: None, + amount_captured: None, + access_token: None, + session_token: None, + reference_id: None, + payment_method_token: None, + recurring_mandate_payment_data: None, + preprocessing_id: None, + payment_method_balance: None, + connector_api_version: None, + request: payment_method_data_request.clone(), + response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), + connector_request_reference_id: payment_method_session.id.get_string_repr().to_string(), + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + test_mode: None, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + frm_metadata: None, + dispute_id: None, + refund_id: None, + connector_response: None, + payment_method_status: None, + minor_amount_captured: None, + integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, + connector_mandate_request_reference_id: None, + authentication_id: None, + psd2_sca_exemption_type: None, + }; + + let payment_method_token_response = tokenization::add_token_for_payment_method( + &mut router_data, + payment_method_data_request.clone(), + state.clone(), + &merchant_connector_account_details.clone(), + ) + .await?; + + let token_response = payment_method_token_response.token.map_err(|err| { + errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: (merchant_connector_account_details.clone()) + .connector_name + .to_string(), + status_code: err.status_code, + reason: err.reason, + } + })?; + + let value = payment_method_data::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token( + token_response.clone().into(), + connector_id.clone() + ); + + let key = payment_method_data::SingleUseTokenKey::store_key(&payment_method.id); + + add_single_use_token_to_store(&state, key, value) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to store single use token")?; + + Ok(()) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +async fn add_single_use_token_to_store( + state: &SessionState, + key: payment_method_data::SingleUseTokenKey, + value: payment_method_data::SingleUsePaymentMethodToken, +) -> CustomResult<(), errors::StorageError> { + let redis_connection = state + .store + .get_redis_conn() + .map_err(Into::<errors::StorageError>::into)?; + + redis_connection + .serialize_and_set_key_with_expiry( + &payment_method_data::SingleUseTokenKey::get_store_key(&key).into(), + value, + consts::DEFAULT_PAYMENT_METHOD_STORE_TTL, + ) + .await + .change_context(errors::StorageError::KVError) + .attach_printable("Failed to insert payment method token to redis")?; + Ok(()) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +async fn get_single_use_token_from_store( + state: &SessionState, + key: payment_method_data::SingleUseTokenKey, +) -> CustomResult<Option<payment_method_data::SingleUsePaymentMethodToken>, errors::StorageError> { + let redis_connection = state + .store + .get_redis_conn() + .map_err(Into::<errors::StorageError>::into)?; + + redis_connection + .get_and_deserialize_key::<Option<payment_method_data::SingleUsePaymentMethodToken>>( + &payment_method_data::SingleUseTokenKey::get_store_key(&key).into(), + "SingleUsePaymentMethodToken", + ) + .await + .change_context(errors::StorageError::KVError) + .attach_printable("Failed to get payment method token from redis") +} diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index a7817329607..56a31732859 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -6,6 +6,8 @@ use common_utils::{ request::RequestContent, }; use error_stack::ResultExt; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use hyperswitch_domain_models::payment_method_data; use josekit::jwe; use router_env::tracing_actix_web::RequestId; use serde::{Deserialize, Serialize}; @@ -548,6 +550,7 @@ pub fn generate_pm_vaulting_req_from_update_request( #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn generate_payment_method_response( payment_method: &domain::PaymentMethod, + single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>, ) -> errors::RouterResult<api::PaymentMethodResponse> { let pmd = payment_method .payment_method_data @@ -559,8 +562,7 @@ pub fn generate_payment_method_response( } _ => None, }); - - let connector_tokens = payment_method + let mut connector_tokens = payment_method .connector_mandate_details .as_ref() .and_then(|connector_token_details| connector_token_details.payments.clone()) @@ -570,7 +572,19 @@ pub fn generate_payment_method_response( .into_iter() .map(transformers::ForeignFrom::foreign_from) .collect::<Vec<_>>() - }); + }) + .unwrap_or_default(); + + if let Some(token) = single_use_token { + let connector_token_single_use = transformers::ForeignFrom::foreign_from(token); + connector_tokens.push(connector_token_single_use); + } + let connector_tokens = if connector_tokens.is_empty() { + None + } else { + Some(connector_tokens) + }; + let network_token_pmd = payment_method .network_token_payment_method_data .clone() @@ -1113,3 +1127,21 @@ impl } } } + +#[cfg(feature = "v2")] +impl transformers::ForeignFrom<&payment_method_data::SingleUsePaymentMethodToken> + for api_models::payment_methods::ConnectorTokenDetails +{ + fn foreign_from(token: &payment_method_data::SingleUsePaymentMethodToken) -> Self { + Self { + connector_id: token.clone().merchant_connector_id, + token_type: common_enums::TokenizationType::SingleUse, + status: api_enums::ConnectorTokenStatus::Active, + connector_token_request_reference_id: None, + original_payment_authorized_amount: None, + original_payment_authorized_currency: None, + metadata: None, + token: token.clone().token, + } + } +} diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 43d190edc74..1bc0152f4dd 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1343,3 +1343,68 @@ pub fn update_connector_mandate_details_status( payouts: None, })) } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub async fn add_token_for_payment_method( + router_data: &mut types::RouterData< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + >, + payment_method_data_request: types::PaymentMethodTokenizationData, + state: SessionState, + merchant_connector_account_details: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, +) -> RouterResult<types::PspTokenResult> { + let connector_id = merchant_connector_account_details.id.clone(); + let connector_data = api::ConnectorData::get_connector_by_name( + &(state.conf.connectors), + &merchant_connector_account_details + .connector_name + .to_string(), + api::GetToken::Connector, + Some(connector_id.clone()), + )?; + + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > = connector_data.connector.get_connector_integration(); + + let payment_method_token_response_data_type: Result< + types::PaymentsResponseData, + types::ErrorResponse, + > = Err(types::ErrorResponse::default()); + + let payment_method_token_router_data = + helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( + router_data.clone(), + payment_method_data_request.clone(), + payment_method_token_response_data_type, + ); + + let connector_integration_response = services::execute_connector_processing_step( + &state, + connector_integration, + &payment_method_token_router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payment_failed_response()?; + let payment_token_response = connector_integration_response.response.map(|res| { + if let types::PaymentsResponseData::TokenizationResponse { token } = res { + Ok(token) + } else { + Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get token from connector") + } + }); + + match payment_token_response { + Ok(token) => Ok(types::PspTokenResult { token: Ok(token?) }), + Err(error_response) => Ok(types::PspTokenResult { + token: Err(error_response), + }), + } +} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index ff9eef080a6..1e1509f8dbc 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -513,6 +513,10 @@ pub struct PaymentMethodTokenResult { pub is_payment_method_tokenization_performed: bool, } +pub struct PspTokenResult { + pub token: Result<String, ErrorResponse>, +} + #[derive(Debug, Clone, Copy)] pub enum Redirection { Redirect,
2025-03-11T19:13:41Z
## Description <!-- Describe your changes in detail --> Add single use token implementation for Payment Method Service The feature would help to provide a single use PSP token for creating payment ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
617adfa33fd543131b5c4d8983319bfdcaa6c425
Create Payment Method Session Request ```bash curl --location 'http://localhost:8080/v2/payment-methods-session' \ --header 'x-profile-id: pro_2A1cEgnP0mOT4rqUqLtt' \ --header 'Authorization: api-key=dev_KVJIPqLBqYEGWUSse6Bggow5xL2PkaWLMYcpgTGcvr334sCVwagyUNbrBOTRnESf' \ --header 'Content-Type: application/json' \ --data-raw '{ "customer_id": "12345_cus_0195ab1d3f807a80bd6611b1b71cd1d0", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" },"psp_tokenization": { "tokenization_type": "single_use", "connector_id": "mca_lWefajNQ9HaKiJUhvAZo" } }' ``` Response ```json { "id": "12345_pms_0195ab1d677970a3bf12c0c019d42f6b", "customer_id": "12345_cus_0195ab1d3f807a80bd6611b1b71cd1d0", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "single_use", "connector_id": "mca_lWefajNQ9HaKiJUhvAZo" }, "network_tokenization": null, "expires_at": "2025-03-18T21:31:25.850Z", "client_secret": "cs_0195ab1d677a73c2a9b18b77354ad4ae", "return_url": null, "next_action": null, "authentication_details": null, "associated_payment_methods": null } ``` Confirm call for the Payment method session with `tokenization_type` as `single_use` under `psp_tokenization` in the request Request ```bash curl --location 'http://localhost:8080/v2/payment-methods-session/12345_pms_0195ab1d677970a3bf12c0c019d42f6b/confirm' \ --header 'x-profile-id: pro_2A1cEgnP0mOT4rqUqLtt' \ --header 'Authorization: publishable-key=pk_dev_427ac8f9e07d403a9dc21d71be6725cb,client-secret=cs_0195ab1d677a73c2a9b18b77354ad4ae' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_KVJIPqLBqYEGWUSse6Bggow5xL2PkaWLMYcpgTGcvr334sCVwagyUNbrBOTRnESf' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "04", "card_exp_year": "40", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "psp_tokenization": { "tokenization_type": "single_use", "connector_id": "mca_wmwOLCiB3NoMv8YwyxcE" } }' ``` Response ```json { "id": "12345_pms_0195ab1d677970a3bf12c0c019d42f6b", "customer_id": "12345_cus_0195ab1d3f807a80bd6611b1b71cd1d0", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "single_use", "connector_id": "mca_lWefajNQ9HaKiJUhvAZo" }, "network_tokenization": null, "expires_at": "2025-03-18T21:31:25.850Z", "client_secret": "CLIENT_SECRET_REDACTED", "return_url": null, "next_action": null, "authentication_details": null, "associated_payment_methods": null } ``` The way the same is stored in the Storage ( Redis ) ```bash 127.0.0.1:6379> get single_use_token_12345_pm_0195d26b9d2b71f094ba39e9fd131ca8 "{\"token\":\"tok_1R6t2xD5R7gDAGffQLz0D4fj\",\"merchant_connector_id\":\"mca_lWefajNQ9HaKiJUhvAZo\"}" ``` Retrieve API for the payment method created Request ```bash curl --location 'http://localhost:8080/v2/payment-methods/12345_pm_0195d26b9d2b71f094ba39e9fd131ca8' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_2A1cEgnP0mOT4rqUqLtt' \ --header 'api-key: dev_KVJIPqLBqYEGWUSse6Bggow5xL2PkaWLMYcpgTGcvr334sCVwagyUNbrBOTRnESf' \ --header 'Authorization: publishable-key=pk_dev_427ac8f9e07d403a9dc21d71be6725cb, api-key=dev_KVJIPqLBqYEGWUSse6Bggow5xL2PkaWLMYcpgTGcvr334sCVwagyUNbrBOTRnESf' ``` Response ```bash { "id": "12345_pm_0195d26b9d2b71f094ba39e9fd131ca8", "merchant_id": "apka_apna_test_gvHKZJ8EatRCipXedizy", "customer_id": "12345_cus_0195ab1d3f807a80bd6611b1b71cd1d0", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": false, "created": "2025-03-26T12:27:02.827Z", "last_used_at": "2025-03-26T12:27:02.827Z", "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "04", "expiry_year": "28", "card_holder_name": "John Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "connector_tokens": [ { "connector_id": "mca_lWefajNQ9HaKiJUhvAZo", "token_type": "single_use", "status": "active", "connector_token_request_reference_id": null, "original_payment_authorized_amount": null, "original_payment_authorized_currency": null, "metadata": null, "token": "tok_1R6t2xD5R7gDAGffQLz0D4fj" } ], "network_token": null } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payment_methods.rs", "crates/common_types/src/payment_methods.rs", "crates/hyperswitch_domain_models/src/payment_method_data.rs", "crates/router/src/connector/stripe/transformers.rs", "crates/router/src/consts.rs", "crates/router/src/core/payment_methods.rs", "crates/router/src/core/payment_methods/transformers.rs", "crates/router/src/core/payments/tokenization.rs", "crates/router/src/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-7482
Bug: feat(analytics): modify authentication queries and add generate report for authentications Need to modify the authentication analytics queries to differentiate between **frictionless flow** and **challenge flow** through the authentication_type field. Introduce support for **authentication report generation**, similar to the existing reports for payments, refunds, and disputes.
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index a2640be6ead..bdcbdd86a94 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -165,6 +165,7 @@ pub async fn get_filters( .filter_map(|fil: AuthEventFilterRow| match dim { AuthEventDimensions::AuthenticationStatus => fil.authentication_status.map(|i| i.as_ref().to_string()), AuthEventDimensions::TransactionStatus => fil.trans_status.map(|i| i.as_ref().to_string()), + AuthEventDimensions::AuthenticationType => fil.authentication_type.map(|i| i.as_ref().to_string()), AuthEventDimensions::ErrorMessage => fil.error_message, AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index da8e0b7cfa3..5f65eeaa279 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -1,4 +1,5 @@ use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange}; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use diesel_models::enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use error_stack::ResultExt; @@ -54,6 +55,7 @@ where pub struct AuthEventFilterRow { pub authentication_status: Option<DBEnumWrapper<AuthenticationStatus>>, pub trans_status: Option<DBEnumWrapper<TransactionStatus>>, + pub authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>>, pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index fd94aac614c..a3d0fe7b683 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -41,6 +41,7 @@ pub struct AuthEventMetricRow { pub count: Option<i64>, pub authentication_status: Option<DBEnumWrapper<storage_enums::AuthenticationStatus>>, pub trans_status: Option<DBEnumWrapper<storage_enums::TransactionStatus>>, + pub authentication_type: Option<DBEnumWrapper<storage_enums::DecoupledAuthenticationType>>, pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 32c76385409..b82d1ef4c35 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -70,7 +70,10 @@ where .switch()?; query_builder - .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending) + .add_filter_in_range_clause( + "authentication_status", + &[AuthenticationStatus::Success, AuthenticationStatus::Failed], + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -103,6 +106,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 39df41f53aa..682e8a07f6b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -96,6 +96,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index cdb89b796dd..047511d477c 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -12,8 +12,8 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ query::{ - Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, - Window, + Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, + ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -45,11 +45,9 @@ where for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } + query_builder - .add_select_column(Aggregate::Count { - field: None, - alias: Some("count"), - }) + .add_select_column("sum(sign_flag) AS count") .switch()?; query_builder @@ -94,6 +92,11 @@ where .switch()?; } + query_builder + .add_order_by_clause("count", Order::Descending) + .attach_printable("Error adding order by clause") + .switch()?; + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) @@ -112,6 +115,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 37f9dfd1c1f..9342e9047e0 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -107,6 +107,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 039ef00dd6e..984350efe6b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -101,6 +101,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index beccc093b19..5a2a9400b20 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,11 +68,17 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; query_builder - .add_negative_filter_clause("authentication_status", "pending") + .add_filter_in_range_clause( + "authentication_status", + &[AuthenticationStatus::Success, AuthenticationStatus::Failed], + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -104,6 +111,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 4d07cffba94..279844388f2 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -99,6 +103,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 310a45f0530..91e8cc54289 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::AuthenticationStatus; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -72,7 +72,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -105,6 +108,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index 24857bfb840..b08edb10113 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "Y".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Frictionless, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -100,6 +104,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 79fef8a16d0..80417ac64bf 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::AuthenticationStatus; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -68,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "Y".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Frictionless, + ) .switch()?; query_builder @@ -105,6 +108,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index f698b1161a0..89f5cbd5b9c 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -1123,6 +1123,7 @@ pub struct ReportConfig { pub payment_function: String, pub refund_function: String, pub dispute_function: String, + pub authentication_function: String, pub region: String, } @@ -1151,6 +1152,7 @@ pub enum AnalyticsFlow { GeneratePaymentReport, GenerateDisputeReport, GenerateRefundReport, + GenerateAuthenticationReport, GetApiEventMetrics, GetApiEventFilters, GetConnectorEvents, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index d483ce43605..5effd9e70a7 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -19,7 +19,9 @@ use api_models::{ }, refunds::RefundStatus, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, @@ -506,6 +508,7 @@ impl_to_sql_for_to_string!( TransactionStatus, AuthenticationStatus, AuthenticationConnectors, + DecoupledAuthenticationType, Flow, &String, &bool, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index a6db92e753f..6a6237e6783 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -4,7 +4,9 @@ use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, @@ -100,6 +102,7 @@ db_type!(DisputeStatus); db_type!(AuthenticationStatus); db_type!(TransactionStatus); db_type!(AuthenticationConnectors); +db_type!(DecoupledAuthenticationType); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where @@ -208,6 +211,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -237,6 +245,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow Ok(Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, @@ -259,6 +268,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -277,6 +291,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow Ok(Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 5c2d4ed2064..2360e564642 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -3,7 +3,9 @@ use std::{ hash::{Hash, Hasher}, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use super::{NameDescription, TimeRange}; @@ -14,6 +16,8 @@ pub struct AuthEventFilters { #[serde(default)] pub trans_status: Vec<TransactionStatus>, #[serde(default)] + pub authentication_type: Vec<DecoupledAuthenticationType>, + #[serde(default)] pub error_message: Vec<String>, #[serde(default)] pub authentication_connector: Vec<AuthenticationConnectors>, @@ -42,6 +46,7 @@ pub enum AuthEventDimensions { #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, + AuthenticationType, ErrorMessage, AuthenticationConnector, MessageVersion, @@ -101,6 +106,7 @@ pub mod metric_behaviour { pub struct ChallengeAttemptCount; pub struct ChallengeSuccessCount; pub struct AuthenticationErrorMessage; + pub struct AuthenticationFunnel; } impl From<AuthEventMetrics> for NameDescription { @@ -125,6 +131,7 @@ impl From<AuthEventDimensions> for NameDescription { pub struct AuthEventMetricsBucketIdentifier { pub authentication_status: Option<AuthenticationStatus>, pub trans_status: Option<TransactionStatus>, + pub authentication_type: Option<DecoupledAuthenticationType>, pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, @@ -140,6 +147,7 @@ impl AuthEventMetricsBucketIdentifier { pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, + authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, @@ -148,6 +156,7 @@ impl AuthEventMetricsBucketIdentifier { Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, @@ -161,6 +170,7 @@ impl Hash for AuthEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.authentication_status.hash(state); self.trans_status.hash(state); + self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); self.error_message.hash(state); diff --git a/crates/api_models/src/analytics/sdk_events.rs b/crates/api_models/src/analytics/sdk_events.rs index b2abbbe00e1..9a749f1144e 100644 --- a/crates/api_models/src/analytics/sdk_events.rs +++ b/crates/api_models/src/analytics/sdk_events.rs @@ -114,6 +114,10 @@ pub enum SdkEventNames { ThreeDsMethod, LoaderChanged, DisplayThreeDsSdk, + ThreeDsSdkInit, + AreqParamsGeneration, + ChallengePresented, + ChallengeComplete, } pub mod metric_behaviour { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 858c16d052f..cc242f86a5b 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -90,6 +90,10 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) + .service( + web::resource("report/authentications") + .route(web::post().to(generate_merchant_authentication_report)), + ) .service( web::resource("metrics/sdk_events") .route(web::post().to(get_sdk_event_metrics)), @@ -190,6 +194,11 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) + .service( + web::resource("report/authentications").route( + web::post().to(generate_merchant_authentication_report), + ), + ) .service( web::resource("metrics/api_events") .route(web::post().to(get_merchant_api_events_metrics)), @@ -252,6 +261,10 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_org_payment_report)), ) + .service( + web::resource("report/authentications") + .route(web::post().to(generate_org_authentication_report)), + ) .service( web::resource("metrics/sankey") .route(web::post().to(get_org_sankey)), @@ -306,6 +319,11 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_profile_payment_report)), ) + .service( + web::resource("report/authentications").route( + web::post().to(generate_profile_authentication_report), + ), + ) .service( web::resource("api_event_logs") .route(web::get().to(get_profile_api_events)), @@ -1746,6 +1764,7 @@ pub mod routes { )) .await } + #[cfg(feature = "v1")] pub async fn generate_org_payment_report( state: web::Data<AppState>, @@ -1850,6 +1869,161 @@ pub mod routes { .await } + #[cfg(feature = "v1")] + pub async fn generate_merchant_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: Some(merchant_id.clone()), + auth: AuthInfo::MerchantLevel { + org_id: org_id.clone(), + merchant_ids: vec![merchant_id.clone()], + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::MerchantReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn generate_org_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let org_id = auth.merchant_account.get_org_id(); + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: None, + auth: AuthInfo::OrgLevel { + org_id: org_id.clone(), + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::OrganizationReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn generate_profile_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let profile_id = auth + .profile_id + .ok_or(report!(UserErrors::JwtProfileIdMissing)) + .change_context(AnalyticsError::AccessForbiddenError)?; + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: Some(merchant_id.clone()), + auth: AuthInfo::ProfileLevel { + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + profile_ids: vec![profile_id.clone()], + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::ProfileReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + /// # Panics /// /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
2025-03-11T17:25:35Z
## Description <!-- Describe your changes in detail --> This PR modifies authentication queries to improve the way we distinguish between authentication flows. Previously, `trans_status` was used for this purpose, but it has now been replaced with `authentication_type`, which more explicitly differentiates between **frictionless flow** and **challenge flow**. Additionally, this PR introduces support for **authentication report generation**, similar to the existing reports for payments, refunds, and disputes. ## Key Changes ### 1. **Updated Authentication Queries** - Replaced `trans_status` with `authentication_type` in authentication queries. - Ensures a clearer distinction between **frictionless flow** and **challenge flow** during authentication. ### 2. **Added Authentication Report Generation** - Introduced report generation for **authentications**, aligning with the existing reporting structure for `payments`, 'refunds` and `disputes`. ### Routes for the reporting service: - **Org level report**: `/analytics/v1/org/report/authentications` - **Merchant level report**: `/analytics/v1/merchant/report/authentications` - **Profile level report**: `/analytics/v1/profile/report/authentications` This PR resolves the data correctness issue raised here: [https://github.com/juspay/hyperswitch-cloud/issues/8727](https://github.com/juspay/hyperswitch-cloud/issues/8727) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Using `authentication_type` instead of `trans_status` improves accuracy in flow differentiation. - Authentication reporting enables better tracking and analytics for user authentication flows. # #### Authentication Attempt Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status IN ('success', 'failed') AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status = 'success' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Attempt Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'challenge' AND authentication_status in ('success', 'failed') AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Flow Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'challenge' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status = 'success' AND authentication_type = 'challenge' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Frictionless Flow Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'frictionless' AND created_at >= '1738402351' AND created_at <= '1740216751' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Frictionless Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'frictionless' AND authentication_status = 'success' AND created_at >= '1738402351' AND created_at <= '1740216751' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Funnel: (2nd step): ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status IS NOT NULL AND created_at >= '1738434600' AND created_at <= '1740734520' ) ``` #### Authentication Funnel: (3rd step): ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status IS NOT NULL AND authentication_status IN ('success', 'failed') AND created_at >= '1738434600' AND created_at <= '1740734520' ) ``` #### Authentication Error Message: ```bash SELECT error_message, sum(sign_flag) AS count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1741712401' AND authentication_status = 'failed' AND error_message IS NOT NULL AND created_at >= '1738434600' AND created_at <= '1740734520' ) GROUP BY error_message HAVING sum(sign_flag) >= '1' ORDER BY count desc ``` Sample Output: You should be able to receive an email with the authentication report to the email specified in the request. Similarly, just replace `org` with `merchant` and `profile` in the URL for the corresponding authentication report at the merchant and profile level.
5cdfe8325481909a8a1596f967303eff44ffbcec
Can check the test cases from the `How did you test it?` section from these 2 PRs: - [https://github.com/juspay/hyperswitch/pull/7451](https://github.com/juspay/hyperswitch/pull/7451) - [https://github.com/juspay/hyperswitch/pull/7433](https://github.com/juspay/hyperswitch/pull/7433) **Note**: The Response body should be validated from this PR for all the metrics: [https://github.com/juspay/hyperswitch/pull/7451](https://github.com/juspay/hyperswitch/pull/7451) Curl for Authentication Report: ```bash curl --location 'http://localhost:8080/analytics/v1/org/report/authentications' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNmNkZTA0NzYtMTFlMi00NGE5LTlkMjUtOTA5M2QzNDQwZjhlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzM1MDQxMjkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczNjYwNDY3OCwib3JnX2lkIjoib3JnX2pwanI5TkFEWlhqSENNYTU5MmF3IiwicHJvZmlsZV9pZCI6InByb19QRHUydVA3aWNuM2lXY0I3V0VVSSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.7_cuWH5XygVrtIDsbh7nusrjGcQ3jbcaPKhIOo3EbM8' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDU1MmY3YzctMmNjZC00ZmU3LThkM2ItY2U1M2ExMTJhZTIwIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNjk5OTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTg3MjgwMiwib3JnX2lkIjoib3JnX2hQamlOektmbmV6NG8wNjdVVlFwIiwicHJvZmlsZV9pZCI6InByb19kWWJpUm9NVkFkNDAwWEh6R3hYTiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.1bsDkYwwk8FtWrDEYdMIsjmH7DqWOVejX2GVseu68ZQ' \ --data-raw '{ "timeRange": { "startTime": "2025-01-08T13:56:15Z", "endTime": "2025-01-09T13:56:15.277Z" }, "emails": [ "[email protected]" ] }' ``` Queries: #### Authentication Attempt Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status IN ('success', 'failed') AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status = 'success' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Attempt Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'challenge' AND authentication_status in ('success', 'failed') AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Flow Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'challenge' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status = 'success' AND authentication_type = 'challenge' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Frictionless Flow Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'frictionless' AND created_at >= '1738402351' AND created_at <= '1740216751' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Frictionless Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'frictionless' AND authentication_status = 'success' AND created_at >= '1738402351' AND created_at <= '1740216751' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Funnel: (2nd step): ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status IS NOT NULL AND created_at >= '1738434600' AND created_at <= '1740734520' ) ``` #### Authentication Funnel: (3rd step): ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status IS NOT NULL AND authentication_status IN ('success', 'failed') AND created_at >= '1738434600' AND created_at <= '1740734520' ) ``` #### Authentication Error Message: ```bash SELECT error_message, sum(sign_flag) AS count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1741712401' AND authentication_status = 'failed' AND error_message IS NOT NULL AND created_at >= '1738434600' AND created_at <= '1740734520' ) GROUP BY error_message HAVING sum(sign_flag) >= '1' ORDER BY count desc ``` Sample Output: You should be able to receive an email with the authentication report to the email specified in the request. Similarly, just replace `org` with `merchant` and `profile` in the URL for the corresponding authentication report at the merchant and profile level.
[ "crates/analytics/src/auth_events/core.rs", "crates/analytics/src/auth_events/filters.rs", "crates/analytics/src/auth_events/metrics.rs", "crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs", "crates/analytics/src/auth_events/metrics/authentication_count.rs", "crates/analytics/src/auth_events/metrics/authentication_error_message.rs", "crates/analytics/src/auth_events/metrics/authentication_funnel.rs", "crates/analytics/src/auth_events/metrics/authentication_success_count.rs", "crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs", "crates/analytics/src/auth_events/metrics/challenge_flow_count.rs", "crates/analytics/src/auth_events/metrics/challenge_success_count.rs", "crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs", "crates/analytics/src/auth_events/metrics/frictionless_success_count.rs", "crates/analytics/src/lib.rs", "crates/analytics/src/query.rs", "crates/analytics/src/sqlx.rs", "crates/api_models/src/analytics/auth_events.rs", "crates/api_models/src/analytics/sdk_events.rs", "crates/router/src/analytics.rs" ]