repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
24
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-10-09 08:44:51
hints_text
stringlengths
11
235k
base_commit
stringlengths
40
40
juspay/hyperswitch
juspay__hyperswitch-9755
Bug: [BUG] Migration runner fails due to Just already present ### Description: In `docker-compose.yml`, the `migration-runner` service fails if we run `docker compose up` more than once, because, the `just` installer doesn't handle the case where just is already installed. ### Solution: Add a conditional check to run `just` installer only if `just` is not present already.
diff --git a/docker-compose.yml b/docker-compose.yml index e16dd74466b..4e2600c8344 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -63,7 +63,9 @@ services: bash -c " apt-get update && apt-get install -y curl xz-utils && curl --proto '=https' --tlsv1.2 -LsSf https://github.com/diesel-rs/diesel/releases/latest/download/diesel_cli-installer.sh | bash && - curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to /usr/local/bin && + if ! command -v just >/dev/null 2>&1; then + curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to /usr/local/bin + fi && export PATH="$${PATH}:$${HOME}/.cargo/bin" && just migrate" working_dir: /app
2025-10-08T10:15:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> The migration-runner service in the `docker-compose.yml` file fails during a second deployment as `just` installer raises `just already installed` error. This PR fixes that issue issue by adding a conditional statement which calls the just installer only when just command is not available. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> N/A ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Ran `docker compose up -d` twice. <img width="476" height="491" alt="Screenshot 2025-10-08 at 3 44 53 PM" src="https://github.com/user-attachments/assets/c9de99cd-ac3a-4ab9-8c4e-5a1bb8d48d84" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b52aafa8873fc4704bd69014cc457daf32d5523c
juspay/hyperswitch
juspay__hyperswitch-9715
Bug: Create indexes for tracker tables in v2_compatible_migrations
diff --git a/v2_compatible_migrations/2025-10-07-131000_add_indexes_on_id_columns/down.sql b/v2_compatible_migrations/2025-10-07-131000_add_indexes_on_id_columns/down.sql new file mode 100644 index 00000000000..fb18e635e20 --- /dev/null +++ b/v2_compatible_migrations/2025-10-07-131000_add_indexes_on_id_columns/down.sql @@ -0,0 +1,22 @@ +-- Drop unique indexes on id columns +-- This will remove the unique indexes created for id column performance optimization and data integrity + +-- tracker tables +DROP INDEX IF EXISTS customers_id_index; + +DROP INDEX IF EXISTS payment_intent_id_index; + +DROP INDEX IF EXISTS payment_attempt_id_index; + +DROP INDEX IF EXISTS payment_methods_id_index; + +DROP INDEX IF EXISTS refund_id_index; + +-- Accounts tables +DROP INDEX IF EXISTS business_profile_id_index; + +DROP INDEX IF EXISTS merchant_account_id_index; + +DROP INDEX IF EXISTS merchant_connector_account_id_index; + +DROP INDEX IF EXISTS organization_id_index; diff --git a/v2_compatible_migrations/2025-10-07-131000_add_indexes_on_id_columns/up.sql b/v2_compatible_migrations/2025-10-07-131000_add_indexes_on_id_columns/up.sql new file mode 100644 index 00000000000..a8e27af1485 --- /dev/null +++ b/v2_compatible_migrations/2025-10-07-131000_add_indexes_on_id_columns/up.sql @@ -0,0 +1,21 @@ +-- Create unique indexes on id columns for better query performance and data integrity + +-- Tracker Tables +CREATE UNIQUE INDEX IF NOT EXISTS customers_id_index ON customers (id); + +CREATE UNIQUE INDEX IF NOT EXISTS payment_intent_id_index ON payment_intent (id); + +CREATE UNIQUE INDEX IF NOT EXISTS payment_attempt_id_index ON payment_attempt (id); + +CREATE UNIQUE INDEX IF NOT EXISTS payment_methods_id_index ON payment_methods (id); + +CREATE UNIQUE INDEX IF NOT EXISTS refund_id_index ON refund (id); + +-- Accounts Tables +CREATE UNIQUE INDEX IF NOT EXISTS business_profile_id_index ON business_profile (id); + +CREATE UNIQUE INDEX IF NOT EXISTS merchant_account_id_index ON merchant_account (id); + +CREATE UNIQUE INDEX IF NOT EXISTS merchant_connector_account_id_index ON merchant_connector_account (id); + +CREATE UNIQUE INDEX IF NOT EXISTS organization_id_index ON organization (id);
2025-10-07T08:02:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Since `id` column is introduced as varchar for a few major tracker tables in v2, index creation was missed in v2_compatible_migrations directory. This PR includes that. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To improve DB query time. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Ran diesel migrations ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
cc4eaed5702dbcaa6c54a32714b52f479dfbe85b
juspay/hyperswitch
juspay__hyperswitch-9761
Bug: [CHORE] add metrics for ignored incoming webhooks In some scenarios, application need to acknowledge webhook requests with 200 even though the resource was not found for avoiding the webhooks to queue in connector systems. For such scenarios, incoming webhook flow can fail and even then the response is 200. A metric needs to be introduced to keep an eye on the volume of such scenarios happening.
diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rs index efb463b3a37..4110f470cee 100644 --- a/crates/router/src/core/metrics.rs +++ b/crates/router/src/core/metrics.rs @@ -48,6 +48,7 @@ counter_metric!( WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT, GLOBAL_METER ); +counter_metric!(WEBHOOK_FLOW_FAILED_BUT_ACKNOWLEDGED, GLOBAL_METER); counter_metric!(ROUTING_CREATE_REQUEST_RECEIVED, GLOBAL_METER); counter_metric!(ROUTING_CREATE_SUCCESS_RESPONSE, GLOBAL_METER); diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index ce183002834..0e8b879f456 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -284,6 +284,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( &connector, connector_name.as_str(), &request_details, + merchant_context.get_merchant_account().get_id(), ); match error_result { Ok((response, webhook_tracker, serialized_request)) => { @@ -373,6 +374,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( &connector, connector_name.as_str(), &final_request_details, + merchant_context.get_merchant_account().get_id(), ); match error_result { Ok((_, webhook_tracker, _)) => webhook_tracker, @@ -559,8 +561,13 @@ async fn process_webhook_business_logic( { Ok(mca) => mca, Err(error) => { - let result = - handle_incoming_webhook_error(error, connector, connector_name, request_details); + let result = handle_incoming_webhook_error( + error, + connector, + connector_name, + request_details, + merchant_context.get_merchant_account().get_id(), + ); match result { Ok((_, webhook_tracker, _)) => return Ok(webhook_tracker), Err(e) => return Err(e), @@ -850,8 +857,13 @@ async fn process_webhook_business_logic( match result_response { Ok(response) => Ok(response), Err(error) => { - let result = - handle_incoming_webhook_error(error, connector, connector_name, request_details); + let result = handle_incoming_webhook_error( + error, + connector, + connector_name, + request_details, + merchant_context.get_merchant_account().get_id(), + ); match result { Ok((_, webhook_tracker, _)) => Ok(webhook_tracker), Err(e) => Err(e), @@ -865,6 +877,7 @@ fn handle_incoming_webhook_error( connector: &ConnectorEnum, connector_name: &str, request_details: &IncomingWebhookRequestDetails<'_>, + merchant_id: &common_utils::id_type::MerchantId, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, @@ -881,6 +894,13 @@ fn handle_incoming_webhook_error( // get the error response from the connector if connector_enum.should_acknowledge_webhook_for_resource_not_found_errors() { + metrics::WEBHOOK_FLOW_FAILED_BUT_ACKNOWLEDGED.add( + 1, + router_env::metric_attributes!( + ("connector", connector_name.to_string()), + ("merchant_id", merchant_id.get_string_repr().to_string()) + ), + ); let response = connector .get_webhook_api_response( request_details,
2025-10-09T08:44:51Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds a metric `WEBHOOK_FLOW_FAILED_BUT_ACKNOWLEDGED` to track incoming webhooks that failed processing but were acknowledged with 200 status to prevent queueing in connector systems. The metric includes the following attributes: - connector - merchant_id ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context In some scenarios, applications need to acknowledge webhook requests with 200 even though the resource was not found, to avoid webhooks queueing in connector systems. This metric provides visibility into the volume of such scenarios, enabling better monitoring and alerting (if needed). ## How did you test it? Cannot be tested. Metrics will be visible on Grafana. Can be queried using: ```promql webhook_flow_failed_but_acknowledged_total{connector="adyen",merchant_id="merchant_123"} ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
35a20f8e4aac0fcfe6c409964391f2222f3c6770
juspay/hyperswitch
juspay__hyperswitch-9747
Bug: [FEATURE] Multisafepay wasm changes ### Feature Description Add the following payment methods in wasm for multisafepay TRUSTLY ALIPAY WE CHAT PAY EPS MBway Sofort ### Possible Implementation [ ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 027c82e3af8..6729c0add3d 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -2860,6 +2860,18 @@ api_secret="Merchant Id" api_key="Enter API Key" [multisafepay.connector_webhook_details] merchant_secret="Source verification key" +[[multisafepay.bank_redirect]] +payment_method_type = "trustly" +[[multisafepay.bank_redirect]] +payment_method_type = "eps" +[[multisafepay.bank_redirect]] +payment_method_type = "sofort" +[[multisafepay.wallet]] +payment_method_type = "ali_pay" +[[multisafepay.wallet]] +payment_method_type = "we_chat_pay" +[[multisafepay.wallet]] +payment_method_type = "mb_way" [[multisafepay.metadata.google_pay]] name="merchant_name" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 93d7d1f26e7..170886bc095 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -2471,7 +2471,18 @@ payment_method_type = "UnionPay" api_key = "Enter API Key" [multisafepay.connector_webhook_details] merchant_secret = "Source verification key" - +[[multisafepay.bank_redirect]] +payment_method_type = "trustly" +[[multisafepay.bank_redirect]] +payment_method_type = "eps" +[[multisafepay.bank_redirect]] +payment_method_type = "sofort" +[[multisafepay.wallet]] +payment_method_type = "ali_pay" +[[multisafepay.wallet]] +payment_method_type = "we_chat_pay" +[[multisafepay.wallet]] +payment_method_type = "mb_way" [nexinets] [[nexinets.credit]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 77ade3ef742..63b5b3f2d8e 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -2906,7 +2906,18 @@ placeholder = "Enter Allowed Auth Methods" required = true type = "MultiSelect" options = ["PAN_ONLY", "CRYPTOGRAM_3DS"] - +[[multisafepay.bank_redirect]] +payment_method_type = "trustly" +[[multisafepay.bank_redirect]] +payment_method_type = "eps" +[[multisafepay.bank_redirect]] +payment_method_type = "sofort" +[[multisafepay.wallet]] +payment_method_type = "ali_pay" +[[multisafepay.wallet]] +payment_method_type = "we_chat_pay" +[[multisafepay.wallet]] +payment_method_type = "mb_way" [nexinets] [[nexinets.credit]]
2025-10-08T10:20:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add the following payment methods in wasm for multisafepay - TRUSTLY - ALIPAY - WE CHAT PAY - EPS - MBway - Sofort Just dashboard changes and no need test cases from BE ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b52aafa8873fc4704bd69014cc457daf32d5523c
juspay/hyperswitch
juspay__hyperswitch-9705
Bug: [FEATURE] Add Client Auth for Subscriptions APIs ### Feature Description Need to implement auth for client side interactions ### Possible Implementation Subscriptions APIs need to support publishible_key + client_secret auth ### 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/subscription.rs b/crates/api_models/src/subscription.rs index 2829d58b883..7c89eec5e52 100644 --- a/crates/api_models/src/subscription.rs +++ b/crates/api_models/src/subscription.rs @@ -74,6 +74,12 @@ pub struct SubscriptionResponse { /// Optional customer ID associated with this subscription. pub customer_id: common_utils::id_type::CustomerId, + + /// Payment details for the invoice. + pub payment: Option<PaymentResponseData>, + + /// Invoice Details for the subscription. + pub invoice: Option<Invoice>, } /// Possible states of a subscription lifecycle. @@ -127,6 +133,8 @@ impl SubscriptionResponse { merchant_id: common_utils::id_type::MerchantId, client_secret: Option<Secret<String>>, customer_id: common_utils::id_type::CustomerId, + payment: Option<PaymentResponseData>, + invoice: Option<Invoice>, ) -> Self { Self { id, @@ -138,6 +146,8 @@ impl SubscriptionResponse { merchant_id, coupon_code: None, customer_id, + payment, + invoice, } } } @@ -181,6 +191,10 @@ impl ClientSecret { pub fn as_str(&self) -> &str { &self.0 } + + pub fn as_string(&self) -> &String { + &self.0 + } } #[derive(serde::Deserialize, serde::Serialize, Debug)] @@ -197,6 +211,7 @@ impl ApiEventMetric for GetPlansResponse {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionPaymentDetails { + pub shipping: Option<Address>, pub payment_method: api_enums::PaymentMethod, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, @@ -278,7 +293,7 @@ pub struct PaymentResponseData { pub error_code: Option<String>, pub error_message: Option<String>, pub payment_method_type: Option<api_enums::PaymentMethodType>, - pub client_secret: Option<String>, + pub client_secret: Option<Secret<String>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -294,7 +309,7 @@ pub struct CreateMitPaymentRequestData { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionRequest { /// Client secret for SDK based interaction. - pub client_secret: Option<String>, + pub client_secret: Option<ClientSecret>, /// Identifier for the associated plan_id. pub plan_id: Option<String>, @@ -305,15 +320,6 @@ pub struct ConfirmSubscriptionRequest { /// Idenctifier for the coupon code for the subscription. pub coupon_code: Option<String>, - /// Identifier for customer. - pub customer_id: common_utils::id_type::CustomerId, - - /// Billing address for the subscription. - pub billing: Option<Address>, - - /// Shipping address for the subscription. - pub shipping: Option<Address>, - /// Payment details for the invoice. pub payment_details: ConfirmSubscriptionPaymentDetails, } @@ -328,11 +334,15 @@ impl ConfirmSubscriptionRequest { } pub fn get_billing_address(&self) -> Result<Address, error_stack::Report<ValidationError>> { - self.billing.clone().ok_or(error_stack::report!( - ValidationError::MissingRequiredField { - field_name: "billing".to_string() - } - )) + self.payment_details + .payment_method_data + .billing + .clone() + .ok_or(error_stack::report!( + ValidationError::MissingRequiredField { + field_name: "billing".to_string() + } + )) } } diff --git a/crates/diesel_models/src/invoice.rs b/crates/diesel_models/src/invoice.rs index 59ef0b272d5..2b93b0b4a62 100644 --- a/crates/diesel_models/src/invoice.rs +++ b/crates/diesel_models/src/invoice.rs @@ -23,6 +23,7 @@ pub struct InvoiceNew { pub metadata: Option<SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, + pub connector_invoice_id: Option<String>, } #[derive( @@ -49,6 +50,7 @@ pub struct Invoice { pub metadata: Option<SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, + pub connector_invoice_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Deserialize)] @@ -56,6 +58,7 @@ pub struct Invoice { pub struct InvoiceUpdate { pub status: Option<String>, pub payment_method_id: Option<String>, + pub connector_invoice_id: Option<String>, pub modified_at: time::PrimitiveDateTime, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, } @@ -75,6 +78,7 @@ impl InvoiceNew { status: InvoiceStatus, provider_name: Connector, metadata: Option<SecretSerdeValue>, + connector_invoice_id: Option<String>, ) -> Self { let id = common_utils::id_type::InvoiceId::generate(); let now = common_utils::date_time::now(); @@ -94,6 +98,7 @@ impl InvoiceNew { metadata, created_at: now, modified_at: now, + connector_invoice_id, } } } @@ -102,11 +107,13 @@ impl InvoiceUpdate { pub fn new( payment_method_id: Option<String>, status: Option<InvoiceStatus>, + connector_invoice_id: Option<String>, payment_intent_id: Option<common_utils::id_type::PaymentId>, ) -> Self { Self { payment_method_id, status: status.map(|status| status.to_string()), + connector_invoice_id, payment_intent_id, modified_at: common_utils::date_time::now(), } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index bd91c7843e9..e3cd4336b4f 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -750,6 +750,8 @@ diesel::table! { metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, + #[max_length = 64] + connector_invoice_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 560d1fc6468..07f9683e83d 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -762,6 +762,8 @@ diesel::table! { metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, + #[max_length = 64] + connector_invoice_id -> Nullable<Varchar>, } } diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 2d3fd649669..5702f9b0a45 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -4,10 +4,7 @@ use api_models::subscription::{ use common_enums::connector_enums; use common_utils::id_type::GenerateId; use error_stack::ResultExt; -use hyperswitch_domain_models::{ - api::ApplicationResponse, merchant_context::MerchantContext, - router_response_types::subscriptions as subscription_response_types, -}; +use hyperswitch_domain_models::{api::ApplicationResponse, merchant_context::MerchantContext}; use super::errors::{self, RouterResponse}; use crate::{ @@ -31,7 +28,7 @@ pub async fn create_subscription( merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, request: subscription_types::CreateSubscriptionRequest, -) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { +) -> RouterResponse<SubscriptionResponse> { let subscription_id = common_utils::id_type::SubscriptionId::generate(); let profile = @@ -68,7 +65,7 @@ pub async fn create_subscription( .create_payment_with_confirm_false(subscription.handler.state, &request) .await .attach_printable("subscriptions: failed to create payment")?; - let invoice_entry = invoice_handler + let invoice = invoice_handler .create_invoice_entry( &state, billing_handler.merchant_connector_id, @@ -78,6 +75,7 @@ pub async fn create_subscription( connector_enums::InvoiceStatus::InvoiceCreated, billing_handler.connector_data.connector_name, None, + None, ) .await .attach_printable("subscriptions: failed to create invoice")?; @@ -91,11 +89,7 @@ pub async fn create_subscription( .await .attach_printable("subscriptions: failed to update subscription")?; - let response = subscription.generate_response( - &invoice_entry, - &payment, - subscription_response_types::SubscriptionStatus::Created, - )?; + let response = subscription.to_subscription_response(Some(payment), Some(&invoice))?; Ok(ApplicationResponse::Json(response)) } @@ -148,14 +142,12 @@ pub async fn get_subscription_plans( .into_iter() .map(subscription_types::SubscriptionPlanPrices::from) .collect::<Vec<_>>(), - }) + }); } - Ok(ApplicationResponse::Json(response)) } /// Creates and confirms a subscription in one operation. -/// This method combines the creation and confirmation flow to reduce API calls pub async fn create_and_confirm_subscription( state: SessionState, merchant_context: MerchantContext, @@ -163,7 +155,6 @@ pub async fn create_and_confirm_subscription( request: subscription_types::CreateAndConfirmSubscriptionRequest, ) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { let subscription_id = common_utils::id_type::SubscriptionId::generate(); - let profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await @@ -240,6 +231,9 @@ pub async fn create_and_confirm_subscription( .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), billing_handler.connector_data.connector_name, None, + invoice_details + .clone() + .map(|invoice| invoice.id.get_string_repr().to_string()), ) .await?; @@ -292,13 +286,23 @@ pub async fn confirm_subscription( SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable("subscriptions: failed to find business profile")?; - let customer = - SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id) - .await - .attach_printable("subscriptions: failed to find customer")?; let handler = SubscriptionHandler::new(&state, &merchant_context); + if let Some(client_secret) = request.client_secret.clone() { + handler + .find_and_validate_subscription(&client_secret.into()) + .await? + }; + let mut subscription_entry = handler.find_subscription(subscription_id).await?; + let customer = SubscriptionHandler::find_customer( + &state, + &merchant_context, + &subscription_entry.subscription.customer_id, + ) + .await + .attach_printable("subscriptions: failed to find customer")?; + let invoice_handler = subscription_entry.get_invoice_handler(profile.clone()); let invoice = invoice_handler .get_latest_invoice(&state) @@ -331,7 +335,7 @@ pub async fn confirm_subscription( .create_customer_on_connector( &state, subscription.customer_id.clone(), - request.billing.clone(), + request.payment_details.payment_method_data.billing.clone(), request .payment_details .payment_method_data @@ -344,7 +348,7 @@ pub async fn confirm_subscription( &state, subscription, request.item_price_id, - request.billing, + request.payment_details.payment_method_data.billing, ) .await?; @@ -359,6 +363,9 @@ pub async fn confirm_subscription( .clone() .and_then(|invoice| invoice.status) .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), + invoice_details + .clone() + .map(|invoice| invoice.id.get_string_repr().to_string()), ) .await?; @@ -418,7 +425,7 @@ pub async fn get_subscription( .await .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?; - Ok(ApplicationResponse::Json( - subscription.to_subscription_response(), - )) + let response = subscription.to_subscription_response(None, None)?; + + Ok(ApplicationResponse::Json(response)) } diff --git a/crates/router/src/core/subscription/invoice_handler.rs b/crates/router/src/core/subscription/invoice_handler.rs index 8cc026fb373..b7d5cb328fd 100644 --- a/crates/router/src/core/subscription/invoice_handler.rs +++ b/crates/router/src/core/subscription/invoice_handler.rs @@ -44,6 +44,7 @@ impl InvoiceHandler { status: connector_enums::InvoiceStatus, provider_name: connector_enums::Connector, metadata: Option<pii::SecretSerdeValue>, + connector_invoice_id: Option<String>, ) -> errors::RouterResult<diesel_models::invoice::Invoice> { let invoice_new = diesel_models::invoice::InvoiceNew::new( self.subscription.id.to_owned(), @@ -58,6 +59,7 @@ impl InvoiceHandler { status, provider_name, metadata, + connector_invoice_id, ); let invoice = state @@ -79,10 +81,12 @@ impl InvoiceHandler { payment_method_id: Option<Secret<String>>, payment_intent_id: Option<common_utils::id_type::PaymentId>, status: connector_enums::InvoiceStatus, + connector_invoice_id: Option<String>, ) -> errors::RouterResult<diesel_models::invoice::Invoice> { let update_invoice = diesel_models::invoice::InvoiceUpdate::new( payment_method_id.as_ref().map(|id| id.peek()).cloned(), Some(status), + connector_invoice_id, payment_intent_id, ); state @@ -189,8 +193,8 @@ impl InvoiceHandler { ) -> errors::RouterResult<subscription_types::PaymentResponseData> { let payment_details = &request.payment_details; let cit_payment_request = subscription_types::ConfirmPaymentsRequestData { - billing: request.billing.clone(), - shipping: request.shipping.clone(), + billing: request.payment_details.payment_method_data.billing.clone(), + shipping: request.payment_details.shipping.clone(), payment_method: payment_details.payment_method, payment_method_type: payment_details.payment_method_type, payment_method_data: payment_details.payment_method_data.clone(), diff --git a/crates/router/src/core/subscription/subscription_handler.rs b/crates/router/src/core/subscription/subscription_handler.rs index b11cf517b03..b608faca5d5 100644 --- a/crates/router/src/core/subscription/subscription_handler.rs +++ b/crates/router/src/core/subscription/subscription_handler.rs @@ -19,7 +19,7 @@ use crate::{ core::{errors::StorageErrorExt, subscription::invoice_handler::InvoiceHandler}, db::CustomResult, routes::SessionState, - types::domain, + types::{domain, transformers::ForeignTryFrom}, }; pub struct SubscriptionHandler<'a> { @@ -227,31 +227,16 @@ impl SubscriptionWithHandler<'_> { price_id: None, coupon: None, billing_processor_subscription_id: self.subscription.connector_subscription_id.clone(), - invoice: Some(subscription_types::Invoice { - id: invoice.id.clone(), - subscription_id: invoice.subscription_id.clone(), - merchant_id: invoice.merchant_id.clone(), - profile_id: invoice.profile_id.clone(), - merchant_connector_id: invoice.merchant_connector_id.clone(), - payment_intent_id: invoice.payment_intent_id.clone(), - payment_method_id: invoice.payment_method_id.clone(), - customer_id: invoice.customer_id.clone(), - amount: invoice.amount, - currency: api_enums::Currency::from_str(invoice.currency.as_str()) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "currency", - }) - .attach_printable(format!( - "unable to parse currency name {currency:?}", - currency = invoice.currency - ))?, - status: invoice.status.clone(), - }), + invoice: Some(subscription_types::Invoice::foreign_try_from(invoice)?), }) } - pub fn to_subscription_response(&self) -> SubscriptionResponse { - SubscriptionResponse::new( + pub fn to_subscription_response( + &self, + payment: Option<subscription_types::PaymentResponseData>, + invoice: Option<&diesel_models::invoice::Invoice>, + ) -> errors::RouterResult<SubscriptionResponse> { + Ok(SubscriptionResponse::new( self.subscription.id.clone(), self.subscription.merchant_reference_id.clone(), SubscriptionStatus::from_str(&self.subscription.status) @@ -261,7 +246,15 @@ impl SubscriptionWithHandler<'_> { self.subscription.merchant_id.to_owned(), self.subscription.client_secret.clone().map(Secret::new), self.subscription.customer_id.clone(), - ) + payment, + invoice + .map( + |invoice| -> errors::RouterResult<subscription_types::Invoice> { + subscription_types::Invoice::foreign_try_from(invoice) + }, + ) + .transpose()?, + )) } pub async fn update_subscription( @@ -369,3 +362,30 @@ impl SubscriptionWithHandler<'_> { } } } + +impl ForeignTryFrom<&diesel_models::invoice::Invoice> for subscription_types::Invoice { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn foreign_try_from(invoice: &diesel_models::invoice::Invoice) -> Result<Self, Self::Error> { + Ok(Self { + id: invoice.id.clone(), + subscription_id: invoice.subscription_id.clone(), + merchant_id: invoice.merchant_id.clone(), + profile_id: invoice.profile_id.clone(), + merchant_connector_id: invoice.merchant_connector_id.clone(), + payment_intent_id: invoice.payment_intent_id.clone(), + payment_method_id: invoice.payment_method_id.clone(), + customer_id: invoice.customer_id.clone(), + amount: invoice.amount, + currency: api_enums::Currency::from_str(invoice.currency.as_str()) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "currency", + }) + .attach_printable(format!( + "unable to parse currency name {currency:?}", + currency = invoice.currency + ))?, + status: invoice.status.clone(), + }) + } +} diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 657655c25bf..ce183002834 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -2645,6 +2645,7 @@ async fn subscription_incoming_webhook_flow( InvoiceStatus::PaymentPending, connector, None, + None, ) .await?; @@ -2664,6 +2665,7 @@ async fn subscription_incoming_webhook_flow( payment_response.payment_method_id.clone(), Some(payment_response.payment_id.clone()), InvoiceStatus::from(payment_response.status), + Some(mit_payment_data.invoice_id.get_string_repr().to_string()), ) .await?; diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs index 46432810450..b1b3397c46c 100644 --- a/crates/router/src/routes/subscription.rs +++ b/crates/router/src/routes/subscription.rs @@ -101,16 +101,25 @@ pub async fn confirm_subscription( ) -> impl Responder { let flow = Flow::ConfirmSubscription; let subscription_id = subscription_id.into_inner(); + let payload = json_payload.into_inner(); let profile_id = match extract_profile_id(&req) { Ok(id) => id, Err(response) => return response, }; + let api_auth = auth::ApiKeyAuth::default(); + + let (auth_type, _) = + match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { + Ok(auth) => auth, + Err(err) => return oss_api::log_and_return_error_response(error_stack::report!(err)), + }; + Box::pin(oss_api::server_wrap( flow, state, &req, - json_payload.into_inner(), + payload, |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), @@ -124,10 +133,7 @@ pub async fn confirm_subscription( ) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth { - is_connected_allowed: false, - is_platform_allowed: false, - }), + &*auth_type, &auth::JWTAuth { permission: Permission::ProfileSubscriptionWrite, }, @@ -146,28 +152,36 @@ pub async fn get_subscription_plans( ) -> impl Responder { let flow = Flow::GetPlansForSubscription; let api_auth = auth::ApiKeyAuth::default(); + let payload = query.into_inner(); let profile_id = match extract_profile_id(&req) { Ok(profile_id) => profile_id, Err(response) => return response, }; - let auth_data = match auth::is_ephemeral_auth(req.headers(), api_auth) { - Ok(auth) => auth, - Err(err) => return crate::services::api::log_and_return_error_response(err), - }; + let (auth_type, _) = + match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { + Ok(auth) => auth, + Err(err) => return oss_api::log_and_return_error_response(error_stack::report!(err)), + }; Box::pin(oss_api::server_wrap( flow, state, &req, - query.into_inner(), + payload, |state, auth: auth::AuthenticationData, query, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); subscription::get_subscription_plans(state, merchant_context, profile_id.clone(), query) }, - &*auth_data, + auth::auth_type( + &*auth_type, + &auth::JWTAuth { + permission: Permission::ProfileSubscriptionRead, + }, + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await @@ -186,6 +200,7 @@ pub async fn get_subscription( Ok(id) => id, Err(response) => return response, }; + Box::pin(oss_api::server_wrap( flow, state, @@ -244,10 +259,16 @@ pub async fn create_and_confirm_subscription( payload.clone(), ) }, - &auth::HeaderAuth(auth::ApiKeyAuth { - is_connected_allowed: false, - is_platform_allowed: false, - }), + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + &auth::JWTAuth { + permission: Permission::ProfileSubscriptionWrite, + }, + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 13d224a1cd7..4bbb1813833 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -4326,6 +4326,20 @@ impl ClientSecretFetch for api_models::payment_methods::PaymentMethodUpdate { } } +#[cfg(feature = "v1")] +impl ClientSecretFetch for api_models::subscription::ConfirmSubscriptionRequest { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref().map(|s| s.as_string()) + } +} + +#[cfg(feature = "v1")] +impl ClientSecretFetch for api_models::subscription::GetPlansQuery { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref().map(|s| s.as_string()) + } +} + #[cfg(feature = "v1")] impl ClientSecretFetch for api_models::authentication::AuthenticationEligibilityRequest { fn get_client_secret(&self) -> Option<&String> { diff --git a/crates/router/src/workflows/invoice_sync.rs b/crates/router/src/workflows/invoice_sync.rs index c6daab02116..ec71af2b708 100644 --- a/crates/router/src/workflows/invoice_sync.rs +++ b/crates/router/src/workflows/invoice_sync.rs @@ -204,6 +204,7 @@ impl<'a> InvoiceSyncHandler<'a> { None, None, common_enums::connector_enums::InvoiceStatus::from(invoice_sync_status), + Some(connector_invoice_id), ) .await .attach_printable("Failed to update invoice in DB")?; diff --git a/migrations/2025-10-07-130304_add_connector_invoice_id/down.sql b/migrations/2025-10-07-130304_add_connector_invoice_id/down.sql new file mode 100644 index 00000000000..85f8bcf59e5 --- /dev/null +++ b/migrations/2025-10-07-130304_add_connector_invoice_id/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE invoice DROP COLUMN IF EXISTS connector_invoice_id; +DROP INDEX IF EXISTS invoice_subscription_id_connector_invoice_id_index; \ No newline at end of file diff --git a/migrations/2025-10-07-130304_add_connector_invoice_id/up.sql b/migrations/2025-10-07-130304_add_connector_invoice_id/up.sql new file mode 100644 index 00000000000..d17ca57da77 --- /dev/null +++ b/migrations/2025-10-07-130304_add_connector_invoice_id/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE invoice ADD COLUMN IF NOT EXISTS connector_invoice_id VARCHAR(64); +CREATE INDEX invoice_subscription_id_connector_invoice_id_index ON invoice (subscription_id, connector_invoice_id); \ No newline at end of file
2025-10-07T12:46:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces several enhancements and refactors to the subscription API, focusing on improving authentication, response structure, and data handling. The main changes include adding payment and invoice details to subscription responses, updating authentication logic to support client secrets in queries, and refactoring handler methods for better error handling and extensibility. **Subscription Response Improvements** * Added `payment` and `invoice` fields to the `SubscriptionResponse` struct to provide more detailed information about payments and invoices associated with a subscription. * Updated the `PaymentResponseData` struct to use a `Secret<String>` for the `client_secret` field, improving security and consistency. **Authentication and Query Handling** * Introduced a new `GetSubscriptionQuery` struct to allow passing a client secret when fetching subscription details, and implemented `ClientSecretFetch` for relevant subscription request/query types. [[1]](diffhunk://#diff-3d85d9e288cc67856867986ee406a3102ce1d0cf9fe5c8f9efed3a578608f817R206-R215) [[2]](diffhunk://#diff-c66a703d6e518900240c7296a4d6f9c55c9787ea8f490a419dd0395dc0b36d70R4329-R4349) * Refactored authentication logic in subscription route handlers (`get_subscription`, `get_subscription_plans`, and `confirm_subscription`) to extract and validate client secrets from query payloads, improving security and flexibility. [[1]](diffhunk://#diff-d737ada25c830476b3867c693bd362d4b1142773f1b0d971556518b5c04691a3R104-R122) [[2]](diffhunk://#diff-d737ada25c830476b3867c693bd362d4b1142773f1b0d971556518b5c04691a3R149-R172) [[3]](diffhunk://#diff-d737ada25c830476b3867c693bd362d4b1142773f1b0d971556518b5c04691a3R184-R199) [[4]](diffhunk://#diff-d737ada25c830476b3867c693bd362d4b1142773f1b0d971556518b5c04691a3L205-R216) **Handler and Response Refactoring** * Refactored the `to_subscription_response` method in `SubscriptionWithHandler` to accept optional payment and invoice parameters, and handle invoice conversion with error reporting for invalid currency values. [[1]](diffhunk://#diff-1d71cc03e82ba9b3c7478b6304bd763431e20cc723881a1623ab3127301b8976L253-R258) [[2]](diffhunk://#diff-1d71cc03e82ba9b3c7478b6304bd763431e20cc723881a1623ab3127301b8976R268-R295) * Updated core subscription logic to use the new response structure and refactored method signatures for consistency, including changes to how responses are generated and returned. [[1]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL34-R31) [[2]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL71-R68) [[3]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL94-R91) [[4]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL420-R412) These changes collectively improve the robustness and extensibility of the subscription API, making it easier to integrate payment and invoice details while strengthening authentication mechanisms. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Subscription create ``` curl --location 'http://localhost:8080/subscriptions/create' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_CohRshEanxkKSMHgyu6a' \ --header 'api-key: dev_tV0O30052zhBCqdrhGMfQxMN0DerXwnMkNHX6ndCbs0BovewetTaXznBQOCLGAi2' \ --data '{ "customer_id": "cus_d64F9yomaDMqbTDlxw3g", "amount": 14100, "currency": "USD", "payment_details": { "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com" } }' ``` Response - ``` {"id":"sub_8zxmAZAfS0eTL8zRJRk7","merchant_reference_id":null,"status":"created","plan_id":null,"profile_id":"pro_CohRshEanxkKSMHgyu6a","client_secret":"sub_8zxmAZAfS0eTL8zRJRk7_secret_IGg9yCNzrzoziV3odFLt","merchant_id":"merchant_1759849271","coupon_code":null,"customer_id":"cus_d64F9yomaDMqbTDlxw3g","payment":{"payment_id":"pay_pPn6Tz2m3WrOIzANMF2g","status":"requires_payment_method","amount":14100,"currency":"USD","connector":null,"payment_method_id":null,"payment_experience":null,"error_code":null,"error_message":null,"payment_method_type":null,"client_secret":"pay_pPn6Tz2m3WrOIzANMF2g_secret_Wxi6r52cBxz0ujhcWpAh"},"invoice":{"id":"invoice_nEqu7GMVqNMRzBorC9BS","subscription_id":"sub_8zxmAZAfS0eTL8zRJRk7","merchant_id":"merchant_1759849271","profile_id":"pro_CohRshEanxkKSMHgyu6a","merchant_connector_id":"mca_S0OzkqOOhMZs2jJQPSZo","payment_intent_id":"pay_pPn6Tz2m3WrOIzANMF2g","payment_method_id":null,"customer_id":"cus_d64F9yomaDMqbTDlxw3g","amount":14100,"currency":"USD","status":"invoice_created"}} ``` 2. Get plans ``` curl --location 'http://localhost:8080/subscriptions/plans?limit=2&offset=0&client_secret=sub_8zxmAZAfS0eTL8zRJRk7_secret_IGg9yCNzrzoziV3odFLt' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_febeb0fab3be43c79024efaf99764d63' \ --header 'X-Profile-Id: pro_CohRshEanxkKSMHgyu6a' ``` Response - ``` [{"plan_id":"cbdemo_enterprise-suite","name":"Enterprise Suite","description":"High-end customer support suite with enterprise-grade solutions.","price_id":[{"price_id":"cbdemo_enterprise-suite-monthly","plan_id":"cbdemo_enterprise-suite","amount":14100,"currency":"INR","interval":"Month","interval_count":1,"trial_period":null,"trial_period_unit":null},{"price_id":"cbdemo_enterprise-suite-annual","plan_id":"cbdemo_enterprise-suite","amount":169000,"currency":"INR","interval":"Year","interval_count":1,"trial_period":null,"trial_period_unit":null}]},{"plan_id":"cbdemo_business-suite","name":"Business Suite","description":"Advanced customer support plan with premium features.","price_id":[{"price_id":"cbdemo_business-suite-monthly","plan_id":"cbdemo_business-suite","amount":9600,"currency":"INR","interval":"Month","interval_count":1,"trial_period":null,"trial_period_unit":null},{"price_id":"cbdemo_business-suite-annual","plan_id":"cbdemo_business-suite","amount":115000,"currency":"INR","interval":"Year","interval_count":1,"trial_period":null,"trial_period_unit":null}]}] ``` 3. Confirm subscription - ``` curl --location 'http://localhost:8080/subscriptions/sub_8zxmAZAfS0eTL8zRJRk7/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_CohRshEanxkKSMHgyu6a' \ --header 'api-key: pk_dev_febeb0fab3be43c79024efaf99764d63' \ --data '{ "item_price_id": "cbdemo_enterprise-suite-monthly", "description": "Hello this is description", "client_secret": "sub_8zxmAZAfS0eTL8zRJRk7_secret_IGg9yCNzrzoziV3odFLt", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "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" } } } }' ``` Response - ``` {"id":"sub_8zxmAZAfS0eTL8zRJRk7","merchant_reference_id":null,"status":"active","plan_id":null,"price_id":null,"coupon":null,"profile_id":"pro_CohRshEanxkKSMHgyu6a","payment":{"payment_id":"pay_pPn6Tz2m3WrOIzANMF2g","status":"succeeded","amount":14100,"currency":"USD","connector":"stripe","payment_method_id":"pm_ZAtcND5u4SoRq6DnTQET","payment_experience":null,"error_code":null,"error_message":null,"payment_method_type":"credit","client_secret":"pay_pPn6Tz2m3WrOIzANMF2g_secret_Wxi6r52cBxz0ujhcWpAh"},"customer_id":"cus_d64F9yomaDMqbTDlxw3g","invoice":{"id":"invoice_nEqu7GMVqNMRzBorC9BS","subscription_id":"sub_8zxmAZAfS0eTL8zRJRk7","merchant_id":"merchant_1759849271","profile_id":"pro_CohRshEanxkKSMHgyu6a","merchant_connector_id":"mca_S0OzkqOOhMZs2jJQPSZo","payment_intent_id":"pay_pPn6Tz2m3WrOIzANMF2g","payment_method_id":"pm_ZAtcND5u4SoRq6DnTQET","customer_id":"cus_d64F9yomaDMqbTDlxw3g","amount":14100,"currency":"USD","status":"payment_pending"},"billing_processor_subscription_id":"sub_8zxmAZAfS0eTL8zRJRk7"} ``` invoice - <img width="942" height="409" alt="image" src="https://github.com/user-attachments/assets/c674745e-428d-4a69-9c74-4732e160fb31" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f2c2bd64393f24aaac9081622fde52752ae35593
juspay/hyperswitch
juspay__hyperswitch-9711
Bug: [FEATURE] loonio webhooks ### Feature Description Implement webhook support for loonio ### Possible Implementation Implement Webhook - Payment ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/hyperswitch_connectors/src/connectors/loonio.rs b/crates/hyperswitch_connectors/src/connectors/loonio.rs index 96ee717b862..1de6f4236d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/loonio.rs +++ b/crates/hyperswitch_connectors/src/connectors/loonio.rs @@ -2,12 +2,13 @@ pub mod transformers; use common_enums::enums; use common_utils::{ + crypto::Encryptable, errors::CustomResult, - ext_traits::BytesExt, + ext_traits::{ByteSliceExt, BytesExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, @@ -42,7 +43,7 @@ use hyperswitch_interfaces::{ webhooks, }; use lazy_static::lazy_static; -use masking::{ExposeInterface, Mask}; +use masking::{ExposeInterface, Mask, Secret}; use transformers as loonio; use crate::{constants::headers, types::ResponseRouterData, utils}; @@ -334,9 +335,9 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Loo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: loonio::LoonioTransactionSyncResponse = res + let response: loonio::LoonioPaymentResponseData = res .response - .parse_struct("loonio LoonioTransactionSyncResponse") + .parse_struct("loonio LoonioPaymentResponseData") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -588,25 +589,56 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Loonio { #[async_trait::async_trait] impl webhooks::IncomingWebhook for Loonio { - fn get_webhook_object_reference_id( + async fn verify_webhook_source( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, + _merchant_id: &common_utils::id_type::MerchantId, + _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: Encryptable<Secret<serde_json::Value>>, + _connector_name: &str, + ) -> CustomResult<bool, errors::ConnectorError> { + Ok(false) + } + + fn get_webhook_object_reference_id( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let webhook_body: loonio::LoonioWebhookBody = request + .body + .parse_struct("LoonioWebhookBody") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + webhook_body.api_transaction_id, + ), + )) } fn get_webhook_event_type( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let webhook_body: loonio::LoonioWebhookBody = request + .body + .parse_struct("LoonioWebhookBody") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok((&webhook_body.event_code).into()) } fn get_webhook_resource_object( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let webhook_body: loonio::LoonioWebhookBody = request + .body + .parse_struct("LoonioWebhookBody") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + let resource = loonio::LoonioPaymentResponseData::Webhook(webhook_body); + + Ok(Box::new(resource)) } } @@ -614,8 +646,8 @@ lazy_static! { static ref LOONIO_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; - let mut gigadat_supported_payment_methods = SupportedPaymentMethods::new(); - gigadat_supported_payment_methods.add( + let mut loonio_supported_payment_methods = SupportedPaymentMethods::new(); + loonio_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Interac, PaymentMethodDetails { @@ -626,7 +658,7 @@ lazy_static! { }, ); - gigadat_supported_payment_methods + loonio_supported_payment_methods }; static ref LOONIO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Loonio", @@ -634,7 +666,9 @@ lazy_static! { connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; - static ref LOONIO_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); + static ref LOONIO_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![ + enums::EventClass::Payments, + ]; } impl ConnectorSpecifications for Loonio { diff --git a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs index 7efc1a895dc..f1c594145b6 100644 --- a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; +use api_models::webhooks; use common_enums::{enums, Currency}; use common_utils::{id_type, pii::Email, request::Method, types::FloatMajorUnit}; use hyperswitch_domain_models::{ @@ -18,7 +19,6 @@ use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self, PaymentsAuthorizeRequestData, RouterData as _}, }; - pub struct LoonioRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, @@ -62,6 +62,8 @@ pub struct LoonioPaymentRequest { pub payment_method_type: InteracPaymentMethodType, #[serde(skip_serializing_if = "Option::is_none")] pub redirect_url: Option<LoonioRedirectUrl>, + #[serde(skip_serializing_if = "Option::is_none")] + pub webhook_url: Option<String>, } #[derive(Debug, Serialize)] @@ -102,7 +104,6 @@ impl TryFrom<&LoonioRouterData<&PaymentsAuthorizeRouterData>> for LoonioPaymentR success_url: item.router_data.request.get_router_return_url()?, failed_url: item.router_data.request.get_router_return_url()?, }; - Ok(Self { currency_code: item.router_data.request.currency, customer_profile, @@ -111,6 +112,7 @@ impl TryFrom<&LoonioRouterData<&PaymentsAuthorizeRouterData>> for LoonioPaymentR transaction_id, payment_method_type: InteracPaymentMethodType::InteracEtransfer, redirect_url: Some(redirect_url), + webhook_url: Some(item.router_data.request.get_webhook_url()?), }) } PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented( @@ -140,7 +142,9 @@ impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResp Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.payment_form.clone()), + resource_id: ResponseId::ConnectorTransactionId( + item.data.connector_request_reference_id.clone(), + ), redirection_data: Box::new(Some(RedirectForm::Form { endpoint: item.response.payment_form, method: Method::Get, @@ -211,29 +215,48 @@ impl<F> TryFrom<&LoonioRouterData<&RefundsRouterData<F>>> for LoonioRefundReques } } -impl<F, T> TryFrom<ResponseRouterData<F, LoonioTransactionSyncResponse, T, PaymentsResponseData>> +impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentResponseData, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, LoonioTransactionSyncResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, LoonioPaymentResponseData, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - Ok(Self { - status: enums::AttemptStatus::from(item.response.state), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - item.response.transaction_id.clone(), - ), - 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, + match item.response { + LoonioPaymentResponseData::Sync(sync_response) => Ok(Self { + status: enums::AttemptStatus::from(sync_response.state), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(sync_response.transaction_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 }), - ..item.data - }) + LoonioPaymentResponseData::Webhook(webhook_body) => { + let payment_status = enums::AttemptStatus::from(&webhook_body.event_code); + Ok(Self { + status: payment_status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + webhook_body.api_transaction_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 + }) + } + } } } @@ -303,3 +326,94 @@ pub struct LoonioErrorResponse { pub error_code: Option<String>, pub message: String, } + +// Webhook related structs + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum LoonioWebhookEventCode { + TransactionPrepared, + TransactionPending, + TransactionAvailable, + TransactionSettled, + TransactionFailed, + TransactionRejected, + #[serde(rename = "TRANSACTION_WAITING_STATUS_FILE")] + TransactionWaitingStatusFile, + #[serde(rename = "TRANSACTION_STATUS_FILE_RECEIVED")] + TransactionStatusFileReceived, + #[serde(rename = "TRANSACTION_STATUS_FILE_FAILED")] + TransactionStatusFileFailed, + #[serde(rename = "TRANSACTION_RETURNED")] + TransactionReturned, + #[serde(rename = "TRANSACTION_WRONG_DESTINATION")] + TransactionWrongDestination, + #[serde(rename = "TRANSACTION_NSF")] + TransactionNsf, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum LoonioWebhookTransactionType { + Incoming, + OutgoingVerified, + OutgoingNotVerified, + OutgoingCustomerDefined, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct LoonioWebhookBody { + pub amount: FloatMajorUnit, + pub api_transaction_id: String, + pub signature: Option<String>, + pub event_code: LoonioWebhookEventCode, + pub id: i32, + #[serde(rename = "type")] + pub transaction_type: LoonioWebhookTransactionType, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum LoonioPaymentResponseData { + Sync(LoonioTransactionSyncResponse), + Webhook(LoonioWebhookBody), +} +impl From<&LoonioWebhookEventCode> for webhooks::IncomingWebhookEvent { + fn from(event_code: &LoonioWebhookEventCode) -> Self { + match event_code { + LoonioWebhookEventCode::TransactionSettled + | LoonioWebhookEventCode::TransactionAvailable => Self::PaymentIntentSuccess, + LoonioWebhookEventCode::TransactionPending + | LoonioWebhookEventCode::TransactionPrepared => Self::PaymentIntentProcessing, + LoonioWebhookEventCode::TransactionFailed + // deprecated + | LoonioWebhookEventCode::TransactionRejected + | LoonioWebhookEventCode::TransactionStatusFileFailed + | LoonioWebhookEventCode::TransactionReturned + | LoonioWebhookEventCode::TransactionWrongDestination + | LoonioWebhookEventCode::TransactionNsf => Self::PaymentIntentFailure, + _ => Self::EventNotSupported, + } + } +} + +impl From<&LoonioWebhookEventCode> for enums::AttemptStatus { + fn from(event_code: &LoonioWebhookEventCode) -> Self { + match event_code { + LoonioWebhookEventCode::TransactionSettled + | LoonioWebhookEventCode::TransactionAvailable => Self::Charged, + + LoonioWebhookEventCode::TransactionPending + | LoonioWebhookEventCode::TransactionPrepared => Self::Pending, + + LoonioWebhookEventCode::TransactionFailed + | LoonioWebhookEventCode::TransactionRejected + | LoonioWebhookEventCode::TransactionStatusFileFailed + | LoonioWebhookEventCode::TransactionReturned + | LoonioWebhookEventCode::TransactionWrongDestination + | LoonioWebhookEventCode::TransactionNsf => Self::Failure, + + _ => Self::Pending, + } + } +}
2025-10-07T09:18:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Loomio webhooks for payments ## payment request ```json { "amount": 1500, "currency": "CAD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "authentication_type": "three_ds", "payment_method": "bank_redirect", "payment_method_type": "interac", "payment_method_data": { "bank_redirect": { "interac": {} } }, "billing": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "SG", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` ## response ```json { "payment_id": "pay_J3xaVGqCX1QbnGKyQoCQ", "merchant_id": "merchant_1759821555", "status": "requires_customer_action", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 1500, "amount_received": null, "connector": "loonio", "client_secret": "pay_J3xaVGqCX1QbnGKyQoCQ_secret_IfvZo54PdakCzmi10muX", "created": "2025-10-07T09:15:47.349Z", "currency": "CAD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_J3xaVGqCX1QbnGKyQoCQ/merchant_1759821555/pay_J3xaVGqCX1QbnGKyQoCQ_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "interac", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "aaaa", "created_at": 1759828547, "expires": 1759832147, "secret": "epk_dfb1c2f173f34c4da48ee0a98d48051f" }, "manual_retry_allowed": null, "connector_transaction_id": "pay_J3xaVGqCX1QbnGKyQoCQ_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_MLEtbytGk3haqiqlaheV", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_UKE4wkdWmZVIs8oRKgbo", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-07T09:30:47.349Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-07T09:15:48.782Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` ## make redirect <img width="1708" height="1115" alt="Screenshot 2025-10-07 at 2 47 11 PM" src="https://github.com/user-attachments/assets/35ea68fa-8b86-48ef-9600-64916ebdaf2b" /> ## the status will change when webhook reaches without force psync <img width="1178" height="678" alt="Screenshot 2025-10-07 at 2 47 43 PM" src="https://github.com/user-attachments/assets/254d2a5f-eab1-4b15-988a-a353338d1536" /> ## webhook source verificaiton = false <img width="1085" height="311" alt="Screenshot 2025-10-07 at 6 15 09 PM" src="https://github.com/user-attachments/assets/0f21632f-0927-47ac-95b4-4593dcbb1633" /> <img width="648" height="246" alt="Screenshot 2025-10-07 at 6 15 21 PM" src="https://github.com/user-attachments/assets/1871af58-ce58-4c78-97d3-7c1502ab77ba" /> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b3beda7d7172396452e34858cb6bd701962f75ab
juspay/hyperswitch
juspay__hyperswitch-9782
Bug: [BUG] Rebilling should be "1" for ntid flow for nuvei ### Bug Description : Make rebilling as "1" in connector request 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? None
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 11cd0026ea0..522535e3696 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -563,7 +563,7 @@ ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [payout_method_filters.nuvei] diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 4c402c8c73f..44c41ac8860 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -543,7 +543,7 @@ ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [payout_method_filters.nuvei] diff --git a/config/development.toml b/config/development.toml index 7bc13f554b8..5eb55d390f3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -660,7 +660,7 @@ ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [payout_method_filters.nuvei] diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 8fe123f5e37..3f261ea461b 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -97,7 +97,7 @@ trait NuveiAuthorizePreprocessingCommon { fn get_minor_amount_required( &self, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>>; - fn get_customer_id_required(&self) -> Option<CustomerId>; + fn get_customer_id_optional(&self) -> Option<CustomerId>; fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>>; fn get_currency_required( &self, @@ -130,7 +130,7 @@ impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData { } } - fn get_customer_id_required(&self) -> Option<CustomerId> { + fn get_customer_id_optional(&self) -> Option<CustomerId> { self.customer_id.clone() } @@ -221,7 +221,7 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { ) -> Result<Option<AuthenticationData>, error_stack::Report<errors::ConnectorError>> { Ok(self.authentication_data.clone()) } - fn get_customer_id_required(&self) -> Option<CustomerId> { + fn get_customer_id_optional(&self) -> Option<CustomerId> { self.customer_id.clone() } @@ -290,7 +290,7 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { None } - fn get_customer_id_required(&self) -> Option<CustomerId> { + fn get_customer_id_optional(&self) -> Option<CustomerId> { None } fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { @@ -447,6 +447,14 @@ pub struct NuveiItem { pub image_url: Option<String>, pub product_url: Option<String>, } +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] +pub enum IsRebilling { + #[serde(rename = "1")] + True, + #[serde(rename = "0")] + False, +} + #[serde_with::skip_serializing_none] #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] @@ -463,7 +471,7 @@ pub struct NuveiPaymentsRequest { //unique transaction id pub client_unique_id: String, pub transaction_type: TransactionType, - pub is_rebilling: Option<String>, + pub is_rebilling: Option<IsRebilling>, pub payment_option: PaymentOption, pub is_moto: Option<bool>, pub device_details: DeviceDetails, @@ -1124,7 +1132,7 @@ struct ApplePayPaymentMethodCamelCase { fn get_google_pay_decrypt_data( predecrypt_data: &GPayPredecryptData, - is_rebilling: Option<String>, + is_rebilling: Option<IsRebilling>, brand: Option<String>, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { Ok(NuveiPaymentsRequest { @@ -1163,7 +1171,7 @@ where Req: NuveiAuthorizePreprocessingCommon, { let is_rebilling = if item.request.is_customer_initiated_mandate_payment() { - Some("0".to_string()) + Some(IsRebilling::False) } else { None }; @@ -1237,7 +1245,7 @@ where fn get_apple_pay_decrypt_data( apple_pay_predecrypt_data: &ApplePayPredecryptData, - is_rebilling: Option<String>, + is_rebilling: Option<IsRebilling>, network: String, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { Ok(NuveiPaymentsRequest { @@ -1291,7 +1299,7 @@ where Req: NuveiAuthorizePreprocessingCommon, { let is_rebilling = if item.request.is_customer_initiated_mandate_payment() { - Some("0".to_string()) + Some(IsRebilling::False) } else { None }; @@ -1633,14 +1641,17 @@ where billing_address: None, shipping_address: None, }; - let is_rebilling = if router_data.request.is_customer_initiated_mandate_payment() { - Some("0".to_string()) - } else { - None - }; + let is_rebilling = Some(IsRebilling::True); + Ok(NuveiPaymentsRequest { external_scheme_details, payment_option, + user_token_id: Some( + router_data + .request + .get_customer_id_optional() + .ok_or_else(missing_field_err("customer_id"))?, + ), is_rebilling, ..Default::default() }) @@ -1736,7 +1747,8 @@ fn get_amount_details( impl<F, Req> TryFrom<(&RouterData<F, Req, PaymentsResponseData>, String)> for NuveiPaymentsRequest where - Req: NuveiAuthorizePreprocessingCommon, + Req: NuveiAuthorizePreprocessingCommon + std::fmt::Debug, + F: std::fmt::Debug, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( @@ -1917,10 +1929,9 @@ where } else { request_data.device_details.clone() }; - Ok(Self { is_rebilling: request_data.is_rebilling, - user_token_id: item.customer_id.clone(), + user_token_id: request_data.user_token_id, related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, billing_address, @@ -1934,7 +1945,7 @@ where amount_details, items: l2_l3_items, is_partial_approval: item.request.get_is_partial_approval(), - + external_scheme_details: request_data.external_scheme_details, ..request }) } @@ -1969,7 +1980,7 @@ where match item.request.is_customer_initiated_mandate_payment() { true => { ( - Some("0".to_string()), // In case of first installment, rebilling should be 0 + Some(IsRebilling::False), // In case of first installment, rebilling should be 0 Some(V2AdditionalParams { rebill_expiry: Some( time::OffsetDateTime::now_utc() @@ -1983,7 +1994,7 @@ where challenge_window_size: Some(CHALLENGE_WINDOW_SIZE.to_string()), challenge_preference: Some(CHALLENGE_PREFERENCE.to_string()), }), - item.request.get_customer_id_required(), + item.request.get_customer_id_optional(), ) } // non mandate transactions @@ -3513,7 +3524,7 @@ where let connector_mandate_id = &item.request.get_connector_mandate_id(); let customer_id = item .request - .get_customer_id_required() + .get_customer_id_optional() .ok_or(missing_field_err("customer_id")())?; let related_transaction_id = item.request.get_related_transaction_id().clone(); @@ -3537,7 +3548,7 @@ where device_details: DeviceDetails { ip_address: Secret::new(ip_address), }, - is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1 + is_rebilling: Some(IsRebilling::True), // In case of second installment, rebilling should be 1 user_token_id: Some(customer_id), payment_option: PaymentOption { user_payment_option_id: connector_mandate_id.clone(), diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0b9f7de40d4..e9ec258aaf8 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1266,7 +1266,7 @@ where let operations::GetTrackerResponse { operation, - customer_details: _, + customer_details, mut payment_data, business_profile, mandate_type: _, @@ -1330,6 +1330,18 @@ where None }; + let (operation, customer) = operation + .to_domain()? + .get_or_create_customer_details( + state, + &mut payment_data, + customer_details, + merchant_context.get_merchant_key_store(), + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) + .attach_printable("Failed while fetching/creating customer")?; let (router_data, mca) = proxy_for_call_connector_service( state, req_state.clone(), @@ -1337,7 +1349,7 @@ where connector.clone(), &operation, &mut payment_data, - &None, + &customer, call_connector_action.clone(), &validate_result, schedule_time,
2025-10-08T06:21:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> `is_rebilling` should be sent as `1` always for `NTID` flow in Nuvei. - Core change: For proxy/ntid flow customer details were not being passed. - Add US as supported countries for GOOGLEPAY, Even though it doesn't list US in supported countries in [DOC](https://docs.nuvei.com/documentation/global-guides/google-pay/) ## REQUEST ```json { "amount": 10023, "currency": "EUR", "confirm": true, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "setup_future_usage": "off_session", "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "[email protected]", "payment_method": "card", "payment_method_type": "credit", "off_session": true, "recurring_details": { "type": "network_transaction_id_and_card_details", "data": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_network":"VISA", "network_transaction_id": "01615070********" } } } ``` RESPONSE : ```json { "payment_id": "pay_LkaUU5hsgNIRtS3dNJ7Y", "merchant_id": "merchant_1760007762", "status": "succeeded", "amount": 10023, "net_amount": 10023, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10023, "connector": "nuvei", "client_secret": "pay_LkaUU5hsgNIRtS3dNJ7Y_secret_SnY5seciR0qmDoTyLD3Z", "created": "2025-10-10T07:39:13.663Z", "currency": "EUR", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1760081953, "expires": 1760085553, "secret": "epk_84b79b41787640c780ec0ffbc06d61e2" }, "manual_retry_allowed": null, "connector_transaction_id": "7110000000018185783", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "9599777111", "payment_link": null, "profile_id": "pro_D59PF6bunaFycoeexf3v", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_dBUZgHuGCA5UOuipcycK", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-10T07:54:13.663Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": "", "payment_method_status": null, "updated": "2025-10-10T07:39:16.176Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": true, "mit_category": null } ``` ## Connector request ```js Object { timeStamp: String("20251010052957"), sessionToken: String("*** alloc::string::String ***"), merchantId: String("*** alloc::string::String ***"), merchantSiteId: String("*** alloc::string::String ***"), clientRequestId: String("*** alloc::string::String ***"), amount: String("100.23"), currency: String("EUR"), userTokenId: String("nithxxinn"), // required when rebilling is "1" clientUniqueId: String(""), transactionType: String("Sale"), isRebilling: String("1"), // rebilling 1 for ntid paymentOption: Object { card: Object { cardNumber: String("424242**********"), expirationMonth: String("*** alloc::string::String ***"), expirationYear: String("*** alloc::string::String ***"), }, }, deviceDetails: Object { ipAddress: String("192.**.**.**"), }, checksum: String("*** alloc::string::String ***"), billingAddress: Object { email: String("*****@gmail.com"), firstName: String("*** alloc::string::String ***"), lastName: String("*** alloc::string::String ***"), country: String("US"), city: String("*** alloc::string::String ***"), address: String("*** alloc::string::String ***"), zip: String("*** alloc::string::String ***"), addressLine2: String("*** alloc::string::String ***"), }, urlDetails: Object { successUrl: String("https://google.com"), failureUrl: String("https://google.com"), pendingUrl: String("https://google.com"), }, amountDetails: Object { totalTax: Null, totalShipping: Null, totalHandling: Null, totalDiscount: Null, }, externalSchemeDetails: Object { transactionId: String("*** alloc::string::String ***"), // NITD brand: String("VISA"), }, } ``` ## Non Mandate request ```json { "amount": 30000, "capture_method": "automatic", "currency": "AED", "confirm": true, "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" } }, "connector": [ "nuvei" ], "customer_id": "nidthxxinn", "return_url": "https://www.google.com", "payment_method": "card", "payment_method_type": "credit", "billing": { "address": { "zip": "560095", "country": "AT", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "[email protected]", "payment_method_data": { "card": { "card_number": "4531739335817394", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } } } ``` RESPONSE ```js { "timeStamp": "20251010163310", "sessionToken": "*** alloc::string::String ***", "merchantId": "*** alloc::string::String ***", "merchantSiteId": "*** alloc::string::String ***", "clientRequestId": "*** alloc::string::String ***", "amount": "300.00", "currency": "AED", "clientUniqueId": "", "transactionType": "Sale", "paymentOption": { "card": { "cardNumber": "453173**********", "cardHolderName": "*** alloc::string::String ***", "expirationMonth": "*** alloc::string::String ***", "expirationYear": "*** alloc::string::String ***", "CVV": "*** alloc::string::String ***" } }, "deviceDetails": { "ipAddress": "192.**.**.**" }, "checksum": "*** alloc::string::String ***", "billingAddress": { "email": "*****@gmail.com", "firstName": "*** alloc::string::String ***", "lastName": "*** alloc::string::String ***", "country": "AT", "city": "*** alloc::string::String ***", "address": "*** alloc::string::String ***", "zip": "*** alloc::string::String ***", "addressLine2": "*** alloc::string::String ***" }, "urlDetails": { "successUrl": "https://google.com", "failureUrl": "https://google.com", "pendingUrl": "https://google.com" }, "amountDetails": { "totalTax": null, "totalShipping": null, "totalHandling": null, "totalDiscount": null } } ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
47f7e258bcddad62ef89bb896ae4117b5ac32038
juspay/hyperswitch
juspay__hyperswitch-9733
Bug: [FEATURE] Finix: Add Google Pay Connector Tokenization Flow ### Feature Description Finix: Add Google Pay Connector Tokenization Flow ### Possible Implementation Finix: Add Google Pay Connector Tokenization Flow ### 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 c4eabbb369f..cfaefc600f9 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -962,6 +962,9 @@ apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } [pm_filters.paysafe] apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } +[pm_filters.finix] +google_pay = { country = "AD, AE, AG, AI, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BZ, CA, CC, CG, CH, CI, CK, CL, CM, CN, CO, CR, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KR, KW, KY, KZ, LA, LC, LI, LK, LR, LS, LT, LU, LV, MA, MC, MD, ME, MF, MG, MH, MK, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RE, RO, RS, RW, SA, SB, SC, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SR, ST, SV, SX, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TT, TV, TZ, UG, UM, UY, UZ, VA, VC, VG, VI, VN, VU, WF, WS, YT, ZA, ZM, US", currency = "USD, CAD" } + [connector_customer] payout_connector_list = "nomupay,stripe,wise" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index b5980eedcff..9d5a912082c 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -447,6 +447,7 @@ pix = { country = "BR", currency = "BRL" } [pm_filters.finix] 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} +google_pay = { country = "AD, AE, AG, AI, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BZ, CA, CC, CG, CH, CI, CK, CL, CM, CN, CO, CR, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KR, KW, KY, KZ, LA, LC, LI, LK, LR, LS, LT, LU, LV, MA, MC, MD, ME, MF, MG, MH, MK, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RE, RO, RS, RW, SA, SB, SC, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SR, ST, SV, SX, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TT, TV, TZ, UG, UM, UY, UZ, VA, VC, VG, VI, VN, VU, WF, WS, YT, ZA, ZM, US", currency = "USD, CAD" } [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } @@ -884,7 +885,7 @@ stripe = { long_lived_token = false, payment_method = "wallet", payment_method_t billwerk = {long_lived_token = false, payment_method = "card"} globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } -finix= { long_lived_token = false, payment_method = "card" } +finix= { long_lived_token = false, payment_method = "card,wallet" } [webhooks] outgoing_enabled = true diff --git a/config/deployments/production.toml b/config/deployments/production.toml index efb770b10f9..356d8e828a4 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -530,6 +530,7 @@ pix = { country = "BR", currency = "BRL" } [pm_filters.finix] 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} +google_pay = { country = "AD, AE, AG, AI, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BZ, CA, CC, CG, CH, CI, CK, CL, CM, CN, CO, CR, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KR, KW, KY, KZ, LA, LC, LI, LK, LR, LS, LT, LU, LV, MA, MC, MD, ME, MF, MG, MH, MK, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RE, RO, RS, RW, SA, SB, SC, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SR, ST, SV, SX, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TT, TV, TZ, UG, UM, UY, UZ, VA, VC, VG, VI, VN, VU, WF, WS, YT, ZA, ZM, US", currency = "USD, CAD" } [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } @@ -893,7 +894,7 @@ stripe = { long_lived_token = false, payment_method = "wallet", payment_method_t billwerk = {long_lived_token = false, payment_method = "card"} globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } -finix= { long_lived_token = false, payment_method = "card" } +finix= { long_lived_token = false, payment_method = "card,wallet" } [webhooks] outgoing_enabled = true diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 87de6f3e430..95a4532cddf 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -512,6 +512,7 @@ pix = { country = "BR", currency = "BRL" } [pm_filters.finix] 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} +google_pay = { country = "AD, AE, AG, AI, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BZ, CA, CC, CG, CH, CI, CK, CL, CM, CN, CO, CR, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KR, KW, KY, KZ, LA, LC, LI, LK, LR, LS, LT, LU, LV, MA, MC, MD, ME, MF, MG, MH, MK, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RE, RO, RS, RW, SA, SB, SC, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SR, ST, SV, SX, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TT, TV, TZ, UG, UM, UY, UZ, VA, VC, VG, VI, VN, VU, WF, WS, YT, ZA, ZM, US", currency = "USD, CAD" } [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } @@ -899,7 +900,7 @@ stripe = { long_lived_token = false, payment_method = "wallet", payment_method_t billwerk = {long_lived_token = false, payment_method = "card"} globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } -finix= { long_lived_token = false, payment_method = "card" } +finix= { long_lived_token = false, payment_method = "card,wallet" } [webhooks] outgoing_enabled = true diff --git a/config/development.toml b/config/development.toml index a0555ec8f3e..a6ad358f6fb 100644 --- a/config/development.toml +++ b/config/development.toml @@ -714,6 +714,7 @@ pix = { country = "BR", currency = "BRL" } [pm_filters.finix] 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} +google_pay = { country = "AD, AE, AG, AI, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BZ, CA, CC, CG, CH, CI, CK, CL, CM, CN, CO, CR, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KR, KW, KY, KZ, LA, LC, LI, LK, LR, LS, LT, LU, LV, MA, MC, MD, ME, MF, MG, MH, MK, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RE, RO, RS, RW, SA, SB, SC, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SR, ST, SV, SX, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TT, TV, TZ, UG, UM, UY, UZ, VA, VC, VG, VI, VN, VU, WF, WS, YT, ZA, ZM, US", currency = "USD, CAD" } [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } @@ -1026,7 +1027,7 @@ gocardless = { long_lived_token = true, payment_method = "bank_debit" } billwerk = { long_lived_token = false, payment_method = "card" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } -finix= { long_lived_token = false, payment_method = "card" } +finix= { long_lived_token = false, payment_method = "card,wallet" } [temp_locker_enable_config] stripe = { payment_method = "bank_transfer" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 989944b60ca..390c8e585a0 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -409,6 +409,7 @@ gocardless = { long_lived_token = true, payment_method = "bank_debit" } billwerk = { long_lived_token = false, payment_method = "card" } globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } +finix= { long_lived_token = false, payment_method = "card,wallet" } [temp_locker_enable_config] stripe = { payment_method = "bank_transfer" } @@ -989,6 +990,9 @@ apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } [pm_filters.paysafe] apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } +[pm_filters.finix] +google_pay = { country = "AD, AE, AG, AI, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BZ, CA, CC, CG, CH, CI, CK, CL, CM, CN, CO, CR, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KR, KW, KY, KZ, LA, LC, LI, LK, LR, LS, LT, LU, LV, MA, MC, MD, ME, MF, MG, MH, MK, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RE, RO, RS, RW, SA, SB, SC, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SR, ST, SV, SX, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TT, TV, TZ, UG, UM, UY, UZ, VA, VC, VG, VI, VN, VU, WF, WS, YT, ZA, ZM, US", currency = "USD, CAD" } + [bank_config.online_banking_fpx] adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" fiuu.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_of_china,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 0bc14f42dca..9cce297e1cf 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7307,6 +7307,12 @@ type = "Text" api_key = "Username" api_secret = "Password" key1 = "Merchant Id" +[finix.metadata.merchant_id] +name = "merchant_id" +label = "Merchant Identity Id" +placeholder = "Enter Merchant Identity Id" +required = true +type = "Text" [[finix.credit]] payment_method_type = "Mastercard" [[finix.credit]] @@ -7325,6 +7331,8 @@ payment_method_type = "UnionPay" payment_method_type = "Interac" [[finix.credit]] payment_method_type = "Maestro" +[[finix.wallet]] + payment_method_type = "google_pay" [loonio] [loonio.connector_auth.BodyKey] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 99042fae462..24ebfa005fd 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -6044,6 +6044,12 @@ type = "Text" api_key = "Username" api_secret = "Password" key1 = "Merchant Id" +[finix.metadata.merchant_id] +name = "merchant_id" +label = "Merchant Identity Id" +placeholder = "Enter Merchant Identity Id" +required = true +type = "Text" [[finix.credit]] payment_method_type = "Mastercard" [[finix.credit]] @@ -6062,7 +6068,8 @@ payment_method_type = "UnionPay" payment_method_type = "Interac" [[finix.credit]] payment_method_type = "Maestro" - +[[finix.wallet]] + payment_method_type = "google_pay" [loonio] [loonio.connector_auth.BodyKey] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 7aba1e4db05..517ca035ea7 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7283,6 +7283,12 @@ type = "Text" api_key = "Username" api_secret = "Password" key1 = "Merchant Id" +[finix.metadata.merchant_id] +name = "merchant_id" +label = "Merchant Identity Id" +placeholder = "Enter Merchant Identity Id" +required = true +type = "Text" [[finix.credit]] payment_method_type = "Mastercard" [[finix.credit]] @@ -7301,7 +7307,8 @@ payment_method_type = "UnionPay" payment_method_type = "Interac" [[finix.credit]] payment_method_type = "Maestro" - +[[finix.wallet]] + payment_method_type = "google_pay" [loonio] [loonio.connector_auth.BodyKey] diff --git a/crates/hyperswitch_connectors/src/connectors/finix.rs b/crates/hyperswitch_connectors/src/connectors/finix.rs index d47f03adf65..15e8f17bfb8 100644 --- a/crates/hyperswitch_connectors/src/connectors/finix.rs +++ b/crates/hyperswitch_connectors/src/connectors/finix.rs @@ -964,6 +964,16 @@ static FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = Lazy ), }, ); + finix_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: default_capture_methods.clone(), + specific_features: None, + }, + ); finix_supported_payment_methods }); diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs index f9e76be04a3..ea60f6d0815 100644 --- a/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs @@ -2,8 +2,9 @@ pub mod request; pub mod response; use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2, CountryAlpha3}; use common_utils::types::MinorUnit; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, + payment_method_data::{PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData}, router_flow_types::{ self as flows, @@ -28,7 +29,7 @@ use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ - get_unimplemented_payment_method_error_message, AddressDetailsData, CardData, + self, get_unimplemented_payment_method_error_message, AddressDetailsData, CardData, RouterData as _, }, }; @@ -37,6 +38,18 @@ pub struct FinixRouterData<'a, Flow, Req, Res> { pub amount: MinorUnit, pub router_data: &'a RouterData<Flow, Req, Res>, pub merchant_id: Secret<String>, + pub merchant_identity_id: Secret<String>, +} + +impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for FinixMeta { + type Error = error_stack::Report<ConnectorError>; + fn try_from( + meta_data: &Option<common_utils::pii::SecretSerdeValue>, + ) -> Result<Self, Self::Error> { + let metadata = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) + .change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?; + Ok(metadata) + } } impl<'a, Flow, Req, Res> TryFrom<(MinorUnit, &'a RouterData<Flow, Req, Res>)> @@ -47,11 +60,13 @@ impl<'a, Flow, Req, Res> TryFrom<(MinorUnit, &'a RouterData<Flow, Req, Res>)> fn try_from(value: (MinorUnit, &'a RouterData<Flow, Req, Res>)) -> Result<Self, Self::Error> { let (amount, router_data) = value; let auth = FinixAuthType::try_from(&router_data.connector_auth_type)?; + let connector_meta = FinixMeta::try_from(&router_data.connector_meta_data)?; Ok(Self { amount, router_data, merchant_id: auth.merchant_id, + merchant_identity_id: connector_meta.merchant_id, }) } } @@ -160,6 +175,28 @@ impl TryFrom<&FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsResp three_d_secure: None, }) } + PaymentMethodData::Wallet(WalletData::GooglePay(_)) => { + let source = item.router_data.get_payment_method_token()?; + Ok(Self { + amount: item.amount, + currency: item.router_data.request.currency, + source: match source { + PaymentMethodToken::Token(token) => token, + PaymentMethodToken::ApplePayDecrypt(_) => Err( + unimplemented_payment_method!("Apple Pay", "Simplified", "Finix"), + )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Finix"))? + } + PaymentMethodToken::GooglePayDecrypt(_) => { + Err(unimplemented_payment_method!("Google Pay", "Finix"))? + } + }, + merchant: item.merchant_id.clone(), + tags: None, + three_d_secure: None, + }) + } _ => Err( ConnectorError::NotImplemented("Payment method not supported".to_string()).into(), ), @@ -216,6 +253,32 @@ impl card_brand: None, // Finix determines this from the card number card_type: None, // Finix determines this from the card number additional_data: None, + merchant_identity: None, + third_party_token: None, + }) + } + PaymentMethodData::Wallet(WalletData::GooglePay(google_pay_wallet_data)) => { + let third_party_token = google_pay_wallet_data + .tokenization_data + .get_encrypted_google_pay_token() + .change_context(ConnectorError::MissingRequiredField { + field_name: "google_pay_token", + })?; + Ok(Self { + instrument_type: FinixPaymentInstrumentType::GOOGLEPAY, + name: item.router_data.get_optional_billing_full_name(), + identity: item.router_data.get_connector_customer_id()?, + number: None, + security_code: None, + expiration_month: None, + expiration_year: None, + tags: None, + address: None, + card_brand: None, + card_type: None, + additional_data: None, + merchant_identity: Some(item.merchant_identity_id.clone()), + third_party_token: Some(Secret::new(third_party_token)), }) } _ => Err(ConnectorError::NotImplemented( diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs index 703c12aa84e..a2392566d92 100644 --- a/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs +++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs @@ -6,6 +6,12 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use super::*; + +#[derive(Deserialize)] +pub struct FinixMeta { + pub merchant_id: Secret<String>, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FinixPaymentsRequest { pub amount: MinorUnit, @@ -54,9 +60,13 @@ pub struct FinixCreatePaymentInstrumentRequest { #[serde(rename = "type")] pub instrument_type: FinixPaymentInstrumentType, pub name: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] pub number: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] pub security_code: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] pub expiration_month: Option<Secret<i8>>, + #[serde(skip_serializing_if = "Option::is_none")] pub expiration_year: Option<Secret<i32>>, pub identity: String, pub tags: Option<FinixTags>, @@ -64,6 +74,8 @@ pub struct FinixCreatePaymentInstrumentRequest { pub card_brand: Option<String>, pub card_type: Option<FinixCardType>, pub additional_data: Option<HashMap<String, String>>, + pub merchant_identity: Option<Secret<String>>, + pub third_party_token: Option<Secret<String>>, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -143,6 +155,8 @@ pub enum FinixPaymentType { pub enum FinixPaymentInstrumentType { #[serde(rename = "PAYMENT_CARD")] PaymentCard, + #[serde(rename = "GOOGLE_PAY")] + GOOGLEPAY, #[serde(rename = "BANK_ACCOUNT")] BankAccount, diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index a38e55e4205..af67a69c837 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -588,6 +588,7 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { } api_enums::Connector::Finix => { finix::transformers::FinixAuthType::try_from(self.auth_type)?; + finix::transformers::FinixMeta::try_from(self.connector_meta_data)?; Ok(()) } } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 43a6c494c22..34ff72eb48b 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -699,6 +699,9 @@ apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } [pm_filters.paysafe] apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } +[pm_filters.finix] +google_pay = { country = "AD, AE, AG, AI, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BZ, CA, CC, CG, CH, CI, CK, CL, CM, CN, CO, CR, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KR, KW, KY, KZ, LA, LC, LI, LK, LR, LS, LT, LU, LV, MA, MC, MD, ME, MF, MG, MH, MK, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RE, RO, RS, RW, SA, SB, SC, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SR, ST, SV, SX, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TT, TV, TZ, UG, UM, UY, UZ, VA, VC, VG, VI, VN, VU, WF, WS, YT, ZA, ZM, US", currency = "USD, 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" } }
2025-10-07T20:50:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9733) ## Description <!-- Describe your changes in detail --> Added google pay connector tokenization flow for finix connector. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Screenshot of PMT Flow: <img width="1725" height="303" alt="Screenshot 2025-10-10 at 12 35 50 PM" src="https://github.com/user-attachments/assets/073251b3-0a49-45da-ac62-e6e7d741e41c" /> Postman Test Payments-Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ••••••' \ --data-raw '{ "amount": 6500, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6500, "customer_id": "Customer4", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "description": "Credit one: Visa •••• 4242", "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": TOKEN }, "type": "CARD", "info": { "card_network": "VISA", "card_details": "4242" } } } }, "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": "2025-07-25T11:46:12Z" } }' ``` Response: ``` { "payment_id": "pay_8UIPJRDCTTBl0bY0UKu3", "merchant_id": "merchant_1759869874", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "finix", "client_secret": "pay_8UIPJRDCTTBl0bY0UKu3_secret_e6kUS5t7w2W73ieJstMk", "created": "2025-10-07T20:45:05.362Z", "currency": "USD", "customer_id": "Customer4", "customer": { "id": "Customer4", "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": { "google_pay": { "last4": "4242", "card_network": "VISA", "type": "CARD" } }, "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", "origin_zip": 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": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "Customer4", "created_at": 1759869905, "expires": 1759873505, "secret": "epk_8a72edc8a39c469597e02db4f36a04ab" }, "manual_retry_allowed": null, "connector_transaction_id": "TRh8uFLCwyh3iZ8roaT1ksyX", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_Ykn6DQM8KzGMHYEnWRW5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_Q2qpsZHuZ3gq7cTIQvic", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-07T21:00:05.362Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-07T20:45:08.949Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
5c6635be29def50cd64a40a16d906bc21175a381
juspay/hyperswitch
juspay__hyperswitch-9739
Bug: Add support to create subscription with plans having trial period
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 5d8c7a3f0bd..a2cd9d19041 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5025,7 +5025,7 @@ pub enum NextActionType { RedirectInsidePopup, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow @@ -5097,7 +5097,7 @@ pub enum NextActionData { }, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] @@ -5115,7 +5115,7 @@ pub enum IframeData { }, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, @@ -5131,7 +5131,7 @@ pub struct ThreeDsData { pub directory_server_id: Option<String>, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum ThreeDsMethodData { AcsThreeDsMethodData { @@ -5148,7 +5148,7 @@ pub enum ThreeDsMethodData { }, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum ThreeDsMethodKey { #[serde(rename = "threeDSMethodData")] ThreeDsMethodData, @@ -5156,7 +5156,7 @@ pub enum ThreeDsMethodKey { JWT, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, @@ -7761,7 +7761,7 @@ pub struct GooglePayTokenizationParameters { pub stripe_version: Option<Secret<String>>, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { @@ -7819,7 +7819,7 @@ pub struct HyperswitchVaultSessionDetails { pub profile_id: Secret<String>, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID @@ -7839,7 +7839,7 @@ pub struct PazeSessionTokenResponse { pub email_address: Option<Email>, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk @@ -7848,7 +7848,7 @@ pub enum GpaySessionTokenResponse { GooglePaySession(GooglePaySessionResponse), } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response @@ -7859,7 +7859,7 @@ pub struct GooglePayThirdPartySdk { pub sdk_next_action: SdkNextAction, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info @@ -7884,7 +7884,7 @@ pub struct GooglePaySessionResponse { pub secrets: Option<SecretInfoToInitiateSdk>, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version @@ -7908,13 +7908,13 @@ pub struct SamsungPaySessionTokenResponse { pub shipping_address_required: bool, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen @@ -7926,7 +7926,7 @@ pub struct SamsungPayMerchantPaymentInformation { pub country_code: api_enums::CountryAlpha2, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] @@ -7941,7 +7941,7 @@ pub struct SamsungPayAmountDetails { pub total_amount: StringMajorUnit, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only @@ -7950,14 +7950,14 @@ pub enum SamsungPayAmountFormat { FormatTotalEstimatedAmount, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna @@ -7985,7 +7985,7 @@ pub struct PaypalTransactionInfo { pub total_price: StringMajorUnit, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector @@ -8000,14 +8000,14 @@ pub struct PaypalSessionTokenResponse { pub transaction_info: Option<PaypalTransactionInfo>, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay @@ -8030,7 +8030,7 @@ pub struct ApplepaySessionTokenResponse { pub connector_merchant_id: Option<String>, } -#[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] +#[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, @@ -8051,7 +8051,7 @@ pub enum NextActionCall { AwaitMerchantCallback, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved @@ -8090,7 +8090,7 @@ pub struct NoThirdPartySdkSessionResponse { pub psp_id: String, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } @@ -8211,7 +8211,7 @@ pub struct ApplepayErrorResponse { pub status_message: String, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPaySessionTokenResponse { /// Amazon Pay merchant account identifier pub merchant_id: String, @@ -8235,7 +8235,7 @@ pub struct AmazonPaySessionTokenResponse { pub delivery_options: Vec<AmazonPayDeliveryOptions>, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum AmazonPayPaymentIntent { /// Create a Charge Permission to authorize and capture funds at a later time Confirm, @@ -9291,7 +9291,7 @@ pub struct ExtendedCardInfoResponse { pub payload: String, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, @@ -9951,7 +9951,7 @@ pub struct RecordAttemptErrorDetails { pub network_error_message: Option<String>, } -#[derive(Debug, Clone, Eq, PartialEq, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema)] pub struct NullObject; impl Serialize for NullObject { diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs index 45e32a31c66..c7aea80d4f2 100644 --- a/crates/api_models/src/subscription.rs +++ b/crates/api_models/src/subscription.rs @@ -6,7 +6,7 @@ use utoipa::ToSchema; use crate::{ enums as api_enums, mandates::RecurringDetails, - payments::{Address, PaymentMethodDataRequest}, + payments::{Address, NextActionData, PaymentMethodDataRequest}, }; /// Request payload for creating a subscription. @@ -216,6 +216,7 @@ pub struct ConfirmSubscriptionPaymentDetails { pub payment_method_type: Option<api_enums::PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, pub customer_acceptance: Option<CustomerAcceptance>, + pub payment_type: Option<api_enums::PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -224,6 +225,7 @@ pub struct CreateSubscriptionPaymentDetails { pub setup_future_usage: Option<api_enums::FutureUsage>, pub capture_method: Option<api_enums::CaptureMethod>, pub authentication_type: Option<api_enums::AuthenticationType>, + pub payment_type: Option<api_enums::PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -236,6 +238,7 @@ pub struct PaymentDetails { pub return_url: Option<common_utils::types::Url>, pub capture_method: Option<api_enums::CaptureMethod>, pub authentication_type: Option<api_enums::AuthenticationType>, + pub payment_type: Option<api_enums::PaymentType>, } // Creating new type for PaymentRequest API call as usage of api_models::PaymentsRequest will result in invalid payment request during serialization @@ -247,6 +250,7 @@ pub struct CreatePaymentsRequestData { pub customer_id: Option<common_utils::id_type::CustomerId>, pub billing: Option<Address>, pub shipping: Option<Address>, + pub profile_id: Option<common_utils::id_type::ProfileId>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub return_url: Option<common_utils::types::Url>, pub capture_method: Option<api_enums::CaptureMethod>, @@ -257,10 +261,12 @@ pub struct CreatePaymentsRequestData { pub struct ConfirmPaymentsRequestData { pub billing: Option<Address>, pub shipping: Option<Address>, + pub profile_id: Option<common_utils::id_type::ProfileId>, pub payment_method: api_enums::PaymentMethod, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, pub customer_acceptance: Option<CustomerAcceptance>, + pub payment_type: Option<api_enums::PaymentType>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] @@ -271,6 +277,7 @@ pub struct CreateAndConfirmPaymentsRequestData { pub confirm: bool, pub billing: Option<Address>, pub shipping: Option<Address>, + pub profile_id: Option<common_utils::id_type::ProfileId>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub return_url: Option<common_utils::types::Url>, pub capture_method: Option<api_enums::CaptureMethod>, @@ -279,6 +286,7 @@ pub struct CreateAndConfirmPaymentsRequestData { pub payment_method_type: Option<api_enums::PaymentMethodType>, pub payment_method_data: Option<PaymentMethodDataRequest>, pub customer_acceptance: Option<CustomerAcceptance>, + pub payment_type: Option<api_enums::PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -287,13 +295,17 @@ pub struct PaymentResponseData { pub status: api_enums::IntentStatus, pub amount: MinorUnit, pub currency: api_enums::Currency, + pub profile_id: Option<common_utils::id_type::ProfileId>, pub connector: Option<String>, pub payment_method_id: Option<Secret<String>>, + pub return_url: Option<common_utils::types::Url>, + pub next_action: Option<NextActionData>, pub payment_experience: Option<api_enums::PaymentExperience>, pub error_code: Option<String>, pub error_message: Option<String>, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub client_secret: Option<Secret<String>>, + pub payment_type: Option<api_enums::PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -304,6 +316,7 @@ pub struct CreateMitPaymentRequestData { pub customer_id: Option<common_utils::id_type::CustomerId>, pub recurring_details: Option<RecurringDetails>, pub off_session: Option<bool>, + pub profile_id: Option<common_utils::id_type::ProfileId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -452,7 +465,7 @@ pub struct Invoice { pub currency: api_enums::Currency, /// Status of the invoice. - pub status: String, + pub status: common_enums::connector_enums::InvoiceStatus, } impl ApiEventMetric for ConfirmSubscriptionResponse {} diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index fe11c685aec..6b42837bc27 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -900,7 +900,19 @@ impl TryFrom<Connector> for RoutableConnectors { } // Enum representing different status an invoice can have. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, strum::Display, strum::EnumString)] +#[derive( + Debug, + Clone, + PartialEq, + Eq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum InvoiceStatus { InvoiceCreated, diff --git a/crates/diesel_models/src/invoice.rs b/crates/diesel_models/src/invoice.rs index 2b93b0b4a62..cbb3b251d19 100644 --- a/crates/diesel_models/src/invoice.rs +++ b/crates/diesel_models/src/invoice.rs @@ -18,12 +18,12 @@ pub struct InvoiceNew { pub customer_id: common_utils::id_type::CustomerId, pub amount: MinorUnit, pub currency: String, - pub status: String, + pub status: InvoiceStatus, pub provider_name: Connector, pub metadata: Option<SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, - pub connector_invoice_id: Option<String>, + pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } #[derive( @@ -45,20 +45,20 @@ pub struct Invoice { pub customer_id: common_utils::id_type::CustomerId, pub amount: MinorUnit, pub currency: String, - pub status: String, + pub status: InvoiceStatus, pub provider_name: Connector, pub metadata: Option<SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, - pub connector_invoice_id: Option<String>, + pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Deserialize)] #[diesel(table_name = invoice)] pub struct InvoiceUpdate { - pub status: Option<String>, + pub status: Option<InvoiceStatus>, pub payment_method_id: Option<String>, - pub connector_invoice_id: Option<String>, + pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, pub modified_at: time::PrimitiveDateTime, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, } @@ -78,7 +78,7 @@ impl InvoiceNew { status: InvoiceStatus, provider_name: Connector, metadata: Option<SecretSerdeValue>, - connector_invoice_id: Option<String>, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> Self { let id = common_utils::id_type::InvoiceId::generate(); let now = common_utils::date_time::now(); @@ -93,7 +93,7 @@ impl InvoiceNew { customer_id, amount, currency, - status: status.to_string(), + status, provider_name, metadata, created_at: now, @@ -107,12 +107,12 @@ impl InvoiceUpdate { pub fn new( payment_method_id: Option<String>, status: Option<InvoiceStatus>, - connector_invoice_id: Option<String>, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, payment_intent_id: Option<common_utils::id_type::PaymentId>, ) -> Self { Self { payment_method_id, - status: status.map(|status| status.to_string()), + status, connector_invoice_id, payment_intent_id, modified_at: common_utils::date_time::now(), diff --git a/crates/diesel_models/src/query/invoice.rs b/crates/diesel_models/src/query/invoice.rs index 0166469d340..6e62d9b5b5f 100644 --- a/crates/diesel_models/src/query/invoice.rs +++ b/crates/diesel_models/src/query/invoice.rs @@ -1,4 +1,4 @@ -use diesel::{associations::HasTable, ExpressionMethods}; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ @@ -66,4 +66,18 @@ impl Invoice { .await } } + + pub async fn get_invoice_by_subscription_id_connector_invoice_id( + conn: &PgPooledConn, + subscription_id: String, + connector_invoice_id: common_utils::id_type::InvoiceId, + ) -> StorageResult<Option<Self>> { + generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( + conn, + dsl::subscription_id + .eq(subscription_id.to_owned()) + .and(dsl::connector_invoice_id.eq(connector_invoice_id.to_owned())), + ) + .await + } } diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 720296cdcac..6179e221694 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -6,6 +6,7 @@ use common_utils::{ date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, + ext_traits::ValueExt, id_type, pii, types::{ keymanager::{self, KeyManagerState, ToEncryptable}, @@ -90,6 +91,23 @@ impl Customer { &self.id } + /// Get the connector customer ID for the specified connector label, if present + #[cfg(feature = "v1")] + pub fn get_connector_customer_map( + &self, + ) -> FxHashMap<id_type::MerchantConnectorAccountId, String> { + use masking::PeekInterface; + if let Some(connector_customer_value) = &self.connector_customer { + connector_customer_value + .peek() + .clone() + .parse_value("ConnectorCustomerMap") + .unwrap_or_default() + } else { + FxHashMap::default() + } + } + /// Get the connector customer ID for the specified connector label, if present #[cfg(feature = "v1")] pub fn get_connector_customer_id(&self, connector_label: &str) -> Option<&str> { diff --git a/crates/hyperswitch_domain_models/src/invoice.rs b/crates/hyperswitch_domain_models/src/invoice.rs index 9457eac56d2..a6b836d3e58 100644 --- a/crates/hyperswitch_domain_models/src/invoice.rs +++ b/crates/hyperswitch_domain_models/src/invoice.rs @@ -1,5 +1,3 @@ -use std::str::FromStr; - use common_utils::{ errors::{CustomResult, ValidationError}, id_type::GenerateId, @@ -9,7 +7,6 @@ use common_utils::{ MinorUnit, }, }; -use error_stack::ResultExt; use masking::Secret; use utoipa::ToSchema; @@ -27,10 +24,10 @@ pub struct Invoice { pub customer_id: common_utils::id_type::CustomerId, pub amount: MinorUnit, pub currency: String, - pub status: String, + pub status: common_enums::connector_enums::InvoiceStatus, pub provider_name: common_enums::connector_enums::Connector, pub metadata: Option<SecretSerdeValue>, - pub connector_invoice_id: Option<String>, + pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } #[async_trait::async_trait] @@ -89,11 +86,6 @@ impl super::behaviour::Conversion for Invoice { } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { - let invoice_status = common_enums::connector_enums::InvoiceStatus::from_str(&self.status) - .change_context(ValidationError::InvalidValue { - message: "Invalid invoice status".to_string(), - })?; - Ok(diesel_models::invoice::InvoiceNew::new( self.subscription_id, self.merchant_id, @@ -104,7 +96,7 @@ impl super::behaviour::Conversion for Invoice { self.customer_id, self.amount, self.currency.to_string(), - invoice_status, + self.status, self.provider_name, None, self.connector_invoice_id, @@ -127,7 +119,7 @@ impl Invoice { status: common_enums::connector_enums::InvoiceStatus, provider_name: common_enums::connector_enums::Connector, metadata: Option<SecretSerdeValue>, - connector_invoice_id: Option<String>, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> Self { Self { id: common_utils::id_type::InvoiceId::generate(), @@ -140,7 +132,7 @@ impl Invoice { customer_id, amount, currency: currency.to_string(), - status: status.to_string(), + status, provider_name, metadata, connector_invoice_id, @@ -179,12 +171,20 @@ pub trait InvoiceInterface { key_store: &MerchantKeyStore, subscription_id: String, ) -> CustomResult<Invoice, Self::Error>; + + async fn find_invoice_by_subscription_id_connector_invoice_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_id: String, + connector_invoice_id: common_utils::id_type::InvoiceId, + ) -> CustomResult<Option<Invoice>, Self::Error>; } pub struct InvoiceUpdate { - pub status: Option<String>, + pub status: Option<common_enums::connector_enums::InvoiceStatus>, pub payment_method_id: Option<String>, - pub connector_invoice_id: Option<String>, + pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, pub modified_at: time::PrimitiveDateTime, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, } @@ -236,15 +236,15 @@ impl InvoiceUpdate { pub fn new( payment_method_id: Option<String>, status: Option<common_enums::connector_enums::InvoiceStatus>, - connector_invoice_id: Option<String>, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, payment_intent_id: Option<common_utils::id_type::PaymentId>, ) -> Self { Self { payment_method_id, - status: status.map(|status| status.to_string()), - connector_invoice_id, + status, modified_at: common_utils::date_time::now(), payment_intent_id, + connector_invoice_id, } } } diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 05254a9b77d..e2d376f3f08 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -35,7 +35,7 @@ pub async fn create_subscription( SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable("subscriptions: failed to find business profile")?; - let customer = + let _customer = SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id) .await .attach_printable("subscriptions: failed to find customer")?; @@ -43,7 +43,6 @@ pub async fn create_subscription( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), - Some(customer), profile.clone(), ) .await?; @@ -119,7 +118,6 @@ pub async fn get_subscription_plans( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), - None, profile.clone(), ) .await?; @@ -169,7 +167,6 @@ pub async fn create_and_confirm_subscription( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), - Some(customer), profile.clone(), ) .await?; @@ -187,9 +184,10 @@ pub async fn create_and_confirm_subscription( .attach_printable("subscriptions: failed to create subscription entry")?; let invoice_handler = subs_handler.get_invoice_handler(profile.clone()); - let _customer_create_response = billing_handler + let customer_create_response = billing_handler .create_customer_on_connector( &state, + customer.clone(), request.customer_id.clone(), request.billing.clone(), request @@ -199,6 +197,15 @@ pub async fn create_and_confirm_subscription( .and_then(|data| data.payment_method_data), ) .await?; + let _customer_updated_response = SubscriptionHandler::update_connector_customer_id_in_customer( + &state, + &merchant_context, + &billing_handler.merchant_connector_id, + &customer, + customer_create_response, + ) + .await + .attach_printable("Failed to update customer with connector customer ID")?; let subscription_create_response = billing_handler .create_subscription_on_connector( @@ -232,9 +239,7 @@ pub async fn create_and_confirm_subscription( .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), billing_handler.connector_data.connector_name, None, - invoice_details - .clone() - .map(|invoice| invoice.id.get_string_repr().to_string()), + invoice_details.clone().map(|invoice| invoice.id), ) .await?; @@ -242,13 +247,7 @@ pub async fn create_and_confirm_subscription( .create_invoice_sync_job( &state, &invoice_entry, - invoice_details - .ok_or(errors::ApiErrorResponse::MissingRequiredField { - field_name: "invoice_details", - })? - .id - .get_string_repr() - .to_string(), + invoice_details.clone().map(|details| details.id), billing_handler.connector_data.connector_name, ) .await?; @@ -327,16 +326,16 @@ pub async fn confirm_subscription( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), - Some(customer), profile.clone(), ) .await?; let invoice_handler = subscription_entry.get_invoice_handler(profile); let subscription = subscription_entry.subscription.clone(); - let _customer_create_response = billing_handler + let customer_create_response = billing_handler .create_customer_on_connector( &state, + customer.clone(), subscription.customer_id.clone(), request.payment_details.payment_method_data.billing.clone(), request @@ -345,6 +344,15 @@ pub async fn confirm_subscription( .payment_method_data, ) .await?; + let _customer_updated_response = SubscriptionHandler::update_connector_customer_id_in_customer( + &state, + &merchant_context, + &billing_handler.merchant_connector_id, + &customer, + customer_create_response, + ) + .await + .attach_printable("Failed to update customer with connector customer ID")?; let subscription_create_response = billing_handler .create_subscription_on_connector( @@ -366,9 +374,7 @@ pub async fn confirm_subscription( .clone() .and_then(|invoice| invoice.status) .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), - invoice_details - .clone() - .map(|invoice| invoice.id.get_string_repr().to_string()), + invoice_details.clone().map(|invoice| invoice.id), ) .await?; @@ -376,14 +382,7 @@ pub async fn confirm_subscription( .create_invoice_sync_job( &state, &invoice_entry, - invoice_details - .clone() - .ok_or(errors::ApiErrorResponse::MissingRequiredField { - field_name: "invoice_details", - })? - .id - .get_string_repr() - .to_string(), + invoice_details.map(|invoice| invoice.id), billing_handler.connector_data.connector_name, ) .await?; @@ -449,7 +448,6 @@ pub async fn get_estimate( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), - None, profile, ) .await?; diff --git a/crates/router/src/core/subscription/billing_processor_handler.rs b/crates/router/src/core/subscription/billing_processor_handler.rs index 910596d66c4..00ca480e5ea 100644 --- a/crates/router/src/core/subscription/billing_processor_handler.rs +++ b/crates/router/src/core/subscription/billing_processor_handler.rs @@ -31,7 +31,6 @@ pub struct BillingHandler { pub connector_data: api_types::ConnectorData, pub connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams, pub connector_metadata: Option<pii::SecretSerdeValue>, - pub customer: Option<hyperswitch_domain_models::customer::Customer>, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, } @@ -41,7 +40,6 @@ impl BillingHandler { state: &SessionState, merchant_account: &hyperswitch_domain_models::merchant_account::MerchantAccount, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, - customer: Option<hyperswitch_domain_models::customer::Customer>, profile: hyperswitch_domain_models::business_profile::Profile, ) -> errors::RouterResult<Self> { let merchant_connector_id = profile.get_billing_processor_id()?; @@ -102,24 +100,22 @@ impl BillingHandler { connector_data, connector_params, connector_metadata: billing_processor_mca.metadata.clone(), - customer, merchant_connector_id, }) } pub async fn create_customer_on_connector( &self, state: &SessionState, + customer: hyperswitch_domain_models::customer::Customer, customer_id: common_utils::id_type::CustomerId, billing_address: Option<api_models::payments::Address>, payment_method_data: Option<api_models::payments::PaymentMethodData>, - ) -> errors::RouterResult<ConnectorCustomerResponseData> { - let customer = - self.customer - .as_ref() - .ok_or(errors::ApiErrorResponse::MissingRequiredField { - field_name: "customer", - })?; - + ) -> errors::RouterResult<Option<ConnectorCustomerResponseData>> { + let connector_customer_map = customer.get_connector_customer_map(); + if connector_customer_map.contains_key(&self.merchant_connector_id) { + // Customer already exists on the connector, no need to create again + return Ok(None); + } let customer_req = ConnectorCustomerData { email: customer.email.clone().map(pii::Email::from), payment_method_data: payment_method_data.clone().map(|pmd| pmd.into()), @@ -156,7 +152,7 @@ impl BillingHandler { match response { Ok(response_data) => match response_data { PaymentsResponseData::ConnectorCustomerResponse(customer_response) => { - Ok(customer_response) + Ok(Some(customer_response)) } _ => Err(errors::ApiErrorResponse::SubscriptionError { operation: "Subscription Customer Create".to_string(), @@ -233,7 +229,7 @@ impl BillingHandler { pub async fn record_back_to_billing_processor( &self, state: &SessionState, - invoice_id: String, + invoice_id: common_utils::id_type::InvoiceId, payment_id: common_utils::id_type::PaymentId, payment_status: common_enums::AttemptStatus, amount: common_utils::types::MinorUnit, @@ -245,10 +241,12 @@ impl BillingHandler { currency, payment_method_type, attempt_status: payment_status, - merchant_reference_id: common_utils::id_type::PaymentReferenceId::from_str(&invoice_id) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "invoice_id", - })?, + merchant_reference_id: common_utils::id_type::PaymentReferenceId::from_str( + invoice_id.get_string_repr(), + ) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "invoice_id", + })?, connector_params: self.connector_params.clone(), connector_transaction_id: Some(common_utils::types::ConnectorTransactionId::TxnId( payment_id.get_string_repr().to_string(), @@ -392,7 +390,6 @@ impl BillingHandler { connector_integration, ) .await?; - match response { Ok(resp) => Ok(resp), Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { diff --git a/crates/router/src/core/subscription/invoice_handler.rs b/crates/router/src/core/subscription/invoice_handler.rs index b383f7a4650..bcdc1b74779 100644 --- a/crates/router/src/core/subscription/invoice_handler.rs +++ b/crates/router/src/core/subscription/invoice_handler.rs @@ -10,9 +10,7 @@ use masking::{PeekInterface, Secret}; use super::errors; use crate::{ - core::{errors::utils::StorageErrorExt, subscription::payments_api_client}, - routes::SessionState, - types::storage as storage_types, + core::subscription::payments_api_client, routes::SessionState, types::storage as storage_types, workflows::invoice_sync as invoice_sync_workflow, }; @@ -20,6 +18,7 @@ pub struct InvoiceHandler { pub subscription: hyperswitch_domain_models::subscription::Subscription, pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, pub profile: hyperswitch_domain_models::business_profile::Profile, + pub merchant_key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, } #[allow(clippy::todo)] @@ -28,11 +27,13 @@ impl InvoiceHandler { subscription: hyperswitch_domain_models::subscription::Subscription, merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, profile: hyperswitch_domain_models::business_profile::Profile, + merchant_key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> Self { Self { subscription, merchant_account, profile, + merchant_key_store, } } #[allow(clippy::too_many_arguments)] @@ -46,7 +47,7 @@ impl InvoiceHandler { status: connector_enums::InvoiceStatus, provider_name: connector_enums::Connector, metadata: Option<pii::SecretSerdeValue>, - connector_invoice_id: Option<String>, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> { let invoice_new = hyperswitch_domain_models::invoice::Invoice::to_invoice( self.subscription.id.to_owned(), @@ -65,18 +66,9 @@ impl InvoiceHandler { ); let key_manager_state = &(state).into(); - let merchant_key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - self.merchant_account.get_id(), - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let invoice = state .store - .insert_invoice_entry(key_manager_state, &merchant_key_store, invoice_new) + .insert_invoice_entry(key_manager_state, &self.merchant_key_store, invoice_new) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Create Invoice".to_string(), @@ -93,7 +85,7 @@ impl InvoiceHandler { payment_method_id: Option<Secret<String>>, payment_intent_id: Option<common_utils::id_type::PaymentId>, status: connector_enums::InvoiceStatus, - connector_invoice_id: Option<String>, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> { let update_invoice = hyperswitch_domain_models::invoice::InvoiceUpdate::new( payment_method_id.as_ref().map(|id| id.peek()).cloned(), @@ -102,20 +94,11 @@ impl InvoiceHandler { payment_intent_id, ); let key_manager_state = &(state).into(); - let merchant_key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - self.merchant_account.get_id(), - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; state .store .update_invoice_entry( key_manager_state, - &merchant_key_store, + &self.merchant_key_store, invoice_id.get_string_repr().to_string(), update_invoice, ) @@ -151,6 +134,7 @@ impl InvoiceHandler { customer_id: Some(self.subscription.customer_id.clone()), billing: request.billing.clone(), shipping: request.shipping.clone(), + profile_id: Some(self.profile.get_id().clone()), setup_future_usage: payment_details.setup_future_usage, return_url: Some(payment_details.return_url.clone()), capture_method: payment_details.capture_method, @@ -194,6 +178,7 @@ impl InvoiceHandler { customer_id: Some(self.subscription.customer_id.clone()), billing: request.billing.clone(), shipping: request.shipping.clone(), + profile_id: Some(self.profile.get_id().clone()), setup_future_usage: payment_details.setup_future_usage, return_url: payment_details.return_url.clone(), capture_method: payment_details.capture_method, @@ -202,6 +187,7 @@ impl InvoiceHandler { payment_method_type: payment_details.payment_method_type, payment_method_data: payment_details.payment_method_data.clone(), customer_acceptance: payment_details.customer_acceptance.clone(), + payment_type: payment_details.payment_type, }; payments_api_client::PaymentsApiClient::create_and_confirm_payment( state, @@ -222,10 +208,12 @@ impl InvoiceHandler { let cit_payment_request = subscription_types::ConfirmPaymentsRequestData { billing: request.payment_details.payment_method_data.billing.clone(), shipping: request.payment_details.shipping.clone(), + profile_id: Some(self.profile.get_id().clone()), payment_method: payment_details.payment_method, payment_method_type: payment_details.payment_method_type, payment_method_data: payment_details.payment_method_data.clone(), customer_acceptance: payment_details.customer_acceptance.clone(), + payment_type: payment_details.payment_type, }; payments_api_client::PaymentsApiClient::confirm_payment( state, @@ -242,20 +230,11 @@ impl InvoiceHandler { state: &SessionState, ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> { let key_manager_state = &(state).into(); - let merchant_key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - self.merchant_account.get_id(), - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; state .store .get_latest_invoice_for_subscription( key_manager_state, - &merchant_key_store, + &self.merchant_key_store, self.subscription.id.get_string_repr().to_string(), ) .await @@ -271,20 +250,11 @@ impl InvoiceHandler { invoice_id: common_utils::id_type::InvoiceId, ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> { let key_manager_state = &(state).into(); - let merchant_key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - self.merchant_account.get_id(), - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; state .store .find_invoice_by_invoice_id( key_manager_state, - &merchant_key_store, + &self.merchant_key_store, invoice_id.get_string_repr().to_string(), ) .await @@ -294,11 +264,33 @@ impl InvoiceHandler { .attach_printable("invoices: unable to get invoice by id from database") } + pub async fn find_invoice_by_subscription_id_connector_invoice_id( + &self, + state: &SessionState, + subscription_id: common_utils::id_type::SubscriptionId, + connector_invoice_id: common_utils::id_type::InvoiceId, + ) -> errors::RouterResult<Option<hyperswitch_domain_models::invoice::Invoice>> { + let key_manager_state = &(state).into(); + state + .store + .find_invoice_by_subscription_id_connector_invoice_id( + key_manager_state, + &self.merchant_key_store, + subscription_id.get_string_repr().to_string(), + connector_invoice_id, + ) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: "Get Invoice by Subscription ID and Connector Invoice ID".to_string(), + }) + .attach_printable("invoices: unable to get invoice by subscription id and connector invoice id from database") + } + pub async fn create_invoice_sync_job( &self, state: &SessionState, invoice: &hyperswitch_domain_models::invoice::Invoice, - connector_invoice_id: String, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, connector_name: connector_enums::Connector, ) -> errors::RouterResult<()> { let request = storage_types::invoice_sync::InvoiceSyncRequest::new( @@ -333,6 +325,7 @@ impl InvoiceHandler { payment_method_id.to_owned(), )), off_session: Some(true), + profile_id: Some(self.profile.get_id().clone()), }; payments_api_client::PaymentsApiClient::create_mit_payment( diff --git a/crates/router/src/core/subscription/payments_api_client.rs b/crates/router/src/core/subscription/payments_api_client.rs index e530a5843c8..b688e3bc339 100644 --- a/crates/router/src/core/subscription/payments_api_client.rs +++ b/crates/router/src/core/subscription/payments_api_client.rs @@ -36,6 +36,10 @@ impl PaymentsApiClient { .clone(), ), ), + ( + headers::X_TENANT_ID.to_string(), + masking::Maskable::Normal(state.tenant.tenant_id.get_string_repr().to_string()), + ), ( headers::X_MERCHANT_ID.to_string(), masking::Maskable::Normal(merchant_id.to_string()), diff --git a/crates/router/src/core/subscription/subscription_handler.rs b/crates/router/src/core/subscription/subscription_handler.rs index 76799c21a74..1f29f38073e 100644 --- a/crates/router/src/core/subscription/subscription_handler.rs +++ b/crates/router/src/core/subscription/subscription_handler.rs @@ -9,14 +9,17 @@ use common_utils::{consts, ext_traits::OptionExt}; use error_stack::ResultExt; use hyperswitch_domain_models::{ merchant_context::MerchantContext, - router_response_types::subscriptions as subscription_response_types, + router_response_types::{self, subscriptions as subscription_response_types}, subscription::{Subscription, SubscriptionStatus}, }; use masking::Secret; use super::errors; use crate::{ - core::{errors::StorageErrorExt, subscription::invoice_handler::InvoiceHandler}, + core::{ + errors::StorageErrorExt, payments as payments_core, + subscription::invoice_handler::InvoiceHandler, + }, db::CustomResult, routes::SessionState, types::{domain, transformers::ForeignTryFrom}, @@ -109,6 +112,64 @@ impl<'a> SubscriptionHandler<'a> { .change_context(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("subscriptions: unable to fetch customer from database") } + pub async fn update_connector_customer_id_in_customer( + state: &SessionState, + merchant_context: &MerchantContext, + merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, + customer: &hyperswitch_domain_models::customer::Customer, + customer_create_response: Option<router_response_types::ConnectorCustomerResponseData>, + ) -> errors::RouterResult<hyperswitch_domain_models::customer::Customer> { + match customer_create_response { + Some(customer_response) => { + match payments_core::customers::update_connector_customer_in_customers( + merchant_connector_id.get_string_repr(), + Some(customer), + Some(customer_response.connector_customer_id), + ) + .await + { + Some(customer_update) => Self::update_customer( + state, + merchant_context, + customer.clone(), + customer_update, + ) + .await + .attach_printable("Failed to update customer with connector customer ID"), + None => Ok(customer.clone()), + } + } + None => Ok(customer.clone()), + } + } + + pub async fn update_customer( + state: &SessionState, + merchant_context: &MerchantContext, + customer: hyperswitch_domain_models::customer::Customer, + customer_update: domain::CustomerUpdate, + ) -> errors::RouterResult<hyperswitch_domain_models::customer::Customer> { + let key_manager_state = &(state).into(); + let merchant_key_store = merchant_context.get_merchant_key_store(); + let merchant_id = merchant_context.get_merchant_account().get_id(); + let db = state.store.as_ref(); + + let updated_customer = db + .update_customer_by_customer_id_merchant_id( + key_manager_state, + customer.customer_id.clone(), + merchant_id.clone(), + customer, + customer_update, + merchant_key_store, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("subscriptions: unable to update customer entry in database")?; + + Ok(updated_customer) + } /// Helper function to find business profile. pub async fn find_business_profile( @@ -304,6 +365,11 @@ impl SubscriptionWithHandler<'_> { subscription: self.subscription.clone(), merchant_account: self.merchant_account.clone(), profile, + merchant_key_store: self + .handler + .merchant_context + .get_merchant_key_store() + .clone(), } } pub async fn get_mca( diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index ce183002834..62db07c8a3f 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -2600,10 +2600,6 @@ async fn subscription_incoming_webhook_flow( .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to extract MIT payment data from subscription webhook")?; - if mit_payment_data.first_invoice { - return Ok(WebhookResponseTracker::NoEffect); - } - let profile_id = business_profile.get_id().clone(); let profile = @@ -2618,11 +2614,29 @@ async fn subscription_incoming_webhook_flow( let subscription_id = mit_payment_data.subscription_id.clone(); let subscription_with_handler = handler - .find_subscription(subscription_id) + .find_subscription(subscription_id.clone()) .await .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?; let invoice_handler = subscription_with_handler.get_invoice_handler(profile.clone()); + let invoice = invoice_handler + .find_invoice_by_subscription_id_connector_invoice_id( + &state, + subscription_id, + mit_payment_data.invoice_id.clone(), + ) + .await + .attach_printable( + "subscriptions: failed to get invoice by subscription id and connector invoice id", + )?; + if let Some(invoice) = invoice { + // During CIT payment we would have already created invoice entry with status as PaymentPending or Paid. + // So we skip incoming webhook for the already processed invoice + if invoice.status != InvoiceStatus::InvoiceCreated { + logger::info!("Invoice is already being processed, skipping MIT payment creation"); + return Ok(WebhookResponseTracker::NoEffect); + } + } let payment_method_id = subscription_with_handler .subscription @@ -2635,17 +2649,36 @@ async fn subscription_incoming_webhook_flow( logger::info!("Payment method ID found: {}", payment_method_id); + let payment_id = generate_id(consts::ID_LENGTH, "pay"); + let payment_id = common_utils::id_type::PaymentId::wrap(payment_id).change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_id", + }, + )?; + + // Multiple MIT payments for the same invoice_generated event is avoided by having the unique constraint on (subscription_id, connector_invoice_id) in the invoices table let invoice_entry = invoice_handler .create_invoice_entry( &state, billing_connector_mca_id.clone(), - None, + Some(payment_id), mit_payment_data.amount_due, mit_payment_data.currency_code, InvoiceStatus::PaymentPending, connector, None, - None, + Some(mit_payment_data.invoice_id.clone()), + ) + .await?; + + // Create a sync job for the invoice with generated payment_id before initiating MIT payment creation. + // This ensures that if payment creation call fails, the sync job can still retrieve the payment status + invoice_handler + .create_invoice_sync_job( + &state, + &invoice_entry, + Some(mit_payment_data.invoice_id.clone()), + connector, ) .await?; @@ -2658,23 +2691,14 @@ async fn subscription_incoming_webhook_flow( ) .await?; - let updated_invoice = invoice_handler + let _updated_invoice = invoice_handler .update_invoice( &state, invoice_entry.id.clone(), payment_response.payment_method_id.clone(), Some(payment_response.payment_id.clone()), InvoiceStatus::from(payment_response.status), - Some(mit_payment_data.invoice_id.get_string_repr().to_string()), - ) - .await?; - - invoice_handler - .create_invoice_sync_job( - &state, - &updated_invoice, - mit_payment_data.invoice_id.get_string_repr().to_string(), - connector, + Some(mit_payment_data.invoice_id.clone()), ) .await?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 84799f91cf5..08e7b18678b 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -4393,6 +4393,24 @@ impl InvoiceInterface for KafkaStore { .get_latest_invoice_for_subscription(state, key_store, subscription_id) .await } + + #[instrument(skip_all)] + async fn find_invoice_by_subscription_id_connector_invoice_id( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + subscription_id: String, + connector_invoice_id: id_type::InvoiceId, + ) -> CustomResult<Option<DomainInvoice>, errors::StorageError> { + self.diesel_store + .find_invoice_by_subscription_id_connector_invoice_id( + state, + key_store, + subscription_id, + connector_invoice_id, + ) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/types/storage/invoice_sync.rs b/crates/router/src/types/storage/invoice_sync.rs index 01bbcf17d92..93bd983765b 100644 --- a/crates/router/src/types/storage/invoice_sync.rs +++ b/crates/router/src/types/storage/invoice_sync.rs @@ -7,7 +7,8 @@ pub struct InvoiceSyncTrackingData { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub customer_id: id_type::CustomerId, - pub connector_invoice_id: String, + // connector_invoice_id is optional because in some cases (Trial/Future), the invoice might not have been created in the connector yet. + pub connector_invoice_id: Option<id_type::InvoiceId>, pub connector_name: api_enums::Connector, // The connector to which the invoice belongs } @@ -18,7 +19,7 @@ pub struct InvoiceSyncRequest { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub customer_id: id_type::CustomerId, - pub connector_invoice_id: String, + pub connector_invoice_id: Option<id_type::InvoiceId>, pub connector_name: api_enums::Connector, } @@ -44,7 +45,7 @@ impl InvoiceSyncRequest { merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, customer_id: id_type::CustomerId, - connector_invoice_id: String, + connector_invoice_id: Option<id_type::InvoiceId>, connector_name: api_enums::Connector, ) -> Self { Self { @@ -67,7 +68,7 @@ impl InvoiceSyncTrackingData { merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, customer_id: id_type::CustomerId, - connector_invoice_id: String, + connector_invoice_id: Option<id_type::InvoiceId>, connector_name: api_enums::Connector, ) -> Self { Self { diff --git a/crates/router/src/workflows/invoice_sync.rs b/crates/router/src/workflows/invoice_sync.rs index d72e59904f1..72c3a11071c 100644 --- a/crates/router/src/workflows/invoice_sync.rs +++ b/crates/router/src/workflows/invoice_sync.rs @@ -162,11 +162,31 @@ impl<'a> InvoiceSyncHandler<'a> { Ok(payments_response) } + pub async fn perform_billing_processor_record_back_if_possible( + &self, + payment_response: subscription_types::PaymentResponseData, + payment_status: common_enums::AttemptStatus, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, + invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus, + ) -> CustomResult<(), router_errors::ApiErrorResponse> { + if let Some(connector_invoice_id) = connector_invoice_id { + Box::pin(self.perform_billing_processor_record_back( + payment_response, + payment_status, + connector_invoice_id, + invoice_sync_status, + )) + .await + .attach_printable("Failed to record back to billing processor")?; + } + Ok(()) + } + pub async fn perform_billing_processor_record_back( &self, payment_response: subscription_types::PaymentResponseData, payment_status: common_enums::AttemptStatus, - connector_invoice_id: String, + connector_invoice_id: common_utils::id_type::InvoiceId, invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus, ) -> CustomResult<(), router_errors::ApiErrorResponse> { logger::info!("perform_billing_processor_record_back"); @@ -175,7 +195,6 @@ impl<'a> InvoiceSyncHandler<'a> { self.state, &self.merchant_account, &self.key_store, - Some(self.customer.clone()), self.profile.clone(), ) .await @@ -185,6 +204,7 @@ impl<'a> InvoiceSyncHandler<'a> { self.subscription.clone(), self.merchant_account.clone(), self.profile.clone(), + self.key_store.clone(), ); // TODO: Handle retries here on failure @@ -220,20 +240,20 @@ impl<'a> InvoiceSyncHandler<'a> { &self, process: storage::ProcessTracker, payment_response: subscription_types::PaymentResponseData, - connector_invoice_id: String, + connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> CustomResult<(), router_errors::ApiErrorResponse> { let invoice_sync_status = storage::invoice_sync::InvoiceSyncPaymentStatus::from(payment_response.status); match invoice_sync_status { storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentSucceeded => { - Box::pin(self.perform_billing_processor_record_back( - payment_response, + Box::pin(self.perform_billing_processor_record_back_if_possible( + payment_response.clone(), common_enums::AttemptStatus::Charged, connector_invoice_id, - invoice_sync_status, + invoice_sync_status.clone(), )) .await - .attach_printable("Failed to record back to billing processor")?; + .attach_printable("Failed to record back success status to billing processor")?; self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT) .await @@ -256,14 +276,14 @@ impl<'a> InvoiceSyncHandler<'a> { .attach_printable("Failed to update process tracker status") } storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentFailed => { - Box::pin(self.perform_billing_processor_record_back( - payment_response, - common_enums::AttemptStatus::Failure, + Box::pin(self.perform_billing_processor_record_back_if_possible( + payment_response.clone(), + common_enums::AttemptStatus::Charged, connector_invoice_id, - invoice_sync_status, + invoice_sync_status.clone(), )) .await - .attach_printable("Failed to record back to billing processor")?; + .attach_printable("Failed to record back failure status to billing processor")?; self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT) .await diff --git a/crates/storage_impl/src/invoice.rs b/crates/storage_impl/src/invoice.rs index 95330239167..0a3a93d2b90 100644 --- a/crates/storage_impl/src/invoice.rs +++ b/crates/storage_impl/src/invoice.rs @@ -100,6 +100,27 @@ impl<T: DatabaseStore> InvoiceInterface for RouterStore<T> { subscription_id )))) } + + #[instrument(skip_all)] + async fn find_invoice_by_subscription_id_connector_invoice_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_id: String, + connector_invoice_id: common_utils::id_type::InvoiceId, + ) -> CustomResult<Option<DomainInvoice>, StorageError> { + let conn = connection::pg_connection_read(self).await?; + self.find_optional_resource( + state, + key_store, + Invoice::get_invoice_by_subscription_id_connector_invoice_id( + &conn, + subscription_id, + connector_invoice_id, + ), + ) + .await + } } #[async_trait::async_trait] @@ -154,6 +175,24 @@ impl<T: DatabaseStore> InvoiceInterface for KVRouterStore<T> { .get_latest_invoice_for_subscription(state, key_store, subscription_id) .await } + + #[instrument(skip_all)] + async fn find_invoice_by_subscription_id_connector_invoice_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_id: String, + connector_invoice_id: common_utils::id_type::InvoiceId, + ) -> CustomResult<Option<DomainInvoice>, StorageError> { + self.router_store + .find_invoice_by_subscription_id_connector_invoice_id( + state, + key_store, + subscription_id, + connector_invoice_id, + ) + .await + } } #[async_trait::async_trait] @@ -197,4 +236,14 @@ impl InvoiceInterface for MockDb { ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } + + async fn find_invoice_by_subscription_id_connector_invoice_id( + &self, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, + _subscription_id: String, + _connector_invoice_id: common_utils::id_type::InvoiceId, + ) -> CustomResult<Option<DomainInvoice>, StorageError> { + Err(StorageError::MockDbError)? + } } diff --git a/migrations/2025-10-09-171834_invoice_subscription_id_connector_invoice_id_unique_index/down.sql b/migrations/2025-10-09-171834_invoice_subscription_id_connector_invoice_id_unique_index/down.sql new file mode 100644 index 00000000000..9972bff1772 --- /dev/null +++ b/migrations/2025-10-09-171834_invoice_subscription_id_connector_invoice_id_unique_index/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE invoice DROP CONSTRAINT IF EXISTS invoice_subscription_id_connector_invoice_id_unique_index; +DROP INDEX IF EXISTS invoice_subscription_id_connector_invoice_id_unique_index; \ No newline at end of file diff --git a/migrations/2025-10-09-171834_invoice_subscription_id_connector_invoice_id_unique_index/up.sql b/migrations/2025-10-09-171834_invoice_subscription_id_connector_invoice_id_unique_index/up.sql new file mode 100644 index 00000000000..f455ec85e55 --- /dev/null +++ b/migrations/2025-10-09-171834_invoice_subscription_id_connector_invoice_id_unique_index/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE invoice ADD CONSTRAINT invoice_subscription_id_connector_invoice_id_unique_index UNIQUE (subscription_id, connector_invoice_id); \ No newline at end of file
2025-10-07T15:18:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> 1. Add support to create a subscription with trial plans. When this type of subscription is created, a payment of $0 will be made to validate the payment method and save it for future use. The incoming webhook for invoice-generated event should work similarly to the MIT flow. 2. Add support to make 3DS payments in subscriptions ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create Merchant Account, create API key, create payment processor, create billing processor 2. Create Customer Request ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_4IM0uzCEoKQ9lkSaTUEceuErgHTSnZhcc0CsjiSc1P2jVv5W4p9nYumBWwnJLqLb' \ --header 'X-Tenant-Id: public' \ --data-raw '{ "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } } }' ``` Response ``` { "customer_id": "cus_PqvEsNGKq1kLRdX7HTHJ", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-10-08T06:35:33.524Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null } ``` 3. Create and Confirm subscription Request ``` curl --location 'http://localhost:8080/subscriptions' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_BSjmSsJE4oqVfDdiJViI' \ --header 'api-key: dev_4IM0uzCEoKQ9lkSaTUEceuErgHTSnZhcc0CsjiSc1P2jVv5W4p9nYumBWwnJLqLb' \ --header 'X-Tenant-Id: public' \ --data '{ "item_price_id": "standard-plan-yearly", "customer_id": "cus_PqvEsNGKq1kLRdX7HTHJ", "description": "Hello this is description", "merchant_reference_id": "mer_ref_1759906164", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_type": "setup_mandate", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com", "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" } } } }' ``` Response ``` { "id": "sub_ZEqweuW4DlSc5BuM6zhW", "merchant_reference_id": "mer_ref_1759906160", "status": "trial", "plan_id": null, "price_id": null, "coupon": null, "profile_id": "pro_BSjmSsJE4oqVfDdiJViI", "payment": { "payment_id": "pay_1B9LjwEWwAfHb4bf0rcS", "status": "succeeded", "amount": 0, "currency": "USD", "connector": "stripe", "payment_method_id": "pm_kLqHMaoTQwDD5wRFj4mf", "payment_experience": null, "error_code": null, "error_message": null, "payment_method_type": "credit", "client_secret": "pay_1B9LjwEWwAfHb4bf0rcS_secret_a5IfTsNMNyh2hXHmmIEq", "payment_type": null }, "customer_id": "cus_PqvEsNGKq1kLRdX7HTHJ", "invoice": { "id": "invoice_gO4K4XTvSoBJygwXBmsf", "subscription_id": "sub_ZEqweuW4DlSc5BuM6zhW", "merchant_id": "merchant_1759818834", "profile_id": "pro_BSjmSsJE4oqVfDdiJViI", "merchant_connector_id": "mca_4C0kfzkr1veBQWDVKnUj", "payment_intent_id": "pay_1B9LjwEWwAfHb4bf0rcS", "payment_method_id": null, "customer_id": "cus_PqvEsNGKq1kLRdX7HTHJ", "amount": 0, "currency": "USD", "status": "invoice_created" }, "billing_processor_subscription_id": "sub_ZEqweuW4DlSc5BuM6zhW" } ``` <img width="1309" height="107" alt="Screenshot 2025-10-08 at 12 20 19 PM" src="https://github.com/user-attachments/assets/feaf1e79-3ed4-441c-8401-767b0a76ac00" /> Time travel to the next billing date, an invoice will be generated with payment due statue and webhook will be received <img width="847" height="200" alt="Screenshot 2025-10-08 at 12 22 26 PM" src="https://github.com/user-attachments/assets/e5fe8953-a3a2-4773-a83c-060bb7385b94" /> 4. Time travel to the next billing date and accept the incoming webhook for `invoice_generated` event, now the invoice should get marked as paid Request ``` curl --location 'http://localhost:8080/webhooks/merchant_1759818834/mca_4C0kfzkr1veBQWDVKnUj' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_BSjmSsJE4oqVfDdiJViI' \ --header 'api-key: dev_4IM0uzCEoKQ9lkSaTUEceuErgHTSnZhcc0CsjiSc1P2jVv5W4p9nYumBWwnJLqLb' \ --header 'X-tenant-id: public' \ --header 'Authorization: Basic aHlwZXJzd2l0Y2g6aHlwZXJzd2l0Y2g=' \ --data '{ "api_version": "v2", "content": { "invoice": { "adjustment_credit_notes": [], "amount_adjusted": 0, "amount_due": 12000, "amount_paid": 0, "amount_to_collect": 12000, "applied_credits": [], "base_currency_code": "INR", "billing_address": { "city": "San Fransico", "country": "US", "first_name": "joseph", "last_name": "Doe", "line1": "1467", "object": "billing_address", "state": "California", "state_code": "CA", "validation_status": "not_validated", "zip": "94122" }, "channel": "web", "credits_applied": 0, "currency_code": "USD", "customer_id": "cus_PqvEsNGKq1kLRdX7HTHJ", "date": 1745303361, "deleted": false, "due_date": 1745303361, "dunning_attempts": [], "exchange_rate": 0.011742719, "first_invoice": true, "generated_at": 1745303361, "has_advance_charges": false, "id": "8", "is_gifted": false, "issued_credit_notes": [], "line_items": [ { "amount": 12000, "customer_id": "cus_PqvEsNGKq1kLRdX7HTHJ", "date_from": 1745303361, "date_to": 1776839361, "description": "Standard Plan - Yearly", "discount_amount": 0, "entity_id": "standard-plan-yearly", "entity_type": "plan_item_price", "id": "li_169lH1Uz11LJr2CNi", "is_taxed": false, "item_level_discount_amount": 0, "object": "line_item", "pricing_model": "flat_fee", "quantity": 1, "subscription_id": "sub_ZEqweuW4DlSc5BuM6zhW", "tax_amount": 0, "tax_exempt_reason": "tax_not_configured", "unit_amount": 12000 } ], "linked_orders": [], "linked_payments": [], "net_term_days": 0, "new_sales_amount": 12000, "object": "invoice", "price_type": "tax_exclusive", "recurring": true, "reference_transactions": [], "resource_version": 1745303362952, "round_off_amount": 0, "site_details_at_creation": { "timezone": "Asia/Calcutta" }, "status": "payment_due", "sub_total": 12000, "subscription_id": "sub_ZEqweuW4DlSc5BuM6zhW", "tax": 0, "term_finalized": true, "total": 12000, "updated_at": 1745303362, "write_off_amount": 0 } }, "event_type": "invoice_generated", "id": "ev_169lH1Uz11LL82CNk", "object": "event", "occurred_at": 1745303363, "source": "scheduled_job", "webhook_status": "scheduled", "webhooks": [ { "id": "whv2_169wFTUz0zZE6S87", "object": "webhook", "webhook_status": "scheduled" } ] }' ``` Response ``` 200 OK ``` <img width="820" height="153" alt="Screenshot 2025-10-08 at 2 49 12 PM" src="https://github.com/user-attachments/assets/fc43b38d-03eb-4015-b8d0-0bbc4e07e2bf" /> 5. Create Customer and create subscription with auth_type: "three_ds" to create 3DS payment Request ``` curl --location 'http://localhost:8080/subscriptions' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_Z5PRkNfUsNYHHGgKDmSc' \ --header 'api-key: dev_TVnuWX7gAfpjrVv4Ex5OHjwTZ7lUKY5LNy8MQnvnSbj19ys5nbEDME4kejTBZ0tg' \ --header 'X-tenant-id: public' \ --data '{ "item_price_id": "standard-plan-USD-Monthly", "customer_id": "cus_Pp7MTQL9p1ovyoKB2QtS", "description": "Hello this is description", "merchant_reference_id": "mer_ref_1760016459", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_type": "setup_mandate", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "authentication_type": "three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com", "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" } } } }' ``` Response ``` { "id": "sub_XSgS745pisVSvcXEWxiE", "merchant_reference_id": "mer_ref_1760016450", "status": "active", "plan_id": null, "price_id": null, "coupon": null, "profile_id": "pro_Z5PRkNfUsNYHHGgKDmSc", "payment": { "payment_id": "pay_pwKrT9HW6vmSukp56Oo0", "status": "requires_customer_action", "amount": 1200, "currency": "USD", "profile_id": "pro_Z5PRkNfUsNYHHGgKDmSc", "connector": "stripe", "payment_method_id": "pm_2i4KXYKijSeX0u4PymkJ", "return_url": "https://google.com/", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_pwKrT9HW6vmSukp56Oo0/merchant_1760009370/pay_pwKrT9HW6vmSukp56Oo0_1" }, "payment_experience": null, "error_code": null, "error_message": null, "payment_method_type": "credit", "client_secret": "pay_pwKrT9HW6vmSukp56Oo0_secret_Z8ZehHMFc45D1KliHX0g", "payment_type": null }, "customer_id": "cus_Pp7MTQL9p1ovyoKB2QtS", "invoice": { "id": "invoice_iVKvCnVwg9aotKN2tcwn", "subscription_id": "sub_XSgS745pisVSvcXEWxiE", "merchant_id": "merchant_1760009370", "profile_id": "pro_Z5PRkNfUsNYHHGgKDmSc", "merchant_connector_id": "mca_hbJ2wahF6dp7ACUW72eO", "payment_intent_id": "pay_pwKrT9HW6vmSukp56Oo0", "payment_method_id": null, "customer_id": "cus_Pp7MTQL9p1ovyoKB2QtS", "amount": 1200, "currency": "USD", "status": "payment_pending" }, "billing_processor_subscription_id": "sub_XSgS745pisVSvcXEWxiE" } ``` <img width="1195" height="542" alt="Screenshot 2025-10-09 at 6 59 39 PM" src="https://github.com/user-attachments/assets/24457ec6-f816-4956-8d88-b59302f9e654" /> Created Unique index on subscription_id_connector_invoice_id in invoice table to avoid multiple MIT payments ``` ➜ ~ seq 1 4 | xargs -n1 -P5 curl -w "\nStatus: %{http_code}\n" --location 'http://localhost.proxyman.io:8080/webhooks/merchant_1760030871/mca_Qxsaj3wPHpCw2BfVLfcp' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_fRxGSwMSfrfb19ttnUJt' \ --header 'api-key: dev_oioLdMN4eQuEHr6e9H3WWllhWgJMwkhYhZgiEP2nc2whZ7tPtC8xx4pCHKt3d8C7' \ --header 'X-tenant-id: public' \ --header 'Authorization: Basic aHlwZXJzd2l0Y2g6aHlwZXJzd2l0Y2g=' \ --data '{"api_version":"v2","content":{"invoice":{"adjustment_credit_notes":[],"amount_adjusted":0,"amount_due":12000,"amount_paid":0,"amount_to_collect":12000,"applied_credits":[],"base_currency_code":"INR","billing_address":{"city":"San Fransico","country":"US","first_name":"joseph","last_name":"Doe","line1":"1467","object":"billing_address","state":"California","state_code":"CA","validation_status":"not_validated","zip":"94122"},"channel":"web","credits_applied":0,"currency_code":"USD","customer_id":"cus_4dPaSdR6AvhvVRGsw2j3","date":1745428099,"deleted":false,"due_date":1745428099,"dunning_attempts":[],"exchange_rate":0.011732607,"first_invoice":true,"generated_at":1745428099,"has_advance_charges":false,"id":"30","is_gifted":false,"issued_credit_notes":[],"line_items":[{"amount":12000,"customer_id":"cus_4dPaSdR6AvhvVRGsw2j3","date_from":1745428099,"date_to":1776964099,"description":"Standard Plan - Yearly","discount_amount":0,"entity_id":"standard-plan-yearly","entity_type":"plan_item_price","id":"li_AzZtuxUz9SYOs8pX8","is_taxed":false,"item_level_discount_amount":0,"object":"line_item","pricing_model":"flat_fee","quantity":1,"subscription_id":"sub_Q1awfb6GdSXDf3QXcmQr","tax_amount":0,"tax_exempt_reason":"tax_not_configured","unit_amount":12000}],"linked_orders":[],"linked_payments":[],"net_term_days":0,"new_sales_amount":12000,"object":"invoice","price_type":"tax_exclusive","recurring":true,"reference_transactions":[],"resource_version":1745428100772,"round_off_amount":0,"site_details_at_creation":{"timezone":"Asia/Calcutta"},"status":"payment_due","sub_total":12000,"subscription_id":"sub_Q1awfb6GdSXDf3QXcmQr","tax":0,"term_finalized":true,"total":12000,"updated_at":1745428100,"write_off_amount":0}},"event_type":"invoice_generated","id":"ev_AzZtuxUz9SYQ08pXA","object":"event","occurred_at":1745428100,"source":"scheduled_job","webhook_status":"scheduled","webhooks":[{"id":"whv2_169wFTUz0zZE6S87","object":"webhook","webhook_status":"scheduled"}]}' {"error":{"type":"invalid_request","message":"Subscription operation: Create Invoice failed with connector","code":"CE_09"}}{"error":{"type":"invalid_request","message":"Subscription operation: Create Invoice failed with connector","code":"CE_09"}}{"error":{"type":"invalid_request","message":"Subscription operation: Create Invoice failed with connector","code":"CE_09"}} Status: 400 Status: 400 Status: 400 curl: (7) Failed to connect to 0.0.0.1 port 80 after 0 ms: Couldn't connect to server Status: 000 curl: (7) Failed to connect to 0.0.0.3 port 80 after 0 ms: Couldn't connect to server Status: 000 curl: (7) Failed to connect to 0.0.0.4 port 80 after 0 ms: Couldn't connect to server Status: 000 Status: 200 curl: (7) Failed to connect to 0.0.0.2 port 80 after 0 ms: Couldn't connect to server Status: 000 ``` Here there is only one 200 and rest of the parallel request are 400 ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f71090a94c55c421ffffd1d7608c33bac24a84e4
juspay/hyperswitch
juspay__hyperswitch-9703
Bug: feat(subscription): domain_model for subscription and invoice
diff --git a/crates/hyperswitch_domain_models/src/invoice.rs b/crates/hyperswitch_domain_models/src/invoice.rs new file mode 100644 index 00000000000..9457eac56d2 --- /dev/null +++ b/crates/hyperswitch_domain_models/src/invoice.rs @@ -0,0 +1,250 @@ +use std::str::FromStr; + +use common_utils::{ + errors::{CustomResult, ValidationError}, + id_type::GenerateId, + pii::SecretSerdeValue, + types::{ + keymanager::{Identifier, KeyManagerState}, + MinorUnit, + }, +}; +use error_stack::ResultExt; +use masking::Secret; +use utoipa::ToSchema; + +use crate::merchant_key_store::MerchantKeyStore; + +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct Invoice { + pub id: common_utils::id_type::InvoiceId, + pub subscription_id: common_utils::id_type::SubscriptionId, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_id: common_utils::id_type::ProfileId, + pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + pub payment_intent_id: Option<common_utils::id_type::PaymentId>, + pub payment_method_id: Option<String>, + pub customer_id: common_utils::id_type::CustomerId, + pub amount: MinorUnit, + pub currency: String, + pub status: String, + pub provider_name: common_enums::connector_enums::Connector, + pub metadata: Option<SecretSerdeValue>, + pub connector_invoice_id: Option<String>, +} + +#[async_trait::async_trait] + +impl super::behaviour::Conversion for Invoice { + type DstType = diesel_models::invoice::Invoice; + type NewDstType = diesel_models::invoice::InvoiceNew; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + let now = common_utils::date_time::now(); + Ok(diesel_models::invoice::Invoice { + id: self.id, + subscription_id: self.subscription_id, + merchant_id: self.merchant_id, + profile_id: self.profile_id, + merchant_connector_id: self.merchant_connector_id, + payment_intent_id: self.payment_intent_id, + payment_method_id: self.payment_method_id, + customer_id: self.customer_id, + amount: self.amount, + currency: self.currency.to_string(), + status: self.status, + provider_name: self.provider_name, + metadata: None, + created_at: now, + modified_at: now, + connector_invoice_id: self.connector_invoice_id, + }) + } + + async fn convert_back( + _state: &KeyManagerState, + item: Self::DstType, + _key: &Secret<Vec<u8>>, + _key_manager_identifier: Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + Ok(Self { + id: item.id, + subscription_id: item.subscription_id, + merchant_id: item.merchant_id, + profile_id: item.profile_id, + merchant_connector_id: item.merchant_connector_id, + payment_intent_id: item.payment_intent_id, + payment_method_id: item.payment_method_id, + customer_id: item.customer_id, + amount: item.amount, + currency: item.currency, + status: item.status, + provider_name: item.provider_name, + metadata: item.metadata, + connector_invoice_id: item.connector_invoice_id, + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + let invoice_status = common_enums::connector_enums::InvoiceStatus::from_str(&self.status) + .change_context(ValidationError::InvalidValue { + message: "Invalid invoice status".to_string(), + })?; + + Ok(diesel_models::invoice::InvoiceNew::new( + self.subscription_id, + self.merchant_id, + self.profile_id, + self.merchant_connector_id, + self.payment_intent_id, + self.payment_method_id, + self.customer_id, + self.amount, + self.currency.to_string(), + invoice_status, + self.provider_name, + None, + self.connector_invoice_id, + )) + } +} + +impl Invoice { + #[allow(clippy::too_many_arguments)] + pub fn to_invoice( + subscription_id: common_utils::id_type::SubscriptionId, + merchant_id: common_utils::id_type::MerchantId, + profile_id: common_utils::id_type::ProfileId, + merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + payment_intent_id: Option<common_utils::id_type::PaymentId>, + payment_method_id: Option<String>, + customer_id: common_utils::id_type::CustomerId, + amount: MinorUnit, + currency: String, + status: common_enums::connector_enums::InvoiceStatus, + provider_name: common_enums::connector_enums::Connector, + metadata: Option<SecretSerdeValue>, + connector_invoice_id: Option<String>, + ) -> Self { + Self { + id: common_utils::id_type::InvoiceId::generate(), + subscription_id, + merchant_id, + profile_id, + merchant_connector_id, + payment_intent_id, + payment_method_id, + customer_id, + amount, + currency: currency.to_string(), + status: status.to_string(), + provider_name, + metadata, + connector_invoice_id, + } + } +} + +#[async_trait::async_trait] +pub trait InvoiceInterface { + type Error; + async fn insert_invoice_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_new: Invoice, + ) -> CustomResult<Invoice, Self::Error>; + + async fn find_invoice_by_invoice_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_id: String, + ) -> CustomResult<Invoice, Self::Error>; + + async fn update_invoice_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_id: String, + data: InvoiceUpdate, + ) -> CustomResult<Invoice, Self::Error>; + + async fn get_latest_invoice_for_subscription( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_id: String, + ) -> CustomResult<Invoice, Self::Error>; +} + +pub struct InvoiceUpdate { + pub status: Option<String>, + pub payment_method_id: Option<String>, + pub connector_invoice_id: Option<String>, + pub modified_at: time::PrimitiveDateTime, + pub payment_intent_id: Option<common_utils::id_type::PaymentId>, +} +#[async_trait::async_trait] +impl super::behaviour::Conversion for InvoiceUpdate { + type DstType = diesel_models::invoice::InvoiceUpdate; + type NewDstType = diesel_models::invoice::InvoiceUpdate; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(diesel_models::invoice::InvoiceUpdate { + status: self.status, + payment_method_id: self.payment_method_id, + connector_invoice_id: self.connector_invoice_id, + modified_at: self.modified_at, + payment_intent_id: self.payment_intent_id, + }) + } + + async fn convert_back( + _state: &KeyManagerState, + item: Self::DstType, + _key: &Secret<Vec<u8>>, + _key_manager_identifier: Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + Ok(Self { + status: item.status, + payment_method_id: item.payment_method_id, + connector_invoice_id: item.connector_invoice_id, + modified_at: item.modified_at, + payment_intent_id: item.payment_intent_id, + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(diesel_models::invoice::InvoiceUpdate { + status: self.status, + payment_method_id: self.payment_method_id, + connector_invoice_id: self.connector_invoice_id, + modified_at: self.modified_at, + payment_intent_id: self.payment_intent_id, + }) + } +} + +impl InvoiceUpdate { + pub fn new( + payment_method_id: Option<String>, + status: Option<common_enums::connector_enums::InvoiceStatus>, + connector_invoice_id: Option<String>, + payment_intent_id: Option<common_utils::id_type::PaymentId>, + ) -> Self { + Self { + payment_method_id, + status: status.map(|status| status.to_string()), + connector_invoice_id, + modified_at: common_utils::date_time::now(), + payment_intent_id, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 3ed5130e077..1a3da30c975 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -15,6 +15,7 @@ pub mod disputes; pub mod errors; pub mod ext_traits; pub mod gsm; +pub mod invoice; pub mod mandates; pub mod merchant_account; pub mod merchant_connector_account; diff --git a/crates/hyperswitch_domain_models/src/subscription.rs b/crates/hyperswitch_domain_models/src/subscription.rs index af2390de3f8..86db04ddc5c 100644 --- a/crates/hyperswitch_domain_models/src/subscription.rs +++ b/crates/hyperswitch_domain_models/src/subscription.rs @@ -1,7 +1,15 @@ -use common_utils::events::ApiEventMetric; +use common_utils::{ + errors::{CustomResult, ValidationError}, + events::ApiEventMetric, + generate_id_with_default_len, + pii::SecretSerdeValue, + types::keymanager::{self, KeyManagerState}, +}; use error_stack::ResultExt; +use masking::{ExposeInterface, PeekInterface, Secret}; +use time::PrimitiveDateTime; -use crate::errors::api_error_response::ApiErrorResponse; +use crate::{errors::api_error_response::ApiErrorResponse, merchant_key_store::MerchantKeyStore}; const SECRET_SPLIT: &str = "_secret"; @@ -48,3 +56,222 @@ impl From<ClientSecret> for api_models::subscription::ClientSecret { Self::new(domain_secret.to_string()) } } + +#[derive(Clone, Debug, serde::Serialize)] +pub struct Subscription { + pub id: common_utils::id_type::SubscriptionId, + pub status: String, + pub billing_processor: Option<String>, + pub payment_method_id: Option<String>, + pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub client_secret: Option<String>, + pub connector_subscription_id: Option<String>, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::CustomerId, + pub metadata: Option<SecretSerdeValue>, + pub created_at: PrimitiveDateTime, + pub modified_at: PrimitiveDateTime, + pub profile_id: common_utils::id_type::ProfileId, + pub merchant_reference_id: Option<String>, +} + +#[derive(Debug, Clone, serde::Serialize)] +pub enum SubscriptionStatus { + Active, + Created, + InActive, + Pending, + Trial, + Paused, + Unpaid, + Onetime, + Cancelled, + Failed, +} + +impl std::fmt::Display for SubscriptionStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Active => write!(f, "Active"), + Self::Created => write!(f, "Created"), + Self::InActive => write!(f, "InActive"), + Self::Pending => write!(f, "Pending"), + Self::Trial => write!(f, "Trial"), + Self::Paused => write!(f, "Paused"), + Self::Unpaid => write!(f, "Unpaid"), + Self::Onetime => write!(f, "Onetime"), + Self::Cancelled => write!(f, "Cancelled"), + Self::Failed => write!(f, "Failed"), + } + } +} + +impl Subscription { + pub fn generate_and_set_client_secret(&mut self) -> Secret<String> { + let client_secret = + generate_id_with_default_len(&format!("{}_secret", self.id.get_string_repr())); + self.client_secret = Some(client_secret.clone()); + Secret::new(client_secret) + } +} + +#[async_trait::async_trait] +impl super::behaviour::Conversion for Subscription { + type DstType = diesel_models::subscription::Subscription; + type NewDstType = diesel_models::subscription::SubscriptionNew; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + let now = common_utils::date_time::now(); + Ok(diesel_models::subscription::Subscription { + id: self.id, + status: self.status, + billing_processor: self.billing_processor, + payment_method_id: self.payment_method_id, + merchant_connector_id: self.merchant_connector_id, + client_secret: self.client_secret, + connector_subscription_id: self.connector_subscription_id, + merchant_id: self.merchant_id, + customer_id: self.customer_id, + metadata: self.metadata.map(|m| m.expose()), + created_at: now, + modified_at: now, + profile_id: self.profile_id, + merchant_reference_id: self.merchant_reference_id, + }) + } + + async fn convert_back( + _state: &KeyManagerState, + item: Self::DstType, + _key: &Secret<Vec<u8>>, + _key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + Ok(Self { + id: item.id, + status: item.status, + billing_processor: item.billing_processor, + payment_method_id: item.payment_method_id, + merchant_connector_id: item.merchant_connector_id, + client_secret: item.client_secret, + connector_subscription_id: item.connector_subscription_id, + merchant_id: item.merchant_id, + customer_id: item.customer_id, + metadata: item.metadata.map(SecretSerdeValue::new), + created_at: item.created_at, + modified_at: item.modified_at, + profile_id: item.profile_id, + merchant_reference_id: item.merchant_reference_id, + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(diesel_models::subscription::SubscriptionNew::new( + self.id, + self.status, + self.billing_processor, + self.payment_method_id, + self.merchant_connector_id, + self.client_secret, + self.connector_subscription_id, + self.merchant_id, + self.customer_id, + self.metadata, + self.profile_id, + self.merchant_reference_id, + )) + } +} + +#[async_trait::async_trait] +pub trait SubscriptionInterface { + type Error; + async fn insert_subscription_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_new: Subscription, + ) -> CustomResult<Subscription, Self::Error>; + + async fn find_by_merchant_id_subscription_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + ) -> CustomResult<Subscription, Self::Error>; + + async fn update_subscription_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + data: SubscriptionUpdate, + ) -> CustomResult<Subscription, Self::Error>; +} + +pub struct SubscriptionUpdate { + pub connector_subscription_id: Option<String>, + pub payment_method_id: Option<String>, + pub status: Option<String>, + pub modified_at: PrimitiveDateTime, +} + +impl SubscriptionUpdate { + pub fn new( + payment_method_id: Option<Secret<String>>, + status: Option<String>, + connector_subscription_id: Option<String>, + ) -> Self { + Self { + payment_method_id: payment_method_id.map(|pmid| pmid.peek().clone()), + status, + connector_subscription_id, + modified_at: common_utils::date_time::now(), + } + } +} + +#[async_trait::async_trait] +impl super::behaviour::Conversion for SubscriptionUpdate { + type DstType = diesel_models::subscription::SubscriptionUpdate; + type NewDstType = diesel_models::subscription::SubscriptionUpdate; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(diesel_models::subscription::SubscriptionUpdate { + connector_subscription_id: self.connector_subscription_id, + payment_method_id: self.payment_method_id, + status: self.status, + modified_at: self.modified_at, + }) + } + + async fn convert_back( + _state: &KeyManagerState, + item: Self::DstType, + _key: &Secret<Vec<u8>>, + _key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + Ok(Self { + connector_subscription_id: item.connector_subscription_id, + payment_method_id: item.payment_method_id, + status: item.status, + modified_at: item.modified_at, + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(diesel_models::subscription::SubscriptionUpdate { + connector_subscription_id: self.connector_subscription_id, + payment_method_id: self.payment_method_id, + status: self.status, + modified_at: self.modified_at, + }) + } +} diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 636b960fed6..05254a9b77d 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -81,11 +81,13 @@ pub async fn create_subscription( .attach_printable("subscriptions: failed to create invoice")?; subscription - .update_subscription(diesel_models::subscription::SubscriptionUpdate::new( - payment.payment_method_id.clone(), - None, - None, - )) + .update_subscription( + hyperswitch_domain_models::subscription::SubscriptionUpdate::new( + payment.payment_method_id.clone(), + None, + None, + ), + ) .await .attach_printable("subscriptions: failed to update subscription")?; @@ -146,7 +148,6 @@ pub async fn get_subscription_plans( } Ok(ApplicationResponse::Json(response)) } - /// Creates and confirms a subscription in one operation. pub async fn create_and_confirm_subscription( state: SessionState, @@ -253,16 +254,18 @@ pub async fn create_and_confirm_subscription( .await?; subs_handler - .update_subscription(diesel_models::subscription::SubscriptionUpdate::new( - payment_response.payment_method_id.clone(), - Some(SubscriptionStatus::from(subscription_create_response.status).to_string()), - Some( - subscription_create_response - .subscription_id - .get_string_repr() - .to_string(), + .update_subscription( + hyperswitch_domain_models::subscription::SubscriptionUpdate::new( + payment_response.payment_method_id.clone(), + Some(SubscriptionStatus::from(subscription_create_response.status).to_string()), + Some( + subscription_create_response + .subscription_id + .get_string_repr() + .to_string(), + ), ), - )) + ) .await?; let response = subs_handler.generate_response( @@ -386,16 +389,18 @@ pub async fn confirm_subscription( .await?; subscription_entry - .update_subscription(diesel_models::subscription::SubscriptionUpdate::new( - payment_response.payment_method_id.clone(), - Some(SubscriptionStatus::from(subscription_create_response.status).to_string()), - Some( - subscription_create_response - .subscription_id - .get_string_repr() - .to_string(), + .update_subscription( + hyperswitch_domain_models::subscription::SubscriptionUpdate::new( + payment_response.payment_method_id.clone(), + Some(SubscriptionStatus::from(subscription_create_response.status).to_string()), + Some( + subscription_create_response + .subscription_id + .get_string_repr() + .to_string(), + ), ), - )) + ) .await?; let response = subscription_entry.generate_response( diff --git a/crates/router/src/core/subscription/billing_processor_handler.rs b/crates/router/src/core/subscription/billing_processor_handler.rs index aa361ef8ce9..910596d66c4 100644 --- a/crates/router/src/core/subscription/billing_processor_handler.rs +++ b/crates/router/src/core/subscription/billing_processor_handler.rs @@ -176,7 +176,7 @@ impl BillingHandler { pub async fn create_subscription_on_connector( &self, state: &SessionState, - subscription: diesel_models::subscription::Subscription, + subscription: hyperswitch_domain_models::subscription::Subscription, item_price_id: Option<String>, billing_address: Option<api_models::payments::Address>, ) -> errors::RouterResult<subscription_response_types::SubscriptionCreateResponse> { diff --git a/crates/router/src/core/subscription/invoice_handler.rs b/crates/router/src/core/subscription/invoice_handler.rs index b7d5cb328fd..b383f7a4650 100644 --- a/crates/router/src/core/subscription/invoice_handler.rs +++ b/crates/router/src/core/subscription/invoice_handler.rs @@ -10,12 +10,14 @@ use masking::{PeekInterface, Secret}; use super::errors; use crate::{ - core::subscription::payments_api_client, routes::SessionState, types::storage as storage_types, + core::{errors::utils::StorageErrorExt, subscription::payments_api_client}, + routes::SessionState, + types::storage as storage_types, workflows::invoice_sync as invoice_sync_workflow, }; pub struct InvoiceHandler { - pub subscription: diesel_models::subscription::Subscription, + pub subscription: hyperswitch_domain_models::subscription::Subscription, pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, pub profile: hyperswitch_domain_models::business_profile::Profile, } @@ -23,7 +25,7 @@ pub struct InvoiceHandler { #[allow(clippy::todo)] impl InvoiceHandler { pub fn new( - subscription: diesel_models::subscription::Subscription, + subscription: hyperswitch_domain_models::subscription::Subscription, merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, profile: hyperswitch_domain_models::business_profile::Profile, ) -> Self { @@ -45,8 +47,8 @@ impl InvoiceHandler { provider_name: connector_enums::Connector, metadata: Option<pii::SecretSerdeValue>, connector_invoice_id: Option<String>, - ) -> errors::RouterResult<diesel_models::invoice::Invoice> { - let invoice_new = diesel_models::invoice::InvoiceNew::new( + ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> { + let invoice_new = hyperswitch_domain_models::invoice::Invoice::to_invoice( self.subscription.id.to_owned(), self.subscription.merchant_id.to_owned(), self.subscription.profile_id.to_owned(), @@ -62,9 +64,19 @@ impl InvoiceHandler { connector_invoice_id, ); + let key_manager_state = &(state).into(); + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + self.merchant_account.get_id(), + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let invoice = state .store - .insert_invoice_entry(invoice_new) + .insert_invoice_entry(key_manager_state, &merchant_key_store, invoice_new) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Create Invoice".to_string(), @@ -82,16 +94,31 @@ impl InvoiceHandler { payment_intent_id: Option<common_utils::id_type::PaymentId>, status: connector_enums::InvoiceStatus, connector_invoice_id: Option<String>, - ) -> errors::RouterResult<diesel_models::invoice::Invoice> { - let update_invoice = diesel_models::invoice::InvoiceUpdate::new( + ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> { + let update_invoice = hyperswitch_domain_models::invoice::InvoiceUpdate::new( payment_method_id.as_ref().map(|id| id.peek()).cloned(), Some(status), connector_invoice_id, payment_intent_id, ); + let key_manager_state = &(state).into(); + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + self.merchant_account.get_id(), + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; state .store - .update_invoice_entry(invoice_id.get_string_repr().to_string(), update_invoice) + .update_invoice_entry( + key_manager_state, + &merchant_key_store, + invoice_id.get_string_repr().to_string(), + update_invoice, + ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Invoice Update".to_string(), @@ -213,10 +240,24 @@ impl InvoiceHandler { pub async fn get_latest_invoice( &self, state: &SessionState, - ) -> errors::RouterResult<diesel_models::invoice::Invoice> { + ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> { + let key_manager_state = &(state).into(); + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + self.merchant_account.get_id(), + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; state .store - .get_latest_invoice_for_subscription(self.subscription.id.get_string_repr().to_string()) + .get_latest_invoice_for_subscription( + key_manager_state, + &merchant_key_store, + self.subscription.id.get_string_repr().to_string(), + ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Get Latest Invoice".to_string(), @@ -228,10 +269,24 @@ impl InvoiceHandler { &self, state: &SessionState, invoice_id: common_utils::id_type::InvoiceId, - ) -> errors::RouterResult<diesel_models::invoice::Invoice> { + ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> { + let key_manager_state = &(state).into(); + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + self.merchant_account.get_id(), + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; state .store - .find_invoice_by_invoice_id(invoice_id.get_string_repr().to_string()) + .find_invoice_by_invoice_id( + key_manager_state, + &merchant_key_store, + invoice_id.get_string_repr().to_string(), + ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Get Invoice by ID".to_string(), @@ -242,7 +297,7 @@ impl InvoiceHandler { pub async fn create_invoice_sync_job( &self, state: &SessionState, - invoice: &diesel_models::invoice::Invoice, + invoice: &hyperswitch_domain_models::invoice::Invoice, connector_invoice_id: String, connector_name: connector_enums::Connector, ) -> errors::RouterResult<()> { diff --git a/crates/router/src/core/subscription/subscription_handler.rs b/crates/router/src/core/subscription/subscription_handler.rs index b608faca5d5..76799c21a74 100644 --- a/crates/router/src/core/subscription/subscription_handler.rs +++ b/crates/router/src/core/subscription/subscription_handler.rs @@ -2,15 +2,15 @@ use std::str::FromStr; use api_models::{ enums as api_enums, - subscription::{self as subscription_types, SubscriptionResponse, SubscriptionStatus}, + subscription::{self as subscription_types, SubscriptionResponse}, }; use common_enums::connector_enums; use common_utils::{consts, ext_traits::OptionExt}; -use diesel_models::subscription::SubscriptionNew; use error_stack::ResultExt; use hyperswitch_domain_models::{ merchant_context::MerchantContext, router_response_types::subscriptions as subscription_response_types, + subscription::{Subscription, SubscriptionStatus}, }; use masking::Secret; @@ -48,28 +48,33 @@ impl<'a> SubscriptionHandler<'a> { let store = self.state.store.clone(); let db = store.as_ref(); - let mut subscription = SubscriptionNew::new( - subscription_id, - SubscriptionStatus::Created.to_string(), - Some(billing_processor.to_string()), - None, - Some(merchant_connector_id), - None, - None, - self.merchant_context + let mut subscription = Subscription { + id: subscription_id, + status: SubscriptionStatus::Created.to_string(), + billing_processor: Some(billing_processor.to_string()), + payment_method_id: None, + merchant_connector_id: Some(merchant_connector_id), + client_secret: None, + connector_subscription_id: None, + merchant_id: self + .merchant_context .get_merchant_account() .get_id() .clone(), - customer_id.clone(), - None, - profile.get_id().clone(), + customer_id: customer_id.clone(), + metadata: None, + profile_id: profile.get_id().clone(), merchant_reference_id, - ); + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + }; subscription.generate_and_set_client_secret(); + let key_manager_state = &(self.state).into(); + let merchant_key_store = self.merchant_context.get_merchant_key_store(); let new_subscription = db - .insert_subscription_entry(subscription) + .insert_subscription_entry(key_manager_state, merchant_key_store, subscription) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("subscriptions: unable to insert subscription entry to database")?; @@ -129,10 +134,15 @@ impl<'a> SubscriptionHandler<'a> { ) -> errors::RouterResult<()> { let subscription_id = client_secret.get_subscription_id()?; + let key_manager_state = &(self.state).into(); + let key_store = self.merchant_context.get_merchant_key_store(); + let subscription = self .state .store .find_by_merchant_id_subscription_id( + key_manager_state, + key_store, self.merchant_context.get_merchant_account().get_id(), subscription_id.to_string(), ) @@ -150,7 +160,7 @@ impl<'a> SubscriptionHandler<'a> { pub fn validate_client_secret( &self, client_secret: &hyperswitch_domain_models::subscription::ClientSecret, - subscription: &diesel_models::subscription::Subscription, + subscription: &Subscription, ) -> errors::RouterResult<()> { let stored_client_secret = subscription .client_secret @@ -185,6 +195,8 @@ impl<'a> SubscriptionHandler<'a> { .state .store .find_by_merchant_id_subscription_id( + &(self.state).into(), + self.merchant_context.get_merchant_key_store(), self.merchant_context.get_merchant_account().get_id(), subscription_id.get_string_repr().to_string().clone(), ) @@ -205,21 +217,21 @@ impl<'a> SubscriptionHandler<'a> { } pub struct SubscriptionWithHandler<'a> { pub handler: &'a SubscriptionHandler<'a>, - pub subscription: diesel_models::subscription::Subscription, + pub subscription: Subscription, pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, } impl SubscriptionWithHandler<'_> { pub fn generate_response( &self, - invoice: &diesel_models::invoice::Invoice, + invoice: &hyperswitch_domain_models::invoice::Invoice, payment_response: &subscription_types::PaymentResponseData, status: subscription_response_types::SubscriptionStatus, ) -> errors::RouterResult<subscription_types::ConfirmSubscriptionResponse> { Ok(subscription_types::ConfirmSubscriptionResponse { id: self.subscription.id.clone(), merchant_reference_id: self.subscription.merchant_reference_id.clone(), - status: SubscriptionStatus::from(status), + status: subscription_types::SubscriptionStatus::from(status), plan_id: None, profile_id: self.subscription.profile_id.to_owned(), payment: Some(payment_response.clone()), @@ -234,13 +246,13 @@ impl SubscriptionWithHandler<'_> { pub fn to_subscription_response( &self, payment: Option<subscription_types::PaymentResponseData>, - invoice: Option<&diesel_models::invoice::Invoice>, + invoice: Option<&hyperswitch_domain_models::invoice::Invoice>, ) -> errors::RouterResult<SubscriptionResponse> { Ok(SubscriptionResponse::new( self.subscription.id.clone(), self.subscription.merchant_reference_id.clone(), - SubscriptionStatus::from_str(&self.subscription.status) - .unwrap_or(SubscriptionStatus::Created), + subscription_types::SubscriptionStatus::from_str(&self.subscription.status) + .unwrap_or(subscription_types::SubscriptionStatus::Created), None, self.subscription.profile_id.to_owned(), self.subscription.merchant_id.to_owned(), @@ -259,11 +271,13 @@ impl SubscriptionWithHandler<'_> { pub async fn update_subscription( &mut self, - subscription_update: diesel_models::subscription::SubscriptionUpdate, + subscription_update: hyperswitch_domain_models::subscription::SubscriptionUpdate, ) -> errors::RouterResult<()> { let db = self.handler.state.store.as_ref(); let updated_subscription = db .update_subscription_entry( + &(self.handler.state).into(), + self.handler.merchant_context.get_merchant_key_store(), self.handler .merchant_context .get_merchant_account() @@ -363,10 +377,12 @@ impl SubscriptionWithHandler<'_> { } } -impl ForeignTryFrom<&diesel_models::invoice::Invoice> for subscription_types::Invoice { +impl ForeignTryFrom<&hyperswitch_domain_models::invoice::Invoice> for subscription_types::Invoice { type Error = error_stack::Report<errors::ApiErrorResponse>; - fn foreign_try_from(invoice: &diesel_models::invoice::Invoice) -> Result<Self, Self::Error> { + fn foreign_try_from( + invoice: &hyperswitch_domain_models::invoice::Invoice, + ) -> Result<Self, Self::Error> { Ok(Self { id: invoice.id.clone(), subscription_id: invoice.subscription_id.clone(), diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 2cead7d0509..4aef4efd3e1 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -21,7 +21,6 @@ pub mod generic_link; pub mod gsm; pub mod health_check; pub mod hyperswitch_ai_interaction; -pub mod invoice; pub mod kafka_store; pub mod locker_mock_up; pub mod mandate; @@ -36,7 +35,6 @@ pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; -pub mod subscription; pub mod unified_translations; pub mod user; pub mod user_authentication_method; @@ -147,8 +145,8 @@ pub trait StorageInterface: + payment_method_session::PaymentMethodsSessionInterface + tokenization::TokenizationInterface + callback_mapper::CallbackMapperInterface - + subscription::SubscriptionInterface - + invoice::InvoiceInterface + + storage_impl::subscription::SubscriptionInterface<Error = StorageError> + + storage_impl::invoice::InvoiceInterface<Error = StorageError> + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/invoice.rs b/crates/router/src/db/invoice.rs deleted file mode 100644 index b12a806840f..00000000000 --- a/crates/router/src/db/invoice.rs +++ /dev/null @@ -1,169 +0,0 @@ -use error_stack::report; -use router_env::{instrument, tracing}; -use storage_impl::MockDb; - -use super::Store; -use crate::{ - connection, - core::errors::{self, CustomResult}, - db::kafka_store::KafkaStore, - types::storage, -}; - -#[async_trait::async_trait] -pub trait InvoiceInterface { - async fn insert_invoice_entry( - &self, - invoice_new: storage::invoice::InvoiceNew, - ) -> CustomResult<storage::Invoice, errors::StorageError>; - - async fn find_invoice_by_invoice_id( - &self, - invoice_id: String, - ) -> CustomResult<storage::Invoice, errors::StorageError>; - - async fn update_invoice_entry( - &self, - invoice_id: String, - data: storage::invoice::InvoiceUpdate, - ) -> CustomResult<storage::Invoice, errors::StorageError>; - - async fn get_latest_invoice_for_subscription( - &self, - subscription_id: String, - ) -> CustomResult<storage::Invoice, errors::StorageError>; -} - -#[async_trait::async_trait] -impl InvoiceInterface for Store { - #[instrument(skip_all)] - async fn insert_invoice_entry( - &self, - invoice_new: storage::invoice::InvoiceNew, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - invoice_new - .insert(&conn) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - #[instrument(skip_all)] - async fn find_invoice_by_invoice_id( - &self, - invoice_id: String, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; - storage::Invoice::find_invoice_by_id_invoice_id(&conn, invoice_id) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - #[instrument(skip_all)] - async fn update_invoice_entry( - &self, - invoice_id: String, - data: storage::invoice::InvoiceUpdate, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::Invoice::update_invoice_entry(&conn, invoice_id, data) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - #[instrument(skip_all)] - async fn get_latest_invoice_for_subscription( - &self, - subscription_id: String, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::Invoice::list_invoices_by_subscription_id( - &conn, - subscription_id.clone(), - Some(1), - None, - false, - ) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - .map(|e| e.last().cloned())? - .ok_or(report!(errors::StorageError::ValueNotFound(format!( - "Invoice not found for subscription_id: {}", - subscription_id - )))) - } -} - -#[async_trait::async_trait] -impl InvoiceInterface for MockDb { - #[instrument(skip_all)] - async fn insert_invoice_entry( - &self, - _invoice_new: storage::invoice::InvoiceNew, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } - - async fn find_invoice_by_invoice_id( - &self, - _invoice_id: String, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } - - async fn update_invoice_entry( - &self, - _invoice_id: String, - _data: storage::invoice::InvoiceUpdate, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } - - async fn get_latest_invoice_for_subscription( - &self, - _subscription_id: String, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } -} - -#[async_trait::async_trait] -impl InvoiceInterface for KafkaStore { - #[instrument(skip_all)] - async fn insert_invoice_entry( - &self, - invoice_new: storage::invoice::InvoiceNew, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - self.diesel_store.insert_invoice_entry(invoice_new).await - } - - #[instrument(skip_all)] - async fn find_invoice_by_invoice_id( - &self, - invoice_id: String, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - self.diesel_store - .find_invoice_by_invoice_id(invoice_id) - .await - } - - #[instrument(skip_all)] - async fn update_invoice_entry( - &self, - invoice_id: String, - data: storage::invoice::InvoiceUpdate, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - self.diesel_store - .update_invoice_entry(invoice_id, data) - .await - } - - async fn get_latest_invoice_for_subscription( - &self, - subscription_id: String, - ) -> CustomResult<storage::Invoice, errors::StorageError> { - self.diesel_store - .get_latest_invoice_for_subscription(subscription_id) - .await - } -} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8bbee6ab8cf..84799f91cf5 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -23,9 +23,14 @@ use hyperswitch_domain_models::payouts::{ use hyperswitch_domain_models::{ cards_info::CardsInfoInterface, disputes, + invoice::{Invoice as DomainInvoice, InvoiceInterface, InvoiceUpdate as DomainInvoiceUpdate}, payment_methods::PaymentMethodInterface, payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface}, refunds, + subscription::{ + Subscription as DomainSubscription, SubscriptionInterface, + SubscriptionUpdate as DomainSubscriptionUpdate, + }, }; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; @@ -4335,3 +4340,101 @@ impl TokenizationInterface for KafkaStore { #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl TokenizationInterface for KafkaStore {} + +#[async_trait::async_trait] +impl InvoiceInterface for KafkaStore { + type Error = errors::StorageError; + + #[instrument(skip_all)] + async fn insert_invoice_entry( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + invoice_new: DomainInvoice, + ) -> CustomResult<DomainInvoice, errors::StorageError> { + self.diesel_store + .insert_invoice_entry(state, key_store, invoice_new) + .await + } + + #[instrument(skip_all)] + async fn find_invoice_by_invoice_id( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + invoice_id: String, + ) -> CustomResult<DomainInvoice, errors::StorageError> { + self.diesel_store + .find_invoice_by_invoice_id(state, key_store, invoice_id) + .await + } + + #[instrument(skip_all)] + async fn update_invoice_entry( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + invoice_id: String, + data: DomainInvoiceUpdate, + ) -> CustomResult<DomainInvoice, errors::StorageError> { + self.diesel_store + .update_invoice_entry(state, key_store, invoice_id, data) + .await + } + + #[instrument(skip_all)] + async fn get_latest_invoice_for_subscription( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + subscription_id: String, + ) -> CustomResult<DomainInvoice, errors::StorageError> { + self.diesel_store + .get_latest_invoice_for_subscription(state, key_store, subscription_id) + .await + } +} + +#[async_trait::async_trait] +impl SubscriptionInterface for KafkaStore { + type Error = errors::StorageError; + + #[instrument(skip_all)] + async fn insert_subscription_entry( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + subscription_new: DomainSubscription, + ) -> CustomResult<DomainSubscription, errors::StorageError> { + self.diesel_store + .insert_subscription_entry(state, key_store, subscription_new) + .await + } + + #[instrument(skip_all)] + async fn find_by_merchant_id_subscription_id( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + merchant_id: &id_type::MerchantId, + subscription_id: String, + ) -> CustomResult<DomainSubscription, errors::StorageError> { + self.diesel_store + .find_by_merchant_id_subscription_id(state, key_store, merchant_id, subscription_id) + .await + } + + #[instrument(skip_all)] + async fn update_subscription_entry( + &self, + state: &KeyManagerState, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + merchant_id: &id_type::MerchantId, + subscription_id: String, + data: DomainSubscriptionUpdate, + ) -> CustomResult<DomainSubscription, errors::StorageError> { + self.diesel_store + .update_subscription_entry(state, key_store, merchant_id, subscription_id, data) + .await + } +} diff --git a/crates/router/src/db/subscription.rs b/crates/router/src/db/subscription.rs deleted file mode 100644 index 5242c44299b..00000000000 --- a/crates/router/src/db/subscription.rs +++ /dev/null @@ -1,140 +0,0 @@ -use error_stack::report; -use router_env::{instrument, tracing}; -use storage_impl::MockDb; - -use super::Store; -use crate::{ - connection, - core::errors::{self, CustomResult}, - db::kafka_store::KafkaStore, - types::storage, -}; - -#[async_trait::async_trait] -pub trait SubscriptionInterface { - async fn insert_subscription_entry( - &self, - subscription_new: storage::subscription::SubscriptionNew, - ) -> CustomResult<storage::Subscription, errors::StorageError>; - - async fn find_by_merchant_id_subscription_id( - &self, - merchant_id: &common_utils::id_type::MerchantId, - subscription_id: String, - ) -> CustomResult<storage::Subscription, errors::StorageError>; - - async fn update_subscription_entry( - &self, - merchant_id: &common_utils::id_type::MerchantId, - subscription_id: String, - data: storage::SubscriptionUpdate, - ) -> CustomResult<storage::Subscription, errors::StorageError>; -} - -#[async_trait::async_trait] -impl SubscriptionInterface for Store { - #[instrument(skip_all)] - async fn insert_subscription_entry( - &self, - subscription_new: storage::subscription::SubscriptionNew, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - subscription_new - .insert(&conn) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - #[instrument(skip_all)] - async fn find_by_merchant_id_subscription_id( - &self, - merchant_id: &common_utils::id_type::MerchantId, - subscription_id: String, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::Subscription::find_by_merchant_id_subscription_id( - &conn, - merchant_id, - subscription_id, - ) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - #[instrument(skip_all)] - async fn update_subscription_entry( - &self, - merchant_id: &common_utils::id_type::MerchantId, - subscription_id: String, - data: storage::SubscriptionUpdate, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::Subscription::update_subscription_entry(&conn, merchant_id, subscription_id, data) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } -} - -#[async_trait::async_trait] -impl SubscriptionInterface for MockDb { - #[instrument(skip_all)] - async fn insert_subscription_entry( - &self, - _subscription_new: storage::subscription::SubscriptionNew, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } - - async fn find_by_merchant_id_subscription_id( - &self, - _merchant_id: &common_utils::id_type::MerchantId, - _subscription_id: String, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } - - async fn update_subscription_entry( - &self, - _merchant_id: &common_utils::id_type::MerchantId, - _subscription_id: String, - _data: storage::SubscriptionUpdate, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } -} - -#[async_trait::async_trait] -impl SubscriptionInterface for KafkaStore { - #[instrument(skip_all)] - async fn insert_subscription_entry( - &self, - subscription_new: storage::subscription::SubscriptionNew, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - self.diesel_store - .insert_subscription_entry(subscription_new) - .await - } - - #[instrument(skip_all)] - async fn find_by_merchant_id_subscription_id( - &self, - merchant_id: &common_utils::id_type::MerchantId, - subscription_id: String, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - self.diesel_store - .find_by_merchant_id_subscription_id(merchant_id, subscription_id) - .await - } - - #[instrument(skip_all)] - async fn update_subscription_entry( - &self, - merchant_id: &common_utils::id_type::MerchantId, - subscription_id: String, - data: storage::SubscriptionUpdate, - ) -> CustomResult<storage::Subscription, errors::StorageError> { - self.diesel_store - .update_subscription_entry(merchant_id, subscription_id, data) - .await - } -} diff --git a/crates/router/src/workflows/invoice_sync.rs b/crates/router/src/workflows/invoice_sync.rs index ec71af2b708..d72e59904f1 100644 --- a/crates/router/src/workflows/invoice_sync.rs +++ b/crates/router/src/workflows/invoice_sync.rs @@ -5,9 +5,7 @@ use common_utils::{ errors::CustomResult, ext_traits::{StringExt, ValueExt}, }; -use diesel_models::{ - invoice::Invoice, process_tracker::business_status, subscription::Subscription, -}; +use diesel_models::process_tracker::business_status; use error_stack::ResultExt; use router_env::logger; use scheduler::{ @@ -39,8 +37,8 @@ pub struct InvoiceSyncHandler<'a> { pub merchant_account: domain::MerchantAccount, pub customer: domain::Customer, pub profile: domain::Profile, - pub subscription: Subscription, - pub invoice: Invoice, + pub subscription: hyperswitch_domain_models::subscription::Subscription, + pub invoice: hyperswitch_domain_models::invoice::Invoice, } #[cfg(feature = "v1")] @@ -95,6 +93,8 @@ impl<'a> InvoiceSyncHandler<'a> { let subscription = state .store .find_by_merchant_id_subscription_id( + &state.into(), + &key_store, merchant_account.get_id(), tracking_data.subscription_id.get_string_repr().to_string(), ) @@ -103,7 +103,11 @@ impl<'a> InvoiceSyncHandler<'a> { let invoice = state .store - .find_invoice_by_invoice_id(tracking_data.invoice_id.get_string_repr().to_string()) + .find_invoice_by_invoice_id( + &state.into(), + &key_store, + tracking_data.invoice_id.get_string_repr().to_string(), + ) .await .attach_printable("invoices: unable to get latest invoice from database")?; diff --git a/crates/storage_impl/src/invoice.rs b/crates/storage_impl/src/invoice.rs new file mode 100644 index 00000000000..95330239167 --- /dev/null +++ b/crates/storage_impl/src/invoice.rs @@ -0,0 +1,200 @@ +use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; +pub use diesel_models::invoice::Invoice; +use error_stack::{report, ResultExt}; +pub use hyperswitch_domain_models::{ + behaviour::Conversion, + invoice::{Invoice as DomainInvoice, InvoiceInterface, InvoiceUpdate as DomainInvoiceUpdate}, + merchant_key_store::MerchantKeyStore, +}; +use router_env::{instrument, tracing}; + +use crate::{ + connection, errors::StorageError, kv_router_store::KVRouterStore, DatabaseStore, MockDb, + RouterStore, +}; + +#[async_trait::async_trait] +impl<T: DatabaseStore> InvoiceInterface for RouterStore<T> { + type Error = StorageError; + + #[instrument(skip_all)] + async fn insert_invoice_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_new: DomainInvoice, + ) -> CustomResult<DomainInvoice, StorageError> { + let inv_new = invoice_new + .construct_new() + .await + .change_context(StorageError::DecryptionError)?; + let conn = connection::pg_connection_write(self).await?; + self.call_database(state, key_store, inv_new.insert(&conn)) + .await + } + + #[instrument(skip_all)] + async fn find_invoice_by_invoice_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_id: String, + ) -> CustomResult<DomainInvoice, StorageError> { + let conn = connection::pg_connection_read(self).await?; + self.call_database( + state, + key_store, + Invoice::find_invoice_by_id_invoice_id(&conn, invoice_id), + ) + .await + } + + #[instrument(skip_all)] + async fn update_invoice_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_id: String, + data: DomainInvoiceUpdate, + ) -> CustomResult<DomainInvoice, StorageError> { + let inv_new = data + .construct_new() + .await + .change_context(StorageError::DecryptionError)?; + let conn = connection::pg_connection_write(self).await?; + self.call_database( + state, + key_store, + Invoice::update_invoice_entry(&conn, invoice_id, inv_new), + ) + .await + } + + #[instrument(skip_all)] + async fn get_latest_invoice_for_subscription( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_id: String, + ) -> CustomResult<DomainInvoice, StorageError> { + let conn = connection::pg_connection_write(self).await?; + let invoices: Vec<DomainInvoice> = self + .find_resources( + state, + key_store, + Invoice::list_invoices_by_subscription_id( + &conn, + subscription_id.clone(), + Some(1), + None, + false, + ), + ) + .await?; + + invoices + .last() + .cloned() + .ok_or(report!(StorageError::ValueNotFound(format!( + "Invoice not found for subscription_id: {}", + subscription_id + )))) + } +} + +#[async_trait::async_trait] +impl<T: DatabaseStore> InvoiceInterface for KVRouterStore<T> { + type Error = StorageError; + + #[instrument(skip_all)] + async fn insert_invoice_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_new: DomainInvoice, + ) -> CustomResult<DomainInvoice, StorageError> { + self.router_store + .insert_invoice_entry(state, key_store, invoice_new) + .await + } + + #[instrument(skip_all)] + async fn find_invoice_by_invoice_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_id: String, + ) -> CustomResult<DomainInvoice, StorageError> { + self.router_store + .find_invoice_by_invoice_id(state, key_store, invoice_id) + .await + } + + #[instrument(skip_all)] + async fn update_invoice_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + invoice_id: String, + data: DomainInvoiceUpdate, + ) -> CustomResult<DomainInvoice, StorageError> { + self.router_store + .update_invoice_entry(state, key_store, invoice_id, data) + .await + } + + #[instrument(skip_all)] + async fn get_latest_invoice_for_subscription( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_id: String, + ) -> CustomResult<DomainInvoice, StorageError> { + self.router_store + .get_latest_invoice_for_subscription(state, key_store, subscription_id) + .await + } +} + +#[async_trait::async_trait] +impl InvoiceInterface for MockDb { + type Error = StorageError; + + #[instrument(skip_all)] + async fn insert_invoice_entry( + &self, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, + _invoice_new: DomainInvoice, + ) -> CustomResult<DomainInvoice, StorageError> { + Err(StorageError::MockDbError)? + } + + async fn find_invoice_by_invoice_id( + &self, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, + _invoice_id: String, + ) -> CustomResult<DomainInvoice, StorageError> { + Err(StorageError::MockDbError)? + } + + async fn update_invoice_entry( + &self, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, + _invoice_id: String, + _data: DomainInvoiceUpdate, + ) -> CustomResult<DomainInvoice, StorageError> { + Err(StorageError::MockDbError)? + } + + async fn get_latest_invoice_for_subscription( + &self, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, + _subscription_id: String, + ) -> CustomResult<DomainInvoice, StorageError> { + Err(StorageError::MockDbError)? + } +} diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index b2a2dba5779..5e6483fd1d3 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -16,6 +16,7 @@ pub mod connection; pub mod customers; pub mod database; pub mod errors; +pub mod invoice; pub mod kv_router_store; pub mod lookup; pub mod mandate; @@ -28,6 +29,7 @@ pub mod payouts; pub mod redis; pub mod refund; mod reverse_lookup; +pub mod subscription; pub mod utils; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; diff --git a/crates/storage_impl/src/subscription.rs b/crates/storage_impl/src/subscription.rs new file mode 100644 index 00000000000..79e844c9857 --- /dev/null +++ b/crates/storage_impl/src/subscription.rs @@ -0,0 +1,155 @@ +use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; +pub use diesel_models::subscription::Subscription; +use error_stack::ResultExt; +pub use hyperswitch_domain_models::{ + behaviour::Conversion, + merchant_key_store::MerchantKeyStore, + subscription::{ + Subscription as DomainSubscription, SubscriptionInterface, + SubscriptionUpdate as DomainSubscriptionUpdate, + }, +}; +use router_env::{instrument, tracing}; + +use crate::{ + connection, errors::StorageError, kv_router_store::KVRouterStore, DatabaseStore, MockDb, + RouterStore, +}; + +#[async_trait::async_trait] +impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> { + type Error = StorageError; + + #[instrument(skip_all)] + async fn insert_subscription_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_new: DomainSubscription, + ) -> CustomResult<DomainSubscription, StorageError> { + let sub_new = subscription_new + .construct_new() + .await + .change_context(StorageError::DecryptionError)?; + let conn = connection::pg_connection_write(self).await?; + self.call_database(state, key_store, sub_new.insert(&conn)) + .await + } + #[instrument(skip_all)] + async fn find_by_merchant_id_subscription_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + ) -> CustomResult<DomainSubscription, StorageError> { + let conn = connection::pg_connection_write(self).await?; + self.call_database( + state, + key_store, + Subscription::find_by_merchant_id_subscription_id(&conn, merchant_id, subscription_id), + ) + .await + } + + #[instrument(skip_all)] + async fn update_subscription_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + data: DomainSubscriptionUpdate, + ) -> CustomResult<DomainSubscription, StorageError> { + let sub_new = data + .construct_new() + .await + .change_context(StorageError::DecryptionError)?; + let conn = connection::pg_connection_write(self).await?; + self.call_database( + state, + key_store, + Subscription::update_subscription_entry(&conn, merchant_id, subscription_id, sub_new), + ) + .await + } +} + +#[async_trait::async_trait] +impl<T: DatabaseStore> SubscriptionInterface for KVRouterStore<T> { + type Error = StorageError; + + #[instrument(skip_all)] + async fn insert_subscription_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + subscription_new: DomainSubscription, + ) -> CustomResult<DomainSubscription, StorageError> { + self.router_store + .insert_subscription_entry(state, key_store, subscription_new) + .await + } + #[instrument(skip_all)] + async fn find_by_merchant_id_subscription_id( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + ) -> CustomResult<DomainSubscription, StorageError> { + self.router_store + .find_by_merchant_id_subscription_id(state, key_store, merchant_id, subscription_id) + .await + } + + #[instrument(skip_all)] + async fn update_subscription_entry( + &self, + state: &KeyManagerState, + key_store: &MerchantKeyStore, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + data: DomainSubscriptionUpdate, + ) -> CustomResult<DomainSubscription, StorageError> { + self.router_store + .update_subscription_entry(state, key_store, merchant_id, subscription_id, data) + .await + } +} + +#[async_trait::async_trait] +impl SubscriptionInterface for MockDb { + type Error = StorageError; + + #[instrument(skip_all)] + async fn insert_subscription_entry( + &self, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, + _subscription_new: DomainSubscription, + ) -> CustomResult<DomainSubscription, StorageError> { + Err(StorageError::MockDbError)? + } + + async fn find_by_merchant_id_subscription_id( + &self, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, + _merchant_id: &common_utils::id_type::MerchantId, + _subscription_id: String, + ) -> CustomResult<DomainSubscription, StorageError> { + Err(StorageError::MockDbError)? + } + + async fn update_subscription_entry( + &self, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, + _merchant_id: &common_utils::id_type::MerchantId, + _subscription_id: String, + _data: DomainSubscriptionUpdate, + ) -> CustomResult<DomainSubscription, StorageError> { + Err(StorageError::MockDbError)? + } +}
2025-10-01T09:39:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This pull request introduces new domain models for subscriptions and invoices, and refactors the codebase to use these models instead of the previous Diesel-based models. The changes improve type safety and abstraction for subscription and invoice handling, and update relevant interfaces and function calls throughout the codebase to use the new models. **Domain Model Additions:** * Added a new `Subscription` domain model in `crates/hyperswitch_domain_models/src/subscription.rs`, including the `SubscriptionStatus` enum, conversion traits, and the `SubscriptionInterface` trait for standardized operations. Also added the `SubscriptionUpdate` struct with conversion logic. * Added a new `Invoice` domain model in `crates/hyperswitch_domain_models/src/invoice.rs`, including conversion traits, the `InvoiceInterface` trait for CRUD operations, and the `InvoiceUpdate` struct with conversion logic. **Refactoring and Integration:** * Refactored all subscription and invoice-related logic in `crates/router/src/core/subscription.rs` and `crates/router/src/core/subscription/billing_processor_handler.rs` to use the new domain models (`hyperswitch_domain_models::subscription::Subscription` and `hyperswitch_domain_models::invoice::Invoice`) instead of Diesel models. [[1]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL83-L95) [[2]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL201-R203) [[3]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL210-R213) [[4]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL320-R324) [[5]](diffhunk://#diff-adea1b33060886c62616ea56c46edb8f356525cbacea004da12e8819334cf27cL329-R334) [[6]](diffhunk://#diff-57a5a7402c9b28e022a6839808acf84b88808f76da82ce1c76a80660c8869ec6L168-R168) [[7]](diffhunk://#diff-bacee0b3d81189090ca0d5f72fc58118b681a7dd4aab772679f2dec2a585a073L13-R28) [[8]](diffhunk://#diff-bacee0b3d81189090ca0d5f72fc58118b681a7dd4aab772679f2dec2a585a073L47-R50) * Updated the invoice creation logic in `invoice_handler.rs` to use the new domain model and retrieve the merchant key store for secure operations. **Module Organization:** * Registered the new `invoice` and `subscription` modules in `crates/hyperswitch_domain_models/src/lib.rs` for proper integration with the rest of the domain models. [[1]](diffhunk://#diff-7ea431033335b7e3d2454c104f750be19973ad4f061a8cdb5c50af53ebdff00bR18) [[2]](diffhunk://#diff-7ea431033335b7e3d2454c104f750be19973ad4f061a8cdb5c50af53ebdff00bR41) These changes lay the groundwork for improved maintainability and extensibility in handling subscriptions and invoices in the codebase. ## How did you test it? Create Billing Connector ``` curl --location 'http://localhost:8080/account/merchant_1759737987/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ****' \ --data '{ "connector_type": "billing_processor", "connector_name": "chargebee", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "****" }, "business_country": "US", "business_label": "default", "connector_webhook_details": { "merchant_secret": "hyperswitch", "additional_secret": "hyperswitch" }, "metadata": { "site": "hyperswitch-juspay3-test" } }' ``` ``` { "connector_type": "billing_processor", "connector_name": "chargebee", "connector_label": "chargebee_US_default", "merchant_connector_id": "mca_nyehf3o9gtzGgeVFzsx0", "profile_id": "pro_Ba2HYJtnuKdJzv2SBizB", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "te**********************************MK" }, "payment_methods_enabled": null, "connector_webhook_details": { "merchant_secret": "hyperswitch", "additional_secret": "hyperswitch" }, "metadata": { "site": "hyperswitch-juspay3-test" }, "test_mode": null, "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 } ``` Update profile to set the billing processor ``` curl --location 'http://localhost:8080/account/merchant_1759737987/business_profile/pro_Ba2HYJtnuKdJzv2SBizB' \ --header 'Content-Type: application/json' \ --header 'api-key: ****' \ --data '{ "billing_processor_id": "mca_nyehf3o9gtzGgeVFzsx0" }' ``` ``` { "merchant_id": "merchant_1759737987", "profile_id": "pro_Ba2HYJtnuKdJzv2SBizB", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "BPIswjNm5ivN92rBE9J4ShmB2dfLVLeQ8DRnzY7cR7qsaUlfNpBgvnOCBWRfhR5e", "redirect_to_merchant_with_http_post": false, "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, "payment_statuses_enabled": null, "refund_statuses_enabled": null, "payout_statuses_enabled": null }, "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": null, "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": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "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, "is_debit_routing_enabled": false, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false, "acquirer_configs": null, "is_iframe_redirection_enabled": null, "merchant_category_code": null, "merchant_country_code": null, "dispute_polling_interval": null, "is_manual_retry_enabled": null, "always_enable_overcapture": null, "is_external_vault_enabled": "skip", "external_vault_connector_details": null, "billing_processor_id": "mca_nyehf3o9gtzGgeVFzsx0" } ``` Create Customer ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ****' \ --data-raw '{ "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "customer_id": "cus_EkIUbktzRFCHooI9Kylq", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "created_at": "2025-10-06T08:08:37.562Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null } ``` Create Subscription ``` curl --location 'http://localhost:8080/subscriptions/create' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_Ba2HYJtnuKdJzv2SBizB' \ --header 'api-key: ****' \ --data '{ "customer_id": "cus_EkIUbktzRFCHooI9Kylq", "amount": 14100, "currency": "USD", "payment_details": { "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com" } }' ``` ``` { "id": "sub_Q1ttH0p1b50OtnDgZfrz", "merchant_reference_id": null, "status": "created", "plan_id": null, "profile_id": "pro_Ba2HYJtnuKdJzv2SBizB", "client_secret": "sub_Q1ttH0p1b50OtnDgZfrz_secret_jXFTn0oMPowj2RqRUcWX", "merchant_id": "merchant_1759737987", "coupon_code": null, "customer_id": "cus_EkIUbktzRFCHooI9Kylq" } ``` Confirm Subscription ``` curl --location 'http://localhost:8080/subscriptions/sub_Q1ttH0p1b50OtnDgZfrz/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_Ba2HYJtnuKdJzv2SBizB' \ --header 'api-key: ****' \ --data '{ "item_price_id": "cbdemo_enterprise-suite-monthly", "customer_id": "cus_EkIUbktzRFCHooI9Kylq", "description": "Hello this is description", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "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" } } } }' ``` ``` { "id": "sub_Q1ttH0p1b50OtnDgZfrz", "merchant_reference_id": null, "status": "active", "plan_id": null, "price_id": null, "coupon": null, "profile_id": "pro_Ba2HYJtnuKdJzv2SBizB", "payment": { "payment_id": "pay_uadWety0AlrsIpLa2Dt6", "status": "succeeded", "amount": 14100, "currency": "USD", "connector": "stripe", "payment_method_id": "pm_HBp7wdIyHsvnta708kxF", "payment_experience": null, "error_code": null, "error_message": null, "payment_method_type": "credit" }, "customer_id": "cus_EkIUbktzRFCHooI9Kylq", "invoice": { "id": "invoice_UwA8TmKbXgxE1a7s6Nux", "subscription_id": "sub_Q1ttH0p1b50OtnDgZfrz", "merchant_id": "merchant_1759737987", "profile_id": "pro_Ba2HYJtnuKdJzv2SBizB", "merchant_connector_id": "mca_nyehf3o9gtzGgeVFzsx0", "payment_intent_id": "pay_uadWety0AlrsIpLa2Dt6", "payment_method_id": "pm_HBp7wdIyHsvnta708kxF", "customer_id": "cus_EkIUbktzRFCHooI9Kylq", "amount": 14100, "currency": "USD", "status": "payment_pending" }, "billing_processor_subscription_id": "sub_Q1ttH0p1b50OtnDgZfrz" } ``` Screenshots <img width="617" height="229" alt="Screenshot 2025-10-06 at 1 44 10 PM" src="https://github.com/user-attachments/assets/f11a1fe2-d7e9-4d2b-99db-c68f35212b2b" /> <img width="436" height="252" alt="Screenshot 2025-10-06 at 1 44 18 PM" src="https://github.com/user-attachments/assets/b66abdad-d216-4a12-84f0-653a1654ea7a" />
abcc70be074130827c14f90ff4cc7de964994efa
juspay/hyperswitch
juspay__hyperswitch-9696
Bug: [FIX] (connector) Skrill payment method in Paysafe throws 501 origin: paysafe transformers L566 payment going through pre process flow, unexpected. skrill should go through authorize + complete authorize flow rca: preprocessing is being applied to entire wallet for paysafe connector. it needs to be restricted to apple pay since apple pay does not require complete authorize flow
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e9a917153f2..e3d153f2aa4 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -6623,11 +6623,14 @@ where false, ) } else if connector.connector_name == router_types::Connector::Paysafe { - router_data = router_data.preprocessing_steps(state, connector).await?; - - let is_error_in_response = router_data.response.is_err(); - // If is_error_in_response is true, should_continue_payment should be false, we should throw the error - (router_data, !is_error_in_response) + match payment_data.get_payment_method_data() { + Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(_))) => { + router_data = router_data.preprocessing_steps(state, connector).await?; + let is_error_in_response = router_data.response.is_err(); + (router_data, !is_error_in_response) + } + _ => (router_data, should_continue_payment), + } } else { (router_data, should_continue_payment) }
2025-10-06T11:39:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> this pr fixes bug in paysafe where skrill wallet payment method was throwing `501`. the reason being, we've added a check in preprocessing call that applied to all wallet payment methods for paysafe instead of having it applied to apple pay specifically. this pr fixes that. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> skrill, unintentionally went to preprocessing step that resulted in 501 while the payment method is implemented in authorize call. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <details> <summary>Apple Pay</summary> Create ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_wcCEnIpNCiH8uz9vhjaLpojPpZLQAo0ScLnQ1VPuSFGWa5x1vbKtBGqwd2wII9HM' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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_nKWxEfg6kk2sBUFGFMeR", "merchant_id": "postman_merchant_GHAction_1759750181", "status": "requires_payment_method", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_nKWxEfg6kk2sBUFGFMeR_secret_89GK0HlI7M74crmy87AS", "created": "2025-10-06T11:32:52.402Z", "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": null, "billing": null, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1759750372, "expires": 1759753972, "secret": "epk_5cf9e0984e984eadb290d4d6f68e1070" }, "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_HwXSI9BzQBCoG4QkGRlw", "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-10-06T11:47:52.402Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T11:32:52.431Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` Session ```bash curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_7d80afd0f4b841e2a0b0e1a460f6039c' \ --data '{ "payment_id": "pay_nKWxEfg6kk2sBUFGFMeR", "wallets": [], "client_secret": "pay_nKWxEfg6kk2sBUFGFMeR_secret_89GK0HlI7M74crmy87AS" }' ``` ```json { "payment_id": "pay_nKWxEfg6kk2sBUFGFMeR", "client_secret": "pay_nKWxEfg6kk2sBUFGFMeR_secret_89GK0HlI7M74crmy87AS", "session_token": [ { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1759750383162, "expires_at": 1759753983162, "merchant_session_identifier": "SS..C3", "nonce": "08ed5fa4", "merchant_identifier": "8C..C4", "domain_name": "hyperswitch.app", "display_name": "apple pay", "signature": "30..00", "operational_analytics_identifier": "apple pay:8C...C4", "retries": 0, "psp_id": "8C...C4" }, "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "10.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.lol" }, "connector": "paysafe", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` Confirm ```bash curl --location 'http://localhost:8080/payments/pay_nKWxEfg6kk2sBUFGFMeR/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7hcskEypRcDWscoO2H26tDR7GKLF3kT0ypXEF1YMCoLPKAm7fglmqZ4zBTaiLlid' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": { "application_primary_account_number": "5204245253050839", "application_expiration_month": "01", "application_expiration_year": "30", "payment_data": { "online_payment_cryptogram": "A/FwSJkAlul/sRItXYorMAACAAA=", "eci_indicator": "1" } }, "payment_method": { "display_name": "Visa 4228", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "a0...4a" } }, "billing": null }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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" } } }' ``` ```json { "payment_id": "pay_nKWxEfg6kk2sBUFGFMeR", "merchant_id": "postman_merchant_GHAction_1759750181", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "paysafe", "client_secret": "pay_nKWxEfg6kk2sBUFGFMeR_secret_89GK0HlI7M74crmy87AS", "created": "2025-10-06T11:34:26.900Z", "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": { "apple_pay": { "last4": "4228", "card_network": "Mastercard", "type": "debit" } }, "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", "origin_zip": 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": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "connector_label": "paysafe_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "f115ce9c-fd30-49dc-94f1-81e3cb868154", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_3ChHsAtYFOz9hH9VMtnw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_4L5eJPYlmGaJigFIaTZl", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T11:49:26.900Z", "fingerprint": null, "browser_info": { "os_type": null, "referer": null, "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "os_version": null, "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, "device_model": null, "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, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T11:34:32.130Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` </details> <details> <summary>Skrill</summary> ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_wcCEnIpNCiH8uz9vhjaLpojPpZLQAo0ScLnQ1VPuSFGWa5x1vbKtBGqwd2wII9HM' \ --data-raw '{ "amount": 1500, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "authentication_type": "three_ds", "payment_method": "wallet", "payment_method_type": "skrill", "payment_method_data": { "wallet": { "skrill": {} } }, "billing": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "SG", "first_name": "박성준", "last_name": "박성준" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } }' ``` ```json { "payment_id": "pay_ZR36mAH59ofEyHCuMfNr", "merchant_id": "postman_merchant_GHAction_1759750181", "status": "requires_customer_action", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 1500, "amount_received": null, "connector": "paysafe", "client_secret": "pay_ZR36mAH59ofEyHCuMfNr_secret_fHOQqa4f7kuV026Br3Sx", "created": "2025-10-06T11:29:48.570Z", "currency": "USD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "박성준", "last_name": "박성준", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_ZR36mAH59ofEyHCuMfNr/postman_merchant_GHAction_1759750181/pay_ZR36mAH59ofEyHCuMfNr_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "skrill", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "aaaa", "created_at": 1759750188, "expires": 1759753788, "secret": "epk_5802f16446f44f4286501593b0a0efe0" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_HwXSI9BzQBCoG4QkGRlw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_akveLwRd2jjVRaaaPyl5", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T11:44:48.570Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T11:29:49.759Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` <img width="1650" height="837" alt="image" src="https://github.com/user-attachments/assets/d02971d2-e598-49dd-a854-a17829cb3d59" /> <img width="543" height="49" alt="image" src="https://github.com/user-attachments/assets/95eac0ff-f57d-4594-9d4a-1dc06b1d1d57" /> Retrieve ```bash curl --location 'https://base_url/payments/pay_N9z0Jg00H5Dynb7CSKQ0?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_zrrGPfKKd8sxgS7BmJrkv4vpl2murNtShyPc8o9YlGzuaonmYJwMMyQOdbCfCXcu' ``` ```json { "payment_id": "pay_N9z0Jg00H5Dynb7CSKQ0", "merchant_id": "postman_merchant_GHAction_1759750928", "status": "succeeded", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1500, "connector": "paysafe", "client_secret": "pay_N9z0Jg00H5Dynb7CSKQ0_secret_uzp2n3oQPqD0tIjdNPVU", "created": "2025-10-06T12:22:47.738Z", "currency": "USD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "박성준", "last_name": "박성준", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "skrill", "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": "9abc1eaf-af0f-49b9-834c-afb2b12291f4", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_gb3FQWk8hJtjW6FP5c6K", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_AkDHUgxUaV8R6UP65h8v", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T12:37:47.738Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T12:23:02.068Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
cc4eaed5702dbcaa6c54a32714b52f479dfbe85b
juspay/hyperswitch
juspay__hyperswitch-9732
Bug: [FEATURE]: [LOONIO] Add payouts Add payouts for loonio
diff --git a/config/config.example.toml b/config/config.example.toml index 986a94540d5..e5e45a09021 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1029,6 +1029,9 @@ debit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } +[payout_method_filters.loonio] +interac = { currency = "CAD" } + [payment_link] sdk_url = "http://localhost:9090/0.16.7/v0/HyperLoader.js" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 11cd0026ea0..9716de5811c 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -786,6 +786,9 @@ debit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } +[payout_method_filters.loonio] +interac = { currency = "CAD" } + [pm_filters.inespay] sepa = { country = "ES", currency = "EUR"} diff --git a/config/deployments/production.toml b/config/deployments/production.toml index bf94c7358eb..bedeb6fa5fc 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -856,6 +856,9 @@ debit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } +[payout_method_filters.loonio] +interac = { currency = "CAD" } + [temp_locker_enable_config] bluesnap.payment_method = "card" nuvei.payment_method = "card" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 4c402c8c73f..f77b4c0f4fa 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -862,6 +862,9 @@ apple_pay = {country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } +[payout_method_filters.loonio] +interac = { currency = "CAD" } + [temp_locker_enable_config] bluesnap.payment_method = "card" nuvei.payment_method = "card" diff --git a/config/development.toml b/config/development.toml index 7bc13f554b8..f9223130229 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1184,6 +1184,9 @@ debit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } +[payout_method_filters.loonio] +interac = { currency = "CAD" } + [payment_link] sdk_url = "http://localhost:9050/HyperLoader.js" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index acfd8c7bcd6..01fddf8ad19 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1194,6 +1194,9 @@ debit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } +[payout_method_filters.loonio] +interac = { currency = "CAD" } + [locker_based_open_banking_connectors] connector_list = "tokenio" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index de46df2373e..45ce4f46d09 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -49,6 +49,7 @@ pub enum PayoutConnectors { Cybersource, Ebanx, Gigadat, + Loonio, Nomupay, Nuvei, Payone, @@ -77,6 +78,7 @@ impl From<PayoutConnectors> for RoutableConnectors { PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Gigadat => Self::Gigadat, + PayoutConnectors::Loonio => Self::Loonio, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, @@ -96,6 +98,7 @@ impl From<PayoutConnectors> for Connector { PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Gigadat => Self::Gigadat, + PayoutConnectors::Loonio => Self::Loonio, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, @@ -115,6 +118,7 @@ impl TryFrom<Connector> for PayoutConnectors { Connector::Adyenplatform => Ok(Self::Adyenplatform), Connector::Cybersource => Ok(Self::Cybersource), Connector::Ebanx => Ok(Self::Ebanx), + Connector::Loonio => Ok(Self::Loonio), Connector::Nuvei => Ok(Self::Nuvei), Connector::Nomupay => Ok(Self::Nomupay), Connector::Payone => Ok(Self::Payone), diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index d61fc5bbc09..03b53804161 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -242,6 +242,7 @@ pub enum PayoutMethodData { Card(CardPayout), Bank(Bank), Wallet(Wallet), + BankRedirect(BankRedirect), } impl Default for PayoutMethodData { @@ -378,6 +379,19 @@ pub enum Wallet { Venmo(Venmo), } +#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum BankRedirect { + Interac(Interac), +} + +#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] +pub struct Interac { + /// Customer email linked with interac account + #[schema(value_type = String, example = "[email protected]")] + pub email: Email, +} + #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Paypal { /// Email linked with paypal account @@ -602,6 +616,8 @@ pub enum PayoutMethodDataResponse { Bank(Box<payout_method_utils::BankAdditionalData>), #[schema(value_type = WalletAdditionalData)] Wallet(Box<payout_method_utils::WalletAdditionalData>), + #[schema(value_type = BankRedirectAdditionalData)] + BankRedirect(Box<payout_method_utils::BankRedirectAdditionalData>), } #[derive( @@ -988,6 +1004,18 @@ impl From<Wallet> for payout_method_utils::WalletAdditionalData { } } +impl From<BankRedirect> for payout_method_utils::BankRedirectAdditionalData { + fn from(bank_redirect: BankRedirect) -> Self { + match bank_redirect { + BankRedirect::Interac(Interac { email }) => { + Self::Interac(Box::new(payout_method_utils::InteracAdditionalData { + email: Some(ForeignFrom::foreign_from(email)), + })) + } + } + } +} + impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataResponse { fn from(additional_data: payout_method_utils::AdditionalPayoutMethodData) -> Self { match additional_data { @@ -1000,6 +1028,9 @@ impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataR payout_method_utils::AdditionalPayoutMethodData::Wallet(wallet_data) => { Self::Wallet(wallet_data) } + payout_method_utils::AdditionalPayoutMethodData::BankRedirect(bank_redirect) => { + Self::BankRedirect(bank_redirect) + } } } } diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 3a92de53503..2b225e09a5d 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -374,6 +374,7 @@ impl Connector { | (_, Some(PayoutType::Card)) | (Self::Adyenplatform, _) | (Self::Nomupay, _) + | (Self::Loonio, _) ) } #[cfg(feature = "payouts")] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index b9053b46bc5..a6b9acd7e3c 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -7865,6 +7865,7 @@ pub enum PayoutType { Card, Bank, Wallet, + BankRedirect, } /// Type of entity to whom the payout is being carried out to, select from the given list of options diff --git a/crates/common_utils/src/payout_method_utils.rs b/crates/common_utils/src/payout_method_utils.rs index 3a2a9e4c386..94f23c179d2 100644 --- a/crates/common_utils/src/payout_method_utils.rs +++ b/crates/common_utils/src/payout_method_utils.rs @@ -23,6 +23,8 @@ pub enum AdditionalPayoutMethodData { Bank(Box<BankAdditionalData>), /// Additional data for wallet payout method Wallet(Box<WalletAdditionalData>), + /// Additional data for Bank Redirect payout method + BankRedirect(Box<BankRedirectAdditionalData>), } crate::impl_to_sql_from_sql_json!(AdditionalPayoutMethodData); @@ -238,3 +240,25 @@ pub struct VenmoAdditionalData { #[schema(value_type = Option<String>, example = "******* 3349")] pub telephone_number: Option<MaskedPhoneNumber>, } + +/// Masked payout method details for wallet payout method +#[derive( + Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, +)] +#[diesel(sql_type = Jsonb)] +#[serde(untagged)] +pub enum BankRedirectAdditionalData { + /// Additional data for interac bank redirect payout method + Interac(Box<InteracAdditionalData>), +} + +/// Masked payout method details for interac bank redirect payout method +#[derive( + Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, +)] +#[diesel(sql_type = Jsonb)] +pub struct InteracAdditionalData { + /// Email linked with interac account + #[schema(value_type = Option<String>, example = "[email protected]")] + pub email: Option<MaskedEmail>, +} diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index be428b1ef1f..e92311b46c0 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -299,6 +299,8 @@ pub struct ConnectorConfig { pub jpmorgan: Option<ConnectorTomlConfig>, pub klarna: Option<ConnectorTomlConfig>, pub loonio: Option<ConnectorTomlConfig>, + #[cfg(feature = "payouts")] + pub loonio_payout: Option<ConnectorTomlConfig>, pub mifinity: Option<ConnectorTomlConfig>, pub mollie: Option<ConnectorTomlConfig>, pub moneris: Option<ConnectorTomlConfig>, @@ -403,6 +405,7 @@ impl ConnectorConfig { PayoutConnectors::Cybersource => Ok(connector_data.cybersource_payout), PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout), PayoutConnectors::Gigadat => Ok(connector_data.gigadat_payout), + PayoutConnectors::Loonio => Ok(connector_data.loonio_payout), PayoutConnectors::Nomupay => Ok(connector_data.nomupay_payout), PayoutConnectors::Nuvei => Ok(connector_data.nuvei_payout), PayoutConnectors::Payone => Ok(connector_data.payone_payout), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index e56bc1f05c7..b318b612b59 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7278,6 +7278,13 @@ key1 = "Merchant Token" [[loonio.bank_redirect]] payment_method_type = "interac" +[loonio_payout] +[loonio_payout.connector_auth.BodyKey] +api_key = "Merchant ID" +key1 = "Merchant Token" +[[loonio_payout.bank_redirect]] +payment_method_type = "interac" + [tesouro] [[tesouro.credit]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 8d8c61f4e7b..0ce8807d8b8 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -6015,6 +6015,13 @@ key1 = "Merchant Token" [[loonio.bank_redirect]] payment_method_type = "interac" +[loonio_payout] +[loonio_payout.connector_auth.BodyKey] +api_key = "Merchant ID" +key1 = "Merchant Token" +[[loonio_payout.bank_redirect]] +payment_method_type = "interac" + [tesouro] [[tesouro.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 4cb91ba2534..0c1af3229f4 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7257,6 +7257,12 @@ key1 = "Merchant Token" [[loonio.bank_redirect]] payment_method_type = "interac" +[loonio_payout] +[loonio_payout.connector_auth.BodyKey] +api_key = "Merchant ID" +key1 = "Merchant Token" +[[loonio_payout.bank_redirect]] +payment_method_type = "interac" [tesouro] [[tesouro.credit]] diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs index 22fb997530c..0664fc27ecf 100644 --- a/crates/euclid/src/enums.rs +++ b/crates/euclid/src/enums.rs @@ -166,4 +166,5 @@ pub enum PayoutType { Card, BankTransfer, Wallet, + BankRedirect, } diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index a07986ba18e..a155d7addd3 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -1593,15 +1593,19 @@ impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Adyen &req.connector_meta_data, )?; let payout_type = req.request.get_payout_type()?; + let path_segment = match payout_type { + enums::PayoutType::Bank | enums::PayoutType::Wallet => "confirmThirdParty", + enums::PayoutType::Card => "payout", + enums::PayoutType::BankRedirect => { + return Err(errors::ConnectorError::NotImplemented( + "bank redirect payouts not supoorted by adyen".to_string(), + ) + .into()) + } + }; Ok(format!( "{}pal/servlet/Payout/{}/{}", - endpoint, - ADYEN_API_VERSION, - match payout_type { - enums::PayoutType::Bank | enums::PayoutType::Wallet => - "confirmThirdParty".to_string(), - enums::PayoutType::Card => "payout".to_string(), - } + endpoint, ADYEN_API_VERSION, path_segment )) } @@ -1627,7 +1631,9 @@ impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Adyen let mut api_key = vec![( headers::X_API_KEY.to_string(), match payout_type { - enums::PayoutType::Bank | enums::PayoutType::Wallet => { + enums::PayoutType::Bank + | enums::PayoutType::Wallet + | enums::PayoutType::BankRedirect => { auth.review_key.unwrap_or(auth.api_key).into_masked() } enums::PayoutType::Card => auth.api_key.into_masked(), diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 957653b3fb3..e455882151a 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -5742,6 +5742,10 @@ impl<F> TryFrom<&AdyenRouterData<&PayoutsRouterData<F>>> for AdyenPayoutCreateRe .transpose()?, }) } + PayoutMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotSupported { + message: "Bank redirect payout creation is not supported".to_string(), + connector: "Adyen", + })?, } } } @@ -5755,7 +5759,9 @@ impl<F> TryFrom<&AdyenRouterData<&PayoutsRouterData<F>>> for AdyenPayoutFulfillR let payout_type = item.router_data.request.get_payout_type()?; let merchant_account = auth_type.merchant_account; match payout_type { - storage_enums::PayoutType::Bank | storage_enums::PayoutType::Wallet => { + storage_enums::PayoutType::Bank + | storage_enums::PayoutType::Wallet + | storage_enums::PayoutType::BankRedirect => { Ok(Self::GenericFulfillRequest(PayoutFulfillGenericRequest { merchant_account, original_reference: item diff --git a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs index 2f49d297569..fd4b249ee3f 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs @@ -458,9 +458,11 @@ impl<F> TryFrom<RawPaymentCounterparty<'_, F>> let request = &raw_payment.item.router_data.request; match raw_payment.raw_payout_method_data { - payouts::PayoutMethodData::Wallet(_) => Err(ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Adyenplatform"), - ))?, + payouts::PayoutMethodData::Wallet(_) | payouts::PayoutMethodData::BankRedirect(_) => { + Err(ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyenplatform"), + ))? + } payouts::PayoutMethodData::Card(c) => { let card_holder: AdyenAccountHolder = (raw_payment.item.router_data, &c).try_into()?; @@ -661,10 +663,12 @@ impl TryFrom<enums::PayoutType> for AdyenPayoutMethod { match payout_type { enums::PayoutType::Bank => Ok(Self::Bank), enums::PayoutType::Card => Ok(Self::Card), - enums::PayoutType::Wallet => Err(report!(ConnectorError::NotSupported { - message: "Card or wallet payouts".to_string(), - connector: "Adyenplatform", - })), + enums::PayoutType::Wallet | enums::PayoutType::BankRedirect => { + Err(report!(ConnectorError::NotSupported { + message: "Bakredirect or wallet payouts".to_string(), + connector: "Adyenplatform", + })) + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index cbd97ccf845..eaf6304ef23 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -4975,12 +4975,12 @@ impl TryFrom<&CybersourceRouterData<&PayoutsRouterData<PoFulfill>>> payment_information, }) } - enums::PayoutType::Bank | enums::PayoutType::Wallet => { - Err(errors::ConnectorError::NotSupported { - message: "PayoutType is not supported".to_string(), - connector: "Cybersource", - })? - } + enums::PayoutType::Bank + | enums::PayoutType::Wallet + | enums::PayoutType::BankRedirect => Err(errors::ConnectorError::NotSupported { + message: "PayoutType is not supported".to_string(), + connector: "Cybersource", + })?, } } } @@ -5034,12 +5034,12 @@ impl TryFrom<PayoutMethodData> for PaymentInformation { }; Ok(Self::Cards(Box::new(CardPaymentInformation { card }))) } - PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { - Err(errors::ConnectorError::NotSupported { - message: "PayoutMethod is not supported".to_string(), - connector: "Cybersource", - })? - } + PayoutMethodData::Bank(_) + | PayoutMethodData::Wallet(_) + | PayoutMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotSupported { + message: "PayoutMethod is not supported".to_string(), + connector: "Cybersource", + })?, } } } diff --git a/crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs b/crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs index 82e37912560..42caad6c2f5 100644 --- a/crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs @@ -139,12 +139,13 @@ impl TryFrom<&EbanxRouterData<&PayoutsRouterData<PoCreate>>> for EbanxPayoutCrea payee, }) } - PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { - Err(ConnectorError::NotSupported { - message: "Payment Method Not Supported".to_string(), - connector: "Ebanx", - })? - } + PayoutMethodData::Card(_) + | PayoutMethodData::Bank(_) + | PayoutMethodData::Wallet(_) + | PayoutMethodData::BankRedirect(_) => Err(ConnectorError::NotSupported { + message: "Payment Method Not Supported".to_string(), + connector: "Ebanx", + })?, } } } @@ -245,10 +246,12 @@ impl<F> TryFrom<&EbanxRouterData<&PayoutsRouterData<F>>> for EbanxPayoutFulfillR .to_owned() .ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?, }), - PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotSupported { - message: "Payout Method Not Supported".to_string(), - connector: "Ebanx", - })?, + PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { + Err(ConnectorError::NotSupported { + message: "Payout Method Not Supported".to_string(), + connector: "Ebanx", + })? + } } } } @@ -334,10 +337,12 @@ impl<F> TryFrom<&PayoutsRouterData<F>> for EbanxPayoutCancelRequest { .to_owned() .ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?, }), - PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotSupported { - message: "Payout Method Not Supported".to_string(), - connector: "Ebanx", - })?, + PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { + Err(ConnectorError::NotSupported { + message: "Payout Method Not Supported".to_string(), + connector: "Ebanx", + })? + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/loonio.rs b/crates/hyperswitch_connectors/src/connectors/loonio.rs index 1de6f4236d4..ba4f80cc9bb 100644 --- a/crates/hyperswitch_connectors/src/connectors/loonio.rs +++ b/crates/hyperswitch_connectors/src/connectors/loonio.rs @@ -31,6 +31,13 @@ use hyperswitch_domain_models::{ RefundSyncRouterData, RefundsRouterData, }, }; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::{PoFulfill, PoSync}, + types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::types::{PayoutFulfillType, PayoutSyncType}; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, @@ -73,6 +80,11 @@ impl api::Refund for Loonio {} impl api::RefundExecute for Loonio {} impl api::RefundSync for Loonio {} impl api::PaymentToken for Loonio {} +impl api::Payouts for Loonio {} +#[cfg(feature = "payouts")] +impl api::PayoutFulfill for Loonio {} +#[cfg(feature = "payouts")] +impl api::PayoutSync for Loonio {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Loonio @@ -587,6 +599,164 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Loonio { } } +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Loonio { + fn get_headers( + &self, + req: &PayoutsRouterData<PoFulfill>, + 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: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}api/v1/transactions/outgoing/send_to_interac", + self.base_url(connectors), + )) + } + + fn get_request_body( + &self, + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.destination_currency, + )?; + + let connector_router_data = loonio::LoonioRouterData::from((amount, req)); + let connector_req = loonio::LoonioPayoutFulfillRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &PayoutsRouterData<PoFulfill>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> { + let response: loonio::LoonioPayoutFulfillResponse = res + .response + .parse_struct("LoonioPayoutFulfillResponse") + .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) + } +} + +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for Loonio { + fn get_url( + &self, + req: &PayoutsRouterData<PoSync>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let transfer_id = req.request.connector_payout_id.to_owned().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "transaction_id", + }, + )?; + Ok(format!( + "{}api/v1/transactions/{}/details", + connectors.loonio.base_url, transfer_id + )) + } + + fn get_headers( + &self, + req: &PayoutsRouterData<PoSync>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoSync>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Get) + .url(&PayoutSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PayoutSyncType::get_headers(self, req, connectors)?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &PayoutsRouterData<PoSync>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PayoutsRouterData<PoSync>, errors::ConnectorError> { + let response: loonio::LoonioPayoutSyncResponse = res + .response + .parse_struct("LoonioPayoutSyncResponse") + .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 Loonio { async fn verify_webhook_source( diff --git a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs index f1c594145b6..85bbe1ab314 100644 --- a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +#[cfg(feature = "payouts")] +use api_models::payouts::{BankRedirect, PayoutMethodData}; use api_models::webhooks; use common_enums::{enums, Currency}; use common_utils::{id_type, pii::Email, request::Method, types::FloatMajorUnit}; @@ -11,10 +13,17 @@ use hyperswitch_domain_models::{ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::PoFulfill, router_response_types::PayoutsResponseData, + types::PayoutsRouterData, +}; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; +#[cfg(feature = "payouts")] +use crate::types::PayoutsResponseRouterData; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self, PaymentsAuthorizeRequestData, RouterData as _}, @@ -417,3 +426,146 @@ impl From<&LoonioWebhookEventCode> for enums::AttemptStatus { } } } + +// Payout Structures +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +pub struct LoonioPayoutFulfillRequest { + pub currency_code: Currency, + pub customer_profile: LoonioCustomerProfile, + pub amount: FloatMajorUnit, + pub customer_id: id_type::CustomerId, + pub transaction_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub webhook_url: Option<String>, +} + +#[cfg(feature = "payouts")] +impl TryFrom<&LoonioRouterData<&PayoutsRouterData<PoFulfill>>> for LoonioPayoutFulfillRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &LoonioRouterData<&PayoutsRouterData<PoFulfill>>, + ) -> Result<Self, Self::Error> { + match item.router_data.get_payout_method_data()? { + PayoutMethodData::BankRedirect(BankRedirect::Interac(interac_data)) => { + let customer_profile = LoonioCustomerProfile { + first_name: item.router_data.get_billing_first_name()?, + last_name: item.router_data.get_billing_last_name()?, + email: interac_data.email, + }; + + Ok(Self { + currency_code: item.router_data.request.destination_currency, + customer_profile, + amount: item.amount, + customer_id: item.router_data.get_customer_id()?, + transaction_id: item.router_data.connector_request_reference_id.clone(), + webhook_url: item.router_data.request.webhook_url.clone(), + }) + } + PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { + Err(errors::ConnectorError::NotSupported { + message: "Payment Method Not Supported".to_string(), + connector: "Loonio", + })? + } + } + } +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LoonioPayoutFulfillResponse { + pub id: i64, + pub api_transaction_id: String, + #[serde(rename = "type")] + pub transaction_type: String, + pub state: LoonioPayoutStatus, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum LoonioPayoutStatus { + Created, + Prepared, + Pending, + Settled, + Available, + Rejected, + Abandoned, + ConnectedAbandoned, + ConnectedInsufficientFunds, + Failed, + Nsf, + Returned, + Rollback, +} + +#[cfg(feature = "payouts")] +impl From<LoonioPayoutStatus> for enums::PayoutStatus { + fn from(item: LoonioPayoutStatus) -> Self { + match item { + LoonioPayoutStatus::Created | LoonioPayoutStatus::Prepared => Self::Initiated, + LoonioPayoutStatus::Pending => Self::Pending, + LoonioPayoutStatus::Settled | LoonioPayoutStatus::Available => Self::Success, + LoonioPayoutStatus::Rejected + | LoonioPayoutStatus::Abandoned + | LoonioPayoutStatus::ConnectedAbandoned + | LoonioPayoutStatus::ConnectedInsufficientFunds + | LoonioPayoutStatus::Failed + | LoonioPayoutStatus::Nsf + | LoonioPayoutStatus::Returned + | LoonioPayoutStatus::Rollback => Self::Failed, + } + } +} + +#[cfg(feature = "payouts")] +impl<F> TryFrom<PayoutsResponseRouterData<F, LoonioPayoutFulfillResponse>> + for PayoutsRouterData<F> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: PayoutsResponseRouterData<F, LoonioPayoutFulfillResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(PayoutsResponseData { + status: Some(enums::PayoutStatus::from(item.response.state)), + connector_payout_id: Some(item.response.api_transaction_id), + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + error_code: None, + error_message: None, + }), + ..item.data + }) + } +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LoonioPayoutSyncResponse { + pub transaction_id: String, + pub state: LoonioPayoutStatus, +} + +#[cfg(feature = "payouts")] +impl<F> TryFrom<PayoutsResponseRouterData<F, LoonioPayoutSyncResponse>> for PayoutsRouterData<F> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: PayoutsResponseRouterData<F, LoonioPayoutSyncResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(PayoutsResponseData { + status: Some(enums::PayoutStatus::from(item.response.state)), + connector_payout_id: Some(item.response.transaction_id.to_string()), + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + error_code: None, + error_message: None, + }), + ..item.data + }) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 8fe123f5e37..2d7b826e417 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -2458,7 +2458,8 @@ impl TryFrom<api_models::payouts::PayoutMethodData> for NuveiPayoutCardData { expiration_year: card_data.expiry_year, }), api_models::payouts::PayoutMethodData::Bank(_) - | api_models::payouts::PayoutMethodData::Wallet(_) => { + | api_models::payouts::PayoutMethodData::Wallet(_) + | api_models::payouts::PayoutMethodData::BankRedirect(_) => { Err(errors::ConnectorError::NotImplemented( "Selected Payout Method is not implemented for Nuvei".to_string(), ) diff --git a/crates/hyperswitch_connectors/src/connectors/payone/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payone/transformers.rs index 25c0320a5e3..b51bb3d3898 100644 --- a/crates/hyperswitch_connectors/src/connectors/payone/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payone/transformers.rs @@ -139,41 +139,45 @@ impl TryFrom<PayoneRouterData<&PayoutsRouterData<PoFulfill>>> for PayonePayoutFu 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(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()?, - )?, + 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(), + )?, }, - PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { - Err(ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Payone"), - ))? - } - }; + payment_product_id: PaymentProductId::try_from( + card_data.get_card_issuer()?, + )?, + }, + PayoutMethodData::Bank(_) + | PayoutMethodData::Wallet(_) + | PayoutMethodData::BankRedirect(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Payone"), + ))?, + }; Ok(Self { amount_of_money, card_payout_method_specific_input, }) } - PayoutType::Wallet | PayoutType::Bank => Err(ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Payone"), - ))?, + PayoutType::Wallet | PayoutType::Bank | PayoutType::BankRedirect => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Payone"), + ))? + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs index 321aad76551..fc3f6bfdc1a 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs @@ -445,6 +445,13 @@ impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRe } .into()) } + api_models::payouts::PayoutMethodData::BankRedirect(_) => { + Err(errors::ConnectorError::NotSupported { + message: "Payouts via BankRedirect are not supported".to_string(), + connector: "stripe", + } + .into()) + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs index a9655976455..3a3d9ecc728 100644 --- a/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs @@ -413,9 +413,11 @@ impl<F> TryFrom<&WiseRouterData<&PayoutsRouterData<F>>> for WiseRecipientCreateR }?; let payout_type = request.get_payout_type()?; match payout_type { - PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Wise"), - ))?, + PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), + ))? + } PayoutType::Bank => { let account_holder_name = customer_details .ok_or(ConnectorError::MissingRequiredField { @@ -478,9 +480,11 @@ impl<F> TryFrom<&WiseRouterData<&PayoutsRouterData<F>>> for WisePayoutQuoteReque target_currency: request.destination_currency.to_string(), pay_out: WisePayOutOption::default(), }), - PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Wise"), - ))?, + PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), + ))? + } } } } @@ -536,9 +540,11 @@ impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutCreateRequest { details: wise_transfer_details, }) } - PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Wise"), - ))?, + PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), + ))? + } } } } @@ -580,9 +586,11 @@ impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutFulfillRequest { PayoutType::Bank => Ok(Self { fund_type: FundType::default(), }), - PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Wise"), - ))?, + PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), + ))? + } } } } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index be8aee14417..c4b6ceaf3ca 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -3865,7 +3865,6 @@ default_imp_for_payouts!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, - connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -4155,7 +4154,6 @@ default_imp_for_payouts_retrieve!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, - connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, @@ -4447,7 +4445,6 @@ default_imp_for_payouts_fulfill!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, - connectors::Loonio, connectors::Netcetera, connectors::Noon, connectors::Nordea, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 6ef0b64125d..b87d57370f0 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -232,11 +232,13 @@ Never share your secret api keys. Keep them guarded and secure. common_utils::payout_method_utils::CardAdditionalData, common_utils::payout_method_utils::BankAdditionalData, common_utils::payout_method_utils::WalletAdditionalData, + common_utils::payout_method_utils::BankRedirectAdditionalData, common_utils::payout_method_utils::AchBankTransferAdditionalData, common_utils::payout_method_utils::BacsBankTransferAdditionalData, common_utils::payout_method_utils::SepaBankTransferAdditionalData, common_utils::payout_method_utils::PixBankTransferAdditionalData, common_utils::payout_method_utils::PaypalAdditionalData, + common_utils::payout_method_utils::InteracAdditionalData, common_utils::payout_method_utils::VenmoAdditionalData, common_types::payments::SplitPaymentsRequest, common_types::payments::GpayTokenizationData, @@ -661,6 +663,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payouts::CardPayout, api_models::payouts::Wallet, api_models::payouts::Paypal, + api_models::payouts::BankRedirect, + api_models::payouts::Interac, api_models::payouts::Venmo, api_models::payouts::AchBankTransfer, api_models::payouts::BacsBankTransfer, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index f4c1944931d..c4b67a2cd56 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -174,11 +174,13 @@ Never share your secret api keys. Keep them guarded and secure. common_utils::payout_method_utils::CardAdditionalData, common_utils::payout_method_utils::BankAdditionalData, common_utils::payout_method_utils::WalletAdditionalData, + common_utils::payout_method_utils::BankRedirectAdditionalData, common_utils::payout_method_utils::AchBankTransferAdditionalData, common_utils::payout_method_utils::BacsBankTransferAdditionalData, common_utils::payout_method_utils::SepaBankTransferAdditionalData, common_utils::payout_method_utils::PixBankTransferAdditionalData, common_utils::payout_method_utils::PaypalAdditionalData, + common_utils::payout_method_utils::InteracAdditionalData, common_utils::payout_method_utils::VenmoAdditionalData, common_types::payments::SplitPaymentsRequest, common_types::payments::GpayTokenizationData, @@ -630,6 +632,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payouts::CardPayout, api_models::payouts::Wallet, api_models::payouts::Paypal, + api_models::payouts::BankRedirect, + api_models::payouts::Interac, api_models::payouts::Venmo, api_models::payouts::AchBankTransfer, api_models::payouts::BacsBankTransfer, diff --git a/crates/router/src/configs/defaults/payout_required_fields.rs b/crates/router/src/configs/defaults/payout_required_fields.rs index 24c13ec5396..56e975d81cf 100644 --- a/crates/router/src/configs/defaults/payout_required_fields.rs +++ b/crates/router/src/configs/defaults/payout_required_fields.rs @@ -244,6 +244,24 @@ fn get_connector_payment_method_type_fields( ) } + // Bank Redirect + PaymentMethodType::Interac => { + common_fields.extend(get_interac_fields()); + ( + payment_method_type, + ConnectorFields { + fields: HashMap::from([( + connector.into(), + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: common_fields, + }, + )]), + }, + ) + } + _ => ( payment_method_type, ConnectorFields { @@ -375,6 +393,38 @@ fn get_paypal_fields() -> HashMap<String, RequiredFieldInfo> { )]) } +fn get_interac_fields() -> HashMap<String, RequiredFieldInfo> { + HashMap::from([ + ( + "payout_method_data.bank_redirect.interac.email".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.bank_redirect.interac.email".to_string(), + display_name: "email".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_address_first_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "billing_address_last_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ]) +} + fn get_countries_for_connector(connector: PayoutConnectors) -> Vec<CountryAlpha2> { match connector { PayoutConnectors::Adyenplatform => vec![ diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index af091faedcb..8941dea6721 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -4803,6 +4803,12 @@ pub async fn get_bank_from_hs_locker( message: "Expected bank details, found wallet details instead".to_string(), } .into()), + api::PayoutMethodData::BankRedirect(_) => { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Expected bank details, found bank redirect details instead".to_string(), + } + .into()) + } } } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 98888520d59..1b99c1ab337 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -824,6 +824,7 @@ pub enum VaultPayoutMethod { Card(String), Bank(String), Wallet(String), + BankRedirect(String), } #[cfg(feature = "payouts")] @@ -836,6 +837,9 @@ impl Vaultable for api::PayoutMethodData { Self::Card(card) => VaultPayoutMethod::Card(card.get_value1(customer_id)?), Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value1(customer_id)?), Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value1(customer_id)?), + Self::BankRedirect(bank_redirect) => { + VaultPayoutMethod::BankRedirect(bank_redirect.get_value1(customer_id)?) + } }; value1 @@ -852,6 +856,9 @@ impl Vaultable for api::PayoutMethodData { Self::Card(card) => VaultPayoutMethod::Card(card.get_value2(customer_id)?), Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value2(customer_id)?), Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value2(customer_id)?), + Self::BankRedirect(bank_redirect) => { + VaultPayoutMethod::BankRedirect(bank_redirect.get_value2(customer_id)?) + } }; value2 @@ -887,12 +894,95 @@ impl Vaultable for api::PayoutMethodData { let (wallet, supp_data) = api::WalletPayout::from_values(mvalue1, mvalue2)?; Ok((Self::Wallet(wallet), supp_data)) } + ( + VaultPayoutMethod::BankRedirect(mvalue1), + VaultPayoutMethod::BankRedirect(mvalue2), + ) => { + let (bank_redirect, supp_data) = + api::BankRedirectPayout::from_values(mvalue1, mvalue2)?; + Ok((Self::BankRedirect(bank_redirect), supp_data)) + } _ => Err(errors::VaultError::PayoutMethodNotSupported) .attach_printable("Payout method not supported"), } } } +#[cfg(feature = "payouts")] +impl Vaultable for api::BankRedirectPayout { + fn get_value1( + &self, + _customer_id: Option<id_type::CustomerId>, + ) -> CustomResult<String, errors::VaultError> { + let value1 = match self { + Self::Interac(interac_data) => TokenizedBankRedirectSensitiveValues { + email: interac_data.email.clone(), + bank_redirect_type: PaymentMethodType::Interac, + }, + }; + + value1 + .encode_to_string_of_json() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable( + "Failed to encode bank redirect data - TokenizedBankRedirectSensitiveValues", + ) + } + + fn get_value2( + &self, + customer_id: Option<id_type::CustomerId>, + ) -> CustomResult<String, errors::VaultError> { + let value2 = TokenizedBankRedirectInsensitiveValues { customer_id }; + + value2 + .encode_to_string_of_json() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode wallet data value2") + } + + fn from_values( + value1: String, + value2: String, + ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { + let value1: TokenizedBankRedirectSensitiveValues = value1 + .parse_struct("TokenizedBankRedirectSensitiveValues") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Could not deserialize into wallet data value1")?; + + let value2: TokenizedBankRedirectInsensitiveValues = value2 + .parse_struct("TokenizedBankRedirectInsensitiveValues") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Could not deserialize into wallet data value2")?; + + let bank_redirect = match value1.bank_redirect_type { + PaymentMethodType::Interac => Self::Interac(api_models::payouts::Interac { + email: value1.email, + }), + _ => Err(errors::VaultError::PayoutMethodNotSupported) + .attach_printable("Payout method not supported")?, + }; + + let supp_data = SupplementaryVaultData { + customer_id: value2.customer_id, + payment_method_id: None, + }; + + Ok((bank_redirect, supp_data)) + } +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct TokenizedBankRedirectSensitiveValues { + pub email: Email, + pub bank_redirect_type: PaymentMethodType, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct TokenizedBankRedirectInsensitiveValues { + pub customer_id: Option<id_type::CustomerId>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct MockTokenizeDBValue { pub value1: String, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 00bcc7a26f6..e2d6cf65e87 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -377,7 +377,8 @@ pub async fn save_payout_data_to_locker( Some(wallet.to_owned()), api_enums::PaymentMethodType::foreign_from(wallet), ), - payouts::PayoutMethodData::Card(_) => { + payouts::PayoutMethodData::Card(_) + | payouts::PayoutMethodData::BankRedirect(_) => { Err(errors::ApiErrorResponse::InternalServerError)? } } @@ -1533,6 +1534,11 @@ pub async fn get_additional_payout_data( Box::new(wallet_data.to_owned().into()), )) } + api::PayoutMethodData::BankRedirect(bank_redirect_data) => { + Some(payout_additional::AdditionalPayoutMethodData::BankRedirect( + Box::new(bank_redirect_data.to_owned().into()), + )) + } } } diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs index b5a6ac24ca9..2652c14ab88 100644 --- a/crates/router/src/types/api/payouts.rs +++ b/crates/router/src/types/api/payouts.rs @@ -1,10 +1,11 @@ pub use api_models::payouts::{ - AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PaymentMethodTypeInfo, - PayoutActionRequest, PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, - PayoutEnabledPaymentMethodsInfo, PayoutLinkResponse, PayoutListConstraints, - PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutMethodData, - PayoutMethodDataResponse, PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, - PixBankTransfer, RequiredFieldsOverrideRequest, SepaBankTransfer, Wallet as WalletPayout, + AchBankTransfer, BacsBankTransfer, Bank as BankPayout, BankRedirect as BankRedirectPayout, + CardPayout, PaymentMethodTypeInfo, PayoutActionRequest, PayoutAttemptResponse, + PayoutCreateRequest, PayoutCreateResponse, PayoutEnabledPaymentMethodsInfo, PayoutLinkResponse, + PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, + PayoutMethodData, PayoutMethodDataResponse, PayoutRequest, PayoutRetrieveBody, + PayoutRetrieveRequest, PixBankTransfer, RequiredFieldsOverrideRequest, SepaBankTransfer, + Wallet as WalletPayout, }; pub use hyperswitch_domain_models::router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 3eea8b1006e..430fceb3bd9 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1195,6 +1195,9 @@ impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentM api_models::payouts::PayoutMethodData::Bank(bank) => Self::foreign_from(bank), api_models::payouts::PayoutMethodData::Card(_) => Self::Debit, api_models::payouts::PayoutMethodData::Wallet(wallet) => Self::foreign_from(wallet), + api_models::payouts::PayoutMethodData::BankRedirect(bank_redirect) => { + Self::foreign_from(bank_redirect) + } } } } @@ -1221,6 +1224,15 @@ impl ForeignFrom<&api_models::payouts::Wallet> for api_enums::PaymentMethodType } } +#[cfg(feature = "payouts")] +impl ForeignFrom<&api_models::payouts::BankRedirect> for api_enums::PaymentMethodType { + fn foreign_from(value: &api_models::payouts::BankRedirect) -> Self { + match value { + api_models::payouts::BankRedirect::Interac(_) => Self::Interac, + } + } +} + #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentMethod { fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self { @@ -1228,6 +1240,7 @@ impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentM api_models::payouts::PayoutMethodData::Bank(_) => Self::BankTransfer, api_models::payouts::PayoutMethodData::Card(_) => Self::Card, api_models::payouts::PayoutMethodData::Wallet(_) => Self::Wallet, + api_models::payouts::PayoutMethodData::BankRedirect(_) => Self::BankRedirect, } } } @@ -1239,6 +1252,7 @@ impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_models::enums:: api_models::payouts::PayoutMethodData::Bank(_) => Self::Bank, api_models::payouts::PayoutMethodData::Card(_) => Self::Card, api_models::payouts::PayoutMethodData::Wallet(_) => Self::Wallet, + api_models::payouts::PayoutMethodData::BankRedirect(_) => Self::BankRedirect, } } } @@ -1250,6 +1264,7 @@ impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod { api_models::enums::PayoutType::Bank => Self::BankTransfer, api_models::enums::PayoutType::Card => Self::Card, api_models::enums::PayoutType::Wallet => Self::Wallet, + api_models::enums::PayoutType::BankRedirect => Self::BankRedirect, } } } diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 9a85d501056..fa5638d7b47 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -128,6 +128,16 @@ impl AdyenTest { paypal_id: None, }), )), + enums::PayoutType::BankRedirect => { + Some(types::api::PayoutMethodData::BankRedirect( + types::api::payouts::BankRedirectPayout::Interac( + api_models::payouts::Interac { + email: Email::from_str("[email protected]") + .ok()?, + }, + ), + )) + } }, ..Default::default() }) diff --git a/migrations/2025-10-07-100547-0000_add_bank_redirect_in/down.sql b/migrations/2025-10-07-100547-0000_add_bank_redirect_in/down.sql new file mode 100644 index 00000000000..c7c9cbeb401 --- /dev/null +++ b/migrations/2025-10-07-100547-0000_add_bank_redirect_in/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +SELECT 1; \ No newline at end of file diff --git a/migrations/2025-10-07-100547-0000_add_bank_redirect_in/up.sql b/migrations/2025-10-07-100547-0000_add_bank_redirect_in/up.sql new file mode 100644 index 00000000000..b409b7dd402 --- /dev/null +++ b/migrations/2025-10-07-100547-0000_add_bank_redirect_in/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TYPE "PayoutType" ADD VALUE IF NOT EXISTS 'bank_redirect'; \ No newline at end of file
2025-10-07T13:26:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description implement payouts for Loonio ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Create Loonio Payout ``` curl --location 'http://localhost:8080/account/merchant_1759832187/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sCP4vFLQ6aoU7Hi1kFSxUfGZXKkYrRBBlaykRucf8qtPDgCz34JI7EJ7x7ZOt0Up' \ --data '{ "connector_type": "payout_processor", "connector_name": "loonio", "connector_account_details": { "auth_type": "BodyKey", "api_key": "_", "key1": "_" }, "test_mode": false, "disabled": false }' ``` Create a interac Payout ``` curl --location 'http://localhost:8080/payouts/create' \ --header 'x-feature: integ-custom' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_sCP4vFLQ6aoU7Hi1kFSxUfGZXKkYrRBBlaykRucf8qtPDgCz34JI7EJ7x7ZOt0Up' \ --data-raw '{ "amount": 1, "currency": "CAD", "customer_id": "cus_T1nIsYGhYLX9gpGLk5A1", "email": "[email protected]", "name": "Doest John", "phone": "6168205366", "phone_country_code": "+1", "description": "Its my first payout request", "payout_type": "bank_redirect", "payout_method_data": { "bank_redirect": { "interac": { "email": "[email protected]" } } }, "connector": [ "loonio" ], "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "CA", "zip": "94122", "country": "US", "first_name": "Doest", "last_name": "John" }, "phone": { "number": "6168205366", "country_code": "1" } }, "entity_type": "Individual", "recurring": false, "confirm": true, "auto_fulfill": true }' ``` Response ``` { "payout_id": "payout_Wo7WSccu3gsj3nHjAceu", "merchant_id": "merchant_1759832187", "merchant_order_reference_id": null, "amount": 1, "currency": "CAD", "connector": "loonio", "payout_type": "bank_redirect", "payout_method_data": { "bank_redirect": { "email": "ex*****@example.com" } }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "CA", "first_name": "Doest", "last_name": "John", "origin_zip": null }, "phone": { "number": "6168205366", "country_code": "1" }, "email": null }, "auto_fulfill": true, "customer_id": "cus_T1nIsYGhYLX9gpGLk5A1", "customer": { "id": "cus_T1nIsYGhYLX9gpGLk5A1", "name": "John Doe", "email": "[email protected]", "phone": "6168205366", "phone_country_code": "+1" }, "client_secret": "payout_payout_Wo7WSccu3gsj3nHjAceu_secret_R0cRg0Ghrp3E1p111dyu", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "Individual", "recurring": false, "metadata": {}, "merchant_connector_id": "mca_CAgv5aZcOkJDxFyidjhp", "status": "initiated", "error_message": null, "error_code": null, "profile_id": "pro_1NTfzZKyGXpM6RZZna3r", "created": "2025-10-07T11:16:00.091Z", "connector_transaction_id": "payout_Wo7WSccu3gsj3nHjAceu_1", "priority": null, "payout_link": null, "email": "[email protected]", "name": "John Doe", "phone": "6168205366", "phone_country_code": "+1", "unified_code": null, "unified_message": null, "payout_method_id": null } ``` Do sync ``` curl --location 'http://localhost:8080/payouts/payout_Wo7WSccu3gsj3nHjAceu?force_sync=true' \ --header 'api-key: dev_sCP4vFLQ6aoU7Hi1kFSxUfGZXKkYrRBBlaykRucf8qtPDgCz34JI7EJ7x7ZOt0Up' ``` Response ``` { "payout_id": "payout_Wo7WSccu3gsj3nHjAceu", "merchant_id": "merchant_1759832187", "merchant_order_reference_id": null, "amount": 1, "currency": "CAD", "connector": "loonio", "payout_type": "bank_redirect", "payout_method_data": { "bank_redirect": { "email": "ex*****@example.com" } }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "CA", "first_name": "Doest", "last_name": "John", "origin_zip": null }, "phone": { "number": "6168205366", "country_code": "1" }, "email": null }, "auto_fulfill": true, "customer_id": "cus_T1nIsYGhYLX9gpGLk5A1", "customer": { "id": "cus_T1nIsYGhYLX9gpGLk5A1", "name": "John Doe", "email": "[email protected]", "phone": "6168205366", "phone_country_code": "+1" }, "client_secret": "payout_payout_Wo7WSccu3gsj3nHjAceu_secret_R0cRg0Ghrp3E1p111dyu", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "Individual", "recurring": false, "metadata": {}, "merchant_connector_id": "mca_CAgv5aZcOkJDxFyidjhp", "status": "pending", "error_message": null, "error_code": null, "profile_id": "pro_1NTfzZKyGXpM6RZZna3r", "created": "2025-10-07T11:16:00.091Z", "connector_transaction_id": "payout_Wo7WSccu3gsj3nHjAceu_1", "priority": null, "payout_link": null, "email": "[email protected]", "name": "John Doe", "phone": "6168205366", "phone_country_code": "+1", "unified_code": null, "unified_message": null, "payout_method_id": null } ``` We will get pending status, as per doc in sbx we can not fullfill the payouts. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
27a7845a26e37dc160d38641c93a1aea21692395
juspay/hyperswitch
juspay__hyperswitch-9693
Bug: Add support to update card exp in update payment methods api 1. Need support to update card expiry in payments method data of payment methods table using batch pm update API. 2. Need support to pass multiple mca ids for updating payment methods entries.
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 591932c5deb..cfb45ef045c 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -294,6 +294,7 @@ pub struct PaymentMethodRecordUpdateResponse { pub status: common_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub connector_mandate_details: Option<pii::SecretSerdeValue>, + pub updated_payment_method_data: Option<bool>, } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] @@ -2689,7 +2690,9 @@ pub struct UpdatePaymentMethodRecord { pub network_transaction_id: Option<String>, pub line_number: Option<i64>, pub payment_instrument_id: Option<masking::Secret<String>>, - pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + pub merchant_connector_ids: Option<String>, + pub card_expiry_month: Option<masking::Secret<String>>, + pub card_expiry_year: Option<masking::Secret<String>>, } #[derive(Debug, serde::Serialize)] @@ -2701,6 +2704,7 @@ pub struct PaymentMethodUpdateResponse { pub update_status: UpdateStatus, #[serde(skip_serializing_if = "Option::is_none")] pub update_error: Option<String>, + pub updated_payment_method_data: Option<bool>, pub line_number: Option<i64>, } @@ -2841,6 +2845,7 @@ impl From<PaymentMethodUpdateResponseType> for PaymentMethodUpdateResponse { status: Some(res.status), network_transaction_id: res.network_transaction_id, connector_mandate_details: res.connector_mandate_details, + updated_payment_method_data: res.updated_payment_method_data, update_status: UpdateStatus::Success, update_error: None, line_number: record.line_number, @@ -2850,6 +2855,7 @@ impl From<PaymentMethodUpdateResponseType> for PaymentMethodUpdateResponse { status: record.status, network_transaction_id: record.network_transaction_id, connector_mandate_details: None, + updated_payment_method_data: None, update_status: UpdateStatus::Failed, update_error: Some(e), line_number: record.line_number, diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 747c6fdbd39..edadeea7990 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -251,10 +251,11 @@ pub enum PaymentMethodUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<Secret<String>>, }, - ConnectorNetworkTransactionIdStatusAndMandateDetailsUpdate { + PaymentMethodBatchUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, + payment_method_data: Option<Encryption>, }, } @@ -687,13 +688,13 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_payment_method_data: None, scheme: None, }, - PaymentMethodUpdate::ConnectorNetworkTransactionIdStatusAndMandateDetailsUpdate { + PaymentMethodUpdate::PaymentMethodBatchUpdate { connector_mandate_details, network_transaction_id, status, + payment_method_data, } => Self { metadata: None, - payment_method_data: None, last_used_at: None, status, locker_id: None, @@ -709,6 +710,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, + payment_method_data, }, } } diff --git a/crates/payment_methods/src/core/migration.rs b/crates/payment_methods/src/core/migration.rs index ea9b6db1036..c077ddb2cfa 100644 --- a/crates/payment_methods/src/core/migration.rs +++ b/crates/payment_methods/src/core/migration.rs @@ -77,10 +77,10 @@ pub struct PaymentMethodsMigrateForm { pub merchant_connector_ids: Option<text::Text<String>>, } -struct MerchantConnectorValidator; +pub struct MerchantConnectorValidator; impl MerchantConnectorValidator { - fn parse_comma_separated_ids( + pub fn parse_comma_separated_ids( ids_string: &str, ) -> Result<Vec<common_utils::id_type::MerchantConnectorAccountId>, errors::ApiErrorResponse> { diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/router/src/core/payment_methods/migration.rs index d802e432ec1..26a2d1737cb 100644 --- a/crates/router/src/core/payment_methods/migration.rs +++ b/crates/router/src/core/payment_methods/migration.rs @@ -7,12 +7,15 @@ use hyperswitch_domain_models::{ api::ApplicationResponse, errors::api_error_response as errors, merchant_context, payment_methods::PaymentMethodUpdate, }; -use masking::PeekInterface; +use masking::{ExposeInterface, PeekInterface}; +use payment_methods::core::migration::MerchantConnectorValidator; use rdkafka::message::ToBytes; use router_env::logger; -use crate::{core::errors::StorageErrorExt, routes::SessionState}; - +use crate::{ + core::{errors::StorageErrorExt, payment_methods::cards::create_encrypted_data}, + routes::SessionState, +}; type PmMigrationResult<T> = CustomResult<ApplicationResponse<T>, errors::ApiErrorResponse>; #[cfg(feature = "v1")] @@ -62,6 +65,8 @@ pub async fn update_payment_method_record( let payment_method_id = req.payment_method_id.clone(); let network_transaction_id = req.network_transaction_id.clone(); let status = req.status; + let key_manager_state = state.into(); + let mut updated_card_expiry = false; let payment_method = db .find_payment_method( @@ -79,94 +84,143 @@ pub async fn update_payment_method_record( }.into()); } - // Process mandate details when both payment_instrument_id and merchant_connector_id are present - let pm_update = match (&req.payment_instrument_id, &req.merchant_connector_id) { - (Some(payment_instrument_id), Some(merchant_connector_id)) => { + let updated_payment_method_data = match payment_method.payment_method_data.as_ref() { + Some(data) => { + match serde_json::from_value::<pm_api::PaymentMethodsData>( + data.clone().into_inner().expose(), + ) { + Ok(pm_api::PaymentMethodsData::Card(mut card_data)) => { + if let Some(new_month) = &req.card_expiry_month { + card_data.expiry_month = Some(new_month.clone()); + updated_card_expiry = true; + } + + if let Some(new_year) = &req.card_expiry_year { + card_data.expiry_year = Some(new_year.clone()); + updated_card_expiry = true; + } + + if updated_card_expiry { + Some( + create_encrypted_data( + &key_manager_state, + merchant_context.get_merchant_key_store(), + pm_api::PaymentMethodsData::Card(card_data), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method data") + .map(Into::into), + ) + } else { + None + } + } + _ => None, + } + } + None => None, + } + .transpose()?; + + // Process mandate details when both payment_instrument_id and merchant_connector_ids are present + let pm_update = match ( + &req.payment_instrument_id, + &req.merchant_connector_ids.clone(), + ) { + (Some(payment_instrument_id), Some(merchant_connector_ids)) => { + let parsed_mca_ids = + MerchantConnectorValidator::parse_comma_separated_ids(merchant_connector_ids)?; let mandate_details = payment_method .get_common_mandate_reference() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; - let mca = db - .find_by_merchant_connector_account_merchant_id_merchant_connector_id( - &state.into(), - merchant_context.get_merchant_account().get_id(), - merchant_connector_id, - merchant_context.get_merchant_key_store(), - ) - .await - .to_not_found_response( - errors::ApiErrorResponse::MerchantConnectorAccountNotFound { - id: merchant_connector_id.get_string_repr().to_string(), - }, - )?; + let mut existing_payments_mandate = mandate_details + .payments + .clone() + .unwrap_or(PaymentsMandateReference(HashMap::new())); + let mut existing_payouts_mandate = mandate_details + .payouts + .clone() + .unwrap_or(PayoutsMandateReference(HashMap::new())); - let updated_connector_mandate_details = match mca.connector_type { - enums::ConnectorType::PayoutProcessor => { - // Handle PayoutsMandateReference - let mut existing_payouts_mandate = mandate_details - .payouts - .unwrap_or_else(|| PayoutsMandateReference(HashMap::new())); + for merchant_connector_id in parsed_mca_ids { + let mca = db + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &state.into(), + merchant_context.get_merchant_account().get_id(), + &merchant_connector_id, + merchant_context.get_merchant_key_store(), + ) + .await + .to_not_found_response( + errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_connector_id.get_string_repr().to_string(), + }, + )?; - // Create new payout mandate record - let new_payout_record = PayoutsMandateReferenceRecord { - transfer_method_id: Some(payment_instrument_id.peek().to_string()), - }; + match mca.connector_type { + enums::ConnectorType::PayoutProcessor => { + // Handle PayoutsMandateReference + let new_payout_record = PayoutsMandateReferenceRecord { + transfer_method_id: Some(payment_instrument_id.peek().to_string()), + }; - // Check if record exists for this merchant_connector_id - if let Some(existing_record) = - existing_payouts_mandate.0.get_mut(merchant_connector_id) - { - if let Some(transfer_method_id) = &new_payout_record.transfer_method_id { - existing_record.transfer_method_id = Some(transfer_method_id.clone()); + // Check if record exists for this merchant_connector_id + if let Some(existing_record) = + existing_payouts_mandate.0.get_mut(&merchant_connector_id) + { + if let Some(transfer_method_id) = &new_payout_record.transfer_method_id + { + existing_record.transfer_method_id = + Some(transfer_method_id.clone()); + } + } else { + // Insert new record in connector_mandate_details + existing_payouts_mandate + .0 + .insert(merchant_connector_id.clone(), new_payout_record); } - } else { - // Insert new record in connector_mandate_details - existing_payouts_mandate - .0 - .insert(merchant_connector_id.clone(), new_payout_record); } - - // Create updated CommonMandateReference preserving payments section - CommonMandateReference { - payments: mandate_details.payments, - payouts: Some(existing_payouts_mandate), + _ => { + // Handle PaymentsMandateReference + // Check if record exists for this merchant_connector_id + if let Some(existing_record) = + existing_payments_mandate.0.get_mut(&merchant_connector_id) + { + existing_record.connector_mandate_id = + payment_instrument_id.peek().to_string(); + } else { + // Insert new record in connector_mandate_details + existing_payments_mandate.0.insert( + merchant_connector_id.clone(), + PaymentsMandateReferenceRecord { + connector_mandate_id: payment_instrument_id.peek().to_string(), + payment_method_type: None, + original_payment_authorized_amount: None, + original_payment_authorized_currency: None, + mandate_metadata: None, + connector_mandate_status: None, + connector_mandate_request_reference_id: None, + }, + ); + } } } - _ => { - // Handle PaymentsMandateReference - let mut existing_payments_mandate = mandate_details - .payments - .unwrap_or_else(|| PaymentsMandateReference(HashMap::new())); - - // Check if record exists for this merchant_connector_id - if let Some(existing_record) = - existing_payments_mandate.0.get_mut(merchant_connector_id) - { - existing_record.connector_mandate_id = - payment_instrument_id.peek().to_string(); - } else { - // Insert new record in connector_mandate_details - existing_payments_mandate.0.insert( - merchant_connector_id.clone(), - PaymentsMandateReferenceRecord { - connector_mandate_id: payment_instrument_id.peek().to_string(), - payment_method_type: None, - original_payment_authorized_amount: None, - original_payment_authorized_currency: None, - mandate_metadata: None, - connector_mandate_status: None, - connector_mandate_request_reference_id: None, - }, - ); - } + } - // Create updated CommonMandateReference preserving payouts section - CommonMandateReference { - payments: Some(existing_payments_mandate), - payouts: mandate_details.payouts, - } - } + let updated_connector_mandate_details = CommonMandateReference { + payments: if !existing_payments_mandate.0.is_empty() { + Some(existing_payments_mandate) + } else { + mandate_details.payments + }, + payouts: if !existing_payouts_mandate.0.is_empty() { + Some(existing_payouts_mandate) + } else { + mandate_details.payouts + }, }; let connector_mandate_details_value = updated_connector_mandate_details @@ -176,19 +230,25 @@ pub async fn update_payment_method_record( errors::ApiErrorResponse::MandateUpdateFailed })?; - PaymentMethodUpdate::ConnectorNetworkTransactionIdStatusAndMandateDetailsUpdate { + PaymentMethodUpdate::PaymentMethodBatchUpdate { connector_mandate_details: Some(pii::SecretSerdeValue::new( connector_mandate_details_value, )), network_transaction_id, status, + payment_method_data: updated_payment_method_data.clone(), } } _ => { - // Update only network_transaction_id and status - PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { - network_transaction_id, - status, + if updated_payment_method_data.is_some() { + PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: updated_payment_method_data, + } + } else { + PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { + network_transaction_id, + status, + } } } }; @@ -217,6 +277,7 @@ pub async fn update_payment_method_record( connector_mandate_details: response .connector_mandate_details .map(pii::SecretSerdeValue::new), + updated_payment_method_data: Some(updated_card_expiry), }, )) }
2025-10-06T12:49:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We can update card expiry in payments method data of payment methods table using batch pm update API> Added support to pass multiple mca ids for updating payment methods entry. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Curls: ``` curl --location 'http://localhost:8080/payment_methods/update-batch' \ --header 'api-key: test_admin' \ --form 'file=@"/Users/mrudul.vajpayee/Downloads/update_check.csv"' \ --form 'merchant_id="merchant_1759727351"' ``` Response: ``` [{"payment_method_id":"pm_lGbP1ZvFLblFT3DafY5L","status":"active","network_transaction_id":null,"connector_mandate_details":{"payouts":{"mca_5hGHfrn1BYGHjse3VT6f":{"transfer_method_id":"yPNWMjhW4h5LmWJYYY"}},"mca_pwD3i1oyHLxzcu9cq1xR":{"mandate_metadata":null,"payment_method_type":"credit","connector_mandate_id":"yPNWMjhW4h5LmWJYYY","connector_mandate_status":"active","original_payment_authorized_amount":3545,"original_payment_authorized_currency":"EUR","connector_mandate_request_reference_id":"LtkxiLx5mDw1p8uLmD"}},"update_status":"Success","updated_payment_method_data":true,"line_number":1}] ``` File used for above: [update_check.csv](https://github.com/user-attachments/files/22723044/update_check.csv) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c172f03c31e9b29b69490c7c5dfb3b4c78206f79
juspay/hyperswitch
juspay__hyperswitch-9702
Bug: [FEATURE] : Need a framework to test the Req, Res and router data which is made through UCS ### Feature Description There can be possibilities where the req, res or router_data may be differ in case of UCS, so to thoroughly check if these things are correct or not we need a framework. ### Possible Implementation Implement a Shadow run framework for ucs so that we can test it without bringing it on critical path ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index a6b9acd7e3c..6739cde8f8d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2274,6 +2274,33 @@ pub enum GatewaySystem { #[default] Direct, UnifiedConnectorService, + ShadowUnifiedConnectorService, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialOrd, + Ord, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::VariantNames, + strum::EnumIter, + strum::EnumString, + ToSchema, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum ExecutionMode { + #[default] + Primary, + Shadow, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index bbb65e1afc6..e2681057f9f 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -157,6 +157,15 @@ pub const APPLEPAY_VALIDATION_URL: &str = /// Request ID pub const X_REQUEST_ID: &str = "x-request-id"; +/// Flow name +pub const X_FLOW_NAME: &str = "x-flow"; + +/// Connector name +pub const X_CONNECTOR_NAME: &str = "x-connector"; + +/// Unified Connector Service Mode +pub const X_UNIFIED_CONNECTOR_SERVICE_MODE: &str = "x-shadow-mode"; + /// Chat Session ID pub const X_CHAT_SESSION_ID: &str = "x-chat-session-id"; diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index 82028076969..66ae55391df 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -1,5 +1,7 @@ //! Errors and error specific types for universal use +use serde::Serialize; + use crate::types::MinorUnit; /// Custom Result @@ -78,7 +80,7 @@ pub enum ValidationError { } /// Integrity check errors. -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq, Default, Serialize)] pub struct IntegrityCheckError { /// Field names for which integrity check failed! pub field_names: String, diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs index a00b3168abc..5352c81c275 100644 --- a/crates/external_services/src/grpc_client.rs +++ b/crates/external_services/src/grpc_client.rs @@ -162,16 +162,23 @@ pub struct GrpcHeadersUcs { external_vault_proxy_metadata: Option<String>, /// Merchant Reference Id merchant_reference_id: Option<ucs_types::UcsReferenceId>, + + request_id: Option<String>, + + shadow_mode: Option<bool>, } /// Type aliase for GrpcHeaders builder in initial stage -pub type GrpcHeadersUcsBuilderInitial = GrpcHeadersUcsBuilder<((String,), (), (), ())>; +pub type GrpcHeadersUcsBuilderInitial = + GrpcHeadersUcsBuilder<((String,), (), (), (), (Option<String>,), (Option<bool>,))>; /// Type aliase for GrpcHeaders builder in intermediate stage pub type GrpcHeadersUcsBuilderFinal = GrpcHeadersUcsBuilder<( (String,), (LineageIds,), (Option<String>,), (Option<ucs_types::UcsReferenceId>,), + (Option<String>,), + (Option<bool>,), )>; /// struct to represent set of Lineage ids diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs index 582ef85d729..b0799ae4ec4 100644 --- a/crates/external_services/src/grpc_client/unified_connector_service.rs +++ b/crates/external_services/src/grpc_client/unified_connector_service.rs @@ -456,6 +456,23 @@ pub fn build_unified_connector_service_grpc_headers( ); }; + if let Some(request_id) = grpc_headers.request_id { + metadata.append( + common_utils_consts::X_REQUEST_ID, + parse(common_utils_consts::X_REQUEST_ID, &request_id)?, + ); + }; + + if let Some(shadow_mode) = grpc_headers.shadow_mode { + metadata.append( + common_utils_consts::X_UNIFIED_CONNECTOR_SERVICE_MODE, + parse( + common_utils_consts::X_UNIFIED_CONNECTOR_SERVICE_MODE, + &shadow_mode.to_string(), + )?, + ); + } + if let Err(err) = grpc_headers .tenant_id .parse() diff --git a/crates/external_services/src/http_client/client.rs b/crates/external_services/src/http_client/client.rs index 633634b6539..1f88f59507b 100644 --- a/crates/external_services/src/http_client/client.rs +++ b/crates/external_services/src/http_client/client.rs @@ -29,7 +29,8 @@ pub fn create_client( } logger::debug!("Creating HTTP client with mutual TLS (client cert + key)"); - let client_builder = get_client_builder(proxy_config)?; + let client_builder = + apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config); let identity = create_identity_from_certificate_and_key( encoded_certificate.clone(), @@ -56,7 +57,9 @@ pub fn create_client( let cert = reqwest::Certificate::from_pem(pem.as_bytes()) .change_context(HttpClientError::ClientConstructionFailed) .attach_printable("Failed to parse CA certificate PEM block")?; - let client_builder = get_client_builder(proxy_config)?.add_root_certificate(cert); + let client_builder = + apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config) + .add_root_certificate(cert); return client_builder .use_rustls_tls() .build() @@ -145,10 +148,32 @@ pub fn create_certificate( .change_context(HttpClientError::CertificateDecodeFailed) } +fn apply_mitm_certificate( + mut client_builder: reqwest::ClientBuilder, + proxy_config: &Proxy, +) -> reqwest::ClientBuilder { + if let Some(mitm_ca_cert) = &proxy_config.mitm_ca_certificate { + let pem = mitm_ca_cert.clone().expose().replace("\\r\\n", "\n"); + match reqwest::Certificate::from_pem(pem.as_bytes()) { + Ok(cert) => { + logger::debug!("Successfully added MITM CA certificate"); + client_builder = client_builder.add_root_certificate(cert); + } + Err(err) => { + logger::error!( + "Failed to parse MITM CA certificate: {}, continuing without MITM support", + err + ); + } + } + } + client_builder +} + fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, HttpClientError> { Ok(DEFAULT_CLIENT .get_or_try_init(|| { - get_client_builder(proxy_config)? + apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config) .build() .change_context(HttpClientError::ClientConstructionFailed) .attach_printable("Failed to construct base client") diff --git a/crates/hyperswitch_domain_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rs index b80e50b5b46..ecfd7f34694 100644 --- a/crates/hyperswitch_domain_models/src/mandates.rs +++ b/crates/hyperswitch_domain_models/src/mandates.rs @@ -56,7 +56,7 @@ pub struct MandateAmountData { // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates -#[derive(Default, Eq, PartialEq, Debug, Clone)] +#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Serialize)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, diff --git a/crates/hyperswitch_domain_models/src/payment_address.rs b/crates/hyperswitch_domain_models/src/payment_address.rs index 176bef0c88b..4240009931c 100644 --- a/crates/hyperswitch_domain_models/src/payment_address.rs +++ b/crates/hyperswitch_domain_models/src/payment_address.rs @@ -1,6 +1,6 @@ use crate::address::Address; -#[derive(Clone, Default, Debug)] +#[derive(Clone, Default, Debug, serde::Serialize)] pub struct PaymentAddress { shipping: Option<Address>, billing: Option<Address>, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 241523db118..80b2fd89d31 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -51,7 +51,7 @@ pub enum ExternalVaultPaymentMethodData { VaultToken(VaultToken), } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub enum ApplePayFlow { Simplified(api_models::payments::PaymentProcessingDetails), Manual, diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index a01efdf0749..80c671c0978 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -849,7 +849,7 @@ impl PaymentIntent { } #[cfg(feature = "v1")] -#[derive(Default, Debug, Clone)] +#[derive(Default, Debug, Clone, serde::Serialize)] pub struct HeaderPayload { pub payment_confirm_source: Option<common_enums::PaymentSource>, pub client_source: Option<String>, @@ -879,7 +879,7 @@ pub struct ClickToPayMetaData { // TODO: uncomment fields as necessary #[cfg(feature = "v2")] -#[derive(Default, Debug, Clone)] +#[derive(Default, Debug, Clone, serde::Serialize)] pub struct HeaderPayload { /// The source with which the payment is confirmed. pub payment_confirm_source: Option<common_enums::PaymentSource>, diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index 5f942e83b3d..d0bffe88882 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -9,6 +9,7 @@ use common_utils::{ }; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; +use serde::{Deserialize, Serialize}; use crate::{ network_tokenization::NetworkTokenNumber, payment_address::PaymentAddress, payment_method_data, @@ -23,7 +24,7 @@ use crate::{ router_flow_types, router_request_types, router_response_types, }; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct RouterData<Flow, Request, Response> { pub flow: PhantomData<Flow>, pub merchant_id: id_type::MerchantId, @@ -118,7 +119,7 @@ pub struct RouterData<Flow, Request, Response> { pub is_payment_id_from_merchant: Option<bool>, } -#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct L2L3Data { pub order_date: Option<time::PrimitiveDateTime>, pub tax_status: Option<common_enums::TaxStatus>, @@ -140,7 +141,7 @@ pub struct L2L3Data { } // Different patterns of authentication. -#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { TemporaryAuth, @@ -263,19 +264,19 @@ impl ConnectorAuthType { } } -#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] +#[derive(Deserialize, Serialize, Debug, Clone)] pub struct AccessTokenAuthenticationResponse { pub code: Secret<String>, pub expires: i64, } -#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] +#[derive(Deserialize, Serialize, Debug, Clone)] pub struct AccessToken { pub token: Secret<String>, pub expires: i64, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub enum PaymentMethodToken { Token(Secret<String>), ApplePayDecrypt(Box<common_payment_types::ApplePayPredecryptData>), @@ -283,7 +284,7 @@ pub enum PaymentMethodToken { PazeDecrypt(Box<PazeDecryptedData>), } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayPredecryptDataInternal { pub application_primary_account_number: cards::CardNumber, @@ -295,7 +296,7 @@ pub struct ApplePayPredecryptDataInternal { pub payment_data: ApplePayCryptogramDataInternal, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayCryptogramDataInternal { pub online_payment_cryptogram: Secret<String>, @@ -365,7 +366,7 @@ impl ApplePayPredecryptDataInternal { } } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPredecryptDataInternal { pub message_expiration: String, @@ -375,7 +376,7 @@ pub struct GooglePayPredecryptDataInternal { pub payment_method_details: GooglePayPaymentMethodDetails, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPaymentMethodDetails { pub auth_method: common_enums::enums::GooglePayAuthMethod, @@ -387,7 +388,7 @@ pub struct GooglePayPaymentMethodDetails { pub card_network: Option<String>, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeDecryptedData { pub client_id: Secret<String>, @@ -400,7 +401,7 @@ pub struct PazeDecryptedData { pub eci: Option<String>, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeToken { pub payment_token: NetworkTokenNumber, @@ -409,7 +410,7 @@ pub struct PazeToken { pub payment_account_reference: Secret<String>, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeDynamicData { pub dynamic_data_value: Option<Secret<String>>, @@ -417,7 +418,7 @@ pub struct PazeDynamicData { pub dynamic_data_expiration: Option<String>, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeAddress { pub name: Option<Secret<String>>, @@ -430,7 +431,7 @@ pub struct PazeAddress { pub country_code: Option<common_enums::enums::CountryAlpha2>, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeConsumer { // This is consumer data not customer data. @@ -443,14 +444,14 @@ pub struct PazeConsumer { pub language_code: Option<String>, } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazePhoneNumber { pub country_code: Secret<String>, pub phone_number: Secret<String>, } -#[derive(Debug, Default, Clone)] +#[derive(Debug, Default, Clone, Serialize)] pub struct RecurringMandatePaymentData { pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe pub original_payment_authorized_amount: Option<i64>, @@ -458,13 +459,13 @@ pub struct RecurringMandatePaymentData { pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentMethodBalance { pub amount: MinorUnit, pub currency: common_enums::enums::Currency, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConnectorResponseData { pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>, extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>, @@ -504,7 +505,7 @@ impl ConnectorResponseData { } } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub enum AdditionalPaymentMethodConnectorResponse { Card { /// Details regarding the authentication details of the connector, if this is a 3ds payment. @@ -521,19 +522,19 @@ pub enum AdditionalPaymentMethodConnectorResponse { }, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct ExtendedAuthorizationResponseData { pub extended_authentication_applied: Option<primitive_wrappers::ExtendedAuthorizationAppliedBool>, pub capture_before: Option<time::PrimitiveDateTime>, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct KlarnaSdkResponse { pub payment_type: Option<String>, } -#[derive(Clone, Debug, serde::Serialize)] +#[derive(Clone, Debug, Serialize)] pub struct ErrorResponse { pub code: String, pub message: String, diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 87cf479339c..995fd9f2f38 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -23,7 +23,7 @@ use crate::{ router_flow_types as flows, router_response_types as response_types, vault::PaymentMethodVaultingData, }; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsAuthorizeData { pub payment_method_data: PaymentMethodData, /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) @@ -92,7 +92,7 @@ pub struct PaymentsAuthorizeData { pub mit_category: Option<common_enums::MitCategory>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct ExternalVaultProxyPaymentsData { pub payment_method_data: ExternalVaultPaymentMethodData, /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) @@ -191,7 +191,7 @@ impl }) } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsPostSessionTokensData { // amount here would include amount, surcharge_amount and shipping_cost pub amount: MinorUnit, @@ -208,13 +208,13 @@ pub struct PaymentsPostSessionTokensData { pub router_return_url: Option<String>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsUpdateMetadataData { pub metadata: pii::SecretSerdeValue, pub connector_transaction_id: String, } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize)] pub struct AuthoriseIntegrityObject { /// Authorise amount pub amount: MinorUnit, @@ -222,7 +222,7 @@ pub struct AuthoriseIntegrityObject { pub currency: storage_enums::Currency, } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize)] pub struct SyncIntegrityObject { /// Sync amount pub amount: Option<MinorUnit>, @@ -230,7 +230,7 @@ pub struct SyncIntegrityObject { pub currency: Option<storage_enums::Currency>, } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, Serialize)] pub struct PaymentsCaptureData { pub amount_to_capture: i64, pub currency: storage_enums::Currency, @@ -250,7 +250,7 @@ pub struct PaymentsCaptureData { pub webhook_url: Option<String>, } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize)] pub struct CaptureIntegrityObject { /// capture amount pub capture_amount: Option<MinorUnit>, @@ -258,7 +258,7 @@ pub struct CaptureIntegrityObject { pub currency: storage_enums::Currency, } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, Serialize)] pub struct PaymentsIncrementalAuthorizationData { pub total_amount: i64, pub additional_amount: i64, @@ -268,13 +268,13 @@ pub struct PaymentsIncrementalAuthorizationData { pub connector_meta: Option<serde_json::Value>, } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, Serialize)] pub struct MultipleCaptureRequestData { pub capture_sequence: i16, pub capture_reference: String, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct AuthorizeSessionTokenData { pub amount_to_capture: Option<i64>, pub currency: storage_enums::Currency, @@ -282,7 +282,7 @@ pub struct AuthorizeSessionTokenData { pub amount: Option<i64>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct ConnectorCustomerData { pub description: Option<String>, pub email: Option<pii::Email>, @@ -407,7 +407,7 @@ impl TryFrom<&RouterData<flows::Session, PaymentsSessionData, response_types::Pa } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentMethodTokenizationData { pub payment_method_data: PaymentMethodData, pub browser_info: Option<BrowserInformation>, @@ -513,7 +513,7 @@ impl TryFrom<ExternalVaultProxyPaymentsData> for PaymentMethodTokenizationData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct CreateOrderRequestData { pub minor_amount: MinorUnit, pub currency: storage_enums::Currency, @@ -541,7 +541,7 @@ impl TryFrom<ExternalVaultProxyPaymentsData> for CreateOrderRequestData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsPreProcessingData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, @@ -570,7 +570,7 @@ pub struct PaymentsPreProcessingData { pub is_stored_credential: Option<bool>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct GiftCardBalanceCheckRequestData { pub payment_method_data: PaymentMethodData, pub currency: Option<storage_enums::Currency>, @@ -610,7 +610,7 @@ impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsPreAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, @@ -649,7 +649,7 @@ impl TryFrom<PaymentsAuthorizeData> for PaymentsPreAuthenticateData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, @@ -688,7 +688,7 @@ impl TryFrom<PaymentsAuthorizeData> for PaymentsAuthenticateData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsPostAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, @@ -760,7 +760,7 @@ impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsPostProcessingData { pub payment_method_data: PaymentMethodData, pub customer_id: Option<id_type::CustomerId>, @@ -798,7 +798,7 @@ impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsRes }) } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct CompleteAuthorizeData { pub payment_method_data: Option<PaymentMethodData>, pub amount: i64, @@ -827,13 +827,13 @@ pub struct CompleteAuthorizeData { pub is_stored_credential: Option<bool>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct CompleteAuthorizeRedirectResponse { pub params: Option<Secret<String>>, pub payload: Option<pii::SecretSerdeValue>, } -#[derive(Debug, Default, Clone)] +#[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsSyncData { //TODO : add fields based on the connector requirements pub connector_transaction_id: ResponseId, @@ -852,14 +852,14 @@ pub struct PaymentsSyncData { pub setup_future_usage: Option<storage_enums::FutureUsage>, } -#[derive(Debug, Default, Clone)] +#[derive(Debug, Default, Clone, Serialize)] pub enum SyncRequestType { MultipleCaptureSync(Vec<String>), #[default] SinglePaymentSync, } -#[derive(Debug, Default, Clone)] +#[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsCancelData { pub amount: Option<i64>, pub currency: Option<storage_enums::Currency>, @@ -876,7 +876,7 @@ pub struct PaymentsCancelData { pub capture_method: Option<storage_enums::CaptureMethod>, } -#[derive(Debug, Default, Clone)] +#[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsCancelPostCaptureData { pub currency: Option<storage_enums::Currency>, pub connector_transaction_id: String, @@ -898,7 +898,7 @@ pub struct PaymentsApproveData { pub currency: Option<storage_enums::Currency>, } -#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Default, Serialize, serde::Deserialize)] pub struct BrowserInformation { pub color_depth: Option<u8>, pub java_enabled: Option<bool>, @@ -984,7 +984,7 @@ impl ResponseId { } } -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, serde::Deserialize, Serialize)] pub struct SurchargeDetails { /// original_amount pub original_amount: MinorUnit, @@ -1049,7 +1049,7 @@ impl } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct AuthenticationData { pub eci: Option<String>, pub cavv: Secret<String>, @@ -1129,18 +1129,18 @@ pub struct ChargeRefunds { pub options: ChargeRefundsOptions, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub enum ChargeRefundsOptions { Destination(DestinationChargeRefund), Direct(DirectChargeRefund), } -#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub struct DirectChargeRefund { pub revert_platform_fee: bool, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub struct DestinationChargeRefund { pub revert_platform_fee: bool, pub revert_transfer: bool, @@ -1310,7 +1310,7 @@ pub struct RetrieveFileRequestData { } #[serde_as] -#[derive(Clone, Debug, serde::Serialize)] +#[derive(Clone, Debug, Serialize)] pub struct UploadFileRequestData { pub file_key: String, #[serde(skip)] @@ -1366,7 +1366,7 @@ pub struct MandateRevokeRequestData { pub connector_mandate_id: Option<String>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct PaymentsSessionData { pub amount: i64, pub currency: common_enums::Currency, @@ -1395,7 +1395,7 @@ pub struct PaymentsTaxCalculationData { pub shipping_address: address::Address, } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, Serialize)] pub struct SdkPaymentsSessionUpdateData { pub order_tax_amount: MinorUnit, // amount here would include amount, surcharge_amount, order_tax_amount and shipping_cost @@ -1407,7 +1407,7 @@ pub struct SdkPaymentsSessionUpdateData { pub shipping_cost: Option<MinorUnit>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct SetupMandateRequestData { pub currency: storage_enums::Currency, pub payment_method_data: PaymentMethodData, diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index 3481a61dfb0..5b50037b617 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -10,6 +10,7 @@ pub use disputes::{ AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, SubmitEvidenceResponse, }; +use serde::Serialize; use crate::{ errors::api_error_response::ApiErrorResponse, @@ -24,7 +25,7 @@ pub struct RefundsResponseData { // pub amount_received: Option<i32>, // Calculation for amount received not in place yet } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub struct ConnectorCustomerResponseData { pub connector_customer_id: String, pub name: Option<String>, @@ -51,7 +52,7 @@ impl ConnectorCustomerResponseData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub enum PaymentsResponseData { TransactionResponse { resource_id: ResponseId, @@ -123,7 +124,7 @@ pub struct TaxCalculationResponseData { pub order_tax_amount: MinorUnit, } -#[derive(serde::Serialize, Debug, Clone)] +#[derive(Serialize, Debug, Clone)] pub struct MandateReference { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, @@ -131,7 +132,7 @@ pub struct MandateReference { pub connector_mandate_request_reference_id: Option<String>, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub enum CaptureSyncResponse { Success { resource_id: ResponseId, @@ -282,13 +283,13 @@ impl PaymentsResponseData { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub enum PreprocessingResponseId { PreProcessingId(String), ConnectorTransactionId(String), } -#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Eq, PartialEq, Clone, Serialize, serde::Deserialize)] pub enum RedirectForm { Form { endpoint: String, diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index 5003fdba1c7..6b9203a7363 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -399,6 +399,12 @@ pub struct Proxy { /// A comma-separated list of hosts that should bypass the proxy. pub bypass_proxy_hosts: Option<String>, + + /// The CA certificate used for man-in-the-middle (MITM) proxying, if enabled. + pub mitm_ca_certificate: Option<masking::Secret<String>>, + + /// Whether man-in-the-middle (MITM) proxying is enabled. + pub mitm_enabled: Option<bool>, } impl Default for Proxy { @@ -408,6 +414,8 @@ impl Default for Proxy { https_url: Default::default(), idle_pool_connection_timeout: Some(90), bypass_proxy_hosts: Default::default(), + mitm_ca_certificate: None, + mitm_enabled: None, } } } diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 37b551081ce..0f59774c6d6 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -591,5 +591,6 @@ pub(crate) async fn fetch_raw_secrets( proxy_status_mapping: conf.proxy_status_mapping, internal_services: conf.internal_services, superposition, + comparison_service: conf.comparison_service, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 28b21cc7e0c..743c308192d 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -7,7 +7,11 @@ use std::{ #[cfg(feature = "olap")] use analytics::{opensearch::OpenSearchConfig, ReportConfig}; use api_models::enums; -use common_utils::{ext_traits::ConfigExt, id_type, types::user::EmailThemeConfig}; +use common_utils::{ + ext_traits::ConfigExt, + id_type, + types::{user::EmailThemeConfig, Url}, +}; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] @@ -172,6 +176,7 @@ pub struct Settings<S: SecretState> { pub superposition: SecretStateContainer<SuperpositionClientConfig, S>, pub proxy_status_mapping: ProxyStatusMapping, pub internal_services: InternalServicesConfig, + pub comparison_service: Option<ComparisonServiceConfig>, } #[derive(Debug, Deserialize, Clone, Default)] @@ -200,6 +205,13 @@ pub struct CloneConnectorAllowlistConfig { pub connector_names: HashSet<enums::Connector>, } +#[derive(Debug, Deserialize, Clone)] +pub struct ComparisonServiceConfig { + pub url: Url, + pub enabled: bool, + pub timeout_secs: Option<u64>, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct Platform { pub enabled: bool, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0b9f7de40d4..e802064730a 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -36,7 +36,7 @@ use api_models::{ mandates::RecurringDetails, payments::{self as payments_api}, }; -pub use common_enums::enums::{CallConnectorAction, GatewaySystem}; +pub use common_enums::enums::{CallConnectorAction, ExecutionMode, GatewaySystem}; use common_types::payments as common_payments_types; use common_utils::{ ext_traits::{AsyncExt, StringExt}, @@ -96,8 +96,12 @@ use self::{ #[cfg(feature = "v1")] use super::unified_connector_service::update_gateway_system_in_feature_metadata; use super::{ - errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData, - unified_connector_service::should_call_unified_connector_service, + errors::StorageErrorExt, + payment_methods::surcharge_decision_configs, + routing::TransactionData, + unified_connector_service::{ + send_comparison_data, should_call_unified_connector_service, ComparisonData, + }, }; #[cfg(feature = "v1")] use crate::core::debit_routing; @@ -456,7 +460,7 @@ where // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, - FData: Send + Sync + Clone, + FData: Send + Sync + Clone + serde::Serialize, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); @@ -534,7 +538,7 @@ where #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] -pub async fn payments_operation_core<F, Req, Op, FData, D>( +pub async fn payments_operation_core<'a, F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, @@ -547,7 +551,7 @@ pub async fn payments_operation_core<F, Req, Op, FData, D>( header_payload: HeaderPayload, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where - F: Send + Clone + Sync, + F: Send + Clone + Sync + 'static + 'a, Req: Authenticate + Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, @@ -562,7 +566,7 @@ where // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, - FData: Send + Sync + Clone + router_types::Capturable, + FData: Send + Sync + Clone + router_types::Capturable + 'static + 'a + serde::Serialize, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); @@ -1242,8 +1246,9 @@ where RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api - dyn api::Connector: - services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, + dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData> + + Send + + Sync, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, @@ -2087,7 +2092,7 @@ pub async fn call_surcharge_decision_management_for_session_flow( #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] -pub async fn payments_core<F, Res, Req, Op, FData, D>( +pub async fn payments_core<'a, F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, @@ -2100,8 +2105,8 @@ pub async fn payments_core<F, Res, Req, Op, FData, D>( header_payload: HeaderPayload, ) -> RouterResponse<Res> where - F: Send + Clone + Sync, - FData: Send + Sync + Clone + router_types::Capturable, + F: Send + Clone + Sync + 'static + 'a, + FData: Send + Sync + Clone + router_types::Capturable + 'static + 'a + serde::Serialize, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, Req: Debug + Authenticate + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, @@ -2109,7 +2114,6 @@ where // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, - // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, @@ -2671,7 +2675,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, D>( where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, - FData: Send + Sync + Clone, + FData: Send + Sync + Clone + serde::Serialize, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> @@ -3903,8 +3907,9 @@ where D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api - dyn api::Connector: - services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, + dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData> + + Send + + Sync, { let add_access_token_result = router_data .add_access_token( @@ -4081,12 +4086,13 @@ pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>( )> where F: Send + Clone + Sync, - RouterDReq: Send + Sync, + RouterDReq: Send + Clone + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, - RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: + Feature<F, RouterDReq> + Send + Clone, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, @@ -4220,150 +4226,497 @@ where #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] -pub async fn decide_unified_connector_service_call<F, RouterDReq, ApiRequest, D>( - state: &SessionState, +pub async fn decide_unified_connector_service_call<'a, F, RouterDReq, ApiRequest, D>( + state: &'a SessionState, req_state: ReqState, - merchant_context: &domain::MerchantContext, + merchant_context: &'a domain::MerchantContext, connector: api::ConnectorData, - operation: &BoxedOperation<'_, F, ApiRequest, D>, - payment_data: &mut D, + operation: &'a BoxedOperation<'a, F, ApiRequest, D>, + payment_data: &'a mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, - validate_result: &operations::ValidateResult, + validate_result: &'a operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, - business_profile: &domain::Profile, + business_profile: &'a domain::Profile, is_retry_payment: bool, all_keys_required: Option<bool>, merchant_connector_account: helpers::MerchantConnectorAccountType, - mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, tokenization_action: TokenizationAction, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, )> where - F: Send + Clone + Sync, - RouterDReq: Send + Sync, + F: Send + Clone + Sync + 'static + 'a, + RouterDReq: Send + Sync + Clone + 'static + 'a + serde::Serialize, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, - RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: + Feature<F, RouterDReq> + Send + Clone + serde::Serialize, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { - record_time_taken_with(|| async { - if !matches!( - call_connector_action, - CallConnectorAction::UCSHandleResponse(_) - ) && !matches!( - call_connector_action, - CallConnectorAction::HandleResponse(_), - ) && should_call_unified_connector_service( - state, - merchant_context, - &router_data, - Some(payment_data), - ) - .await? - { - router_env::logger::info!( - "Processing payment through UCS gateway system - payment_id={}, attempt_id={}", - payment_data - .get_payment_intent() - .payment_id - .get_string_repr(), - payment_data.get_payment_attempt().attempt_id - ); - if should_add_task_to_process_tracker(payment_data) { - operation - .to_domain()? - .add_task_to_process_tracker( - state, - payment_data.get_payment_attempt(), - validate_result.requeue, - schedule_time, - ) - .await - .map_err(|error| logger::error!(process_tracker_error=?error)) - .ok(); - } + let execution_path = should_call_unified_connector_service( + state, + merchant_context, + &router_data, + Some(payment_data), + ) + .await?; - // Update feature metadata to track UCS usage for stickiness - update_gateway_system_in_feature_metadata( - payment_data, - GatewaySystem::UnifiedConnectorService, - )?; + let is_handle_response_action = matches!( + call_connector_action, + CallConnectorAction::UCSHandleResponse(_) | CallConnectorAction::HandleResponse(_) + ); - (_, *payment_data) = operation - .to_update_tracker()? - .update_trackers( + record_time_taken_with(|| async { + match (execution_path, is_handle_response_action) { + // Process through UCS when system is UCS and not handling response + (GatewaySystem::UnifiedConnectorService, false) => { + process_through_ucs( state, req_state, - payment_data.clone(), - customer.clone(), - merchant_context.get_merchant_account().storage_scheme, - None, - merchant_context.get_merchant_key_store(), + merchant_context, + operation, + payment_data, + customer, + validate_result, + schedule_time, + header_payload, frm_suggestion, - header_payload.clone(), + business_profile, + merchant_connector_account, + router_data, ) - .await?; - let lineage_ids = grpc_client::LineageIds::new( - business_profile.merchant_id.clone(), - business_profile.get_id().clone(), - ); - router_data - .call_unified_connector_service( + .await + } + + // Process through Direct gateway + (GatewaySystem::Direct, _) | (GatewaySystem::UnifiedConnectorService, true) => { + process_through_direct( state, - &header_payload, - lineage_ids, - merchant_connector_account.clone(), + req_state, merchant_context, + connector, + operation, + payment_data, + customer, + call_connector_action, + validate_result, + schedule_time, + header_payload, + frm_suggestion, + business_profile, + is_retry_payment, + all_keys_required, + merchant_connector_account, + router_data, + tokenization_action, ) - .await?; + .await + } - Ok((router_data, merchant_connector_account)) - } else { - router_env::logger::info!( - "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", - payment_data - .get_payment_intent() - .payment_id - .get_string_repr(), - payment_data.get_payment_attempt().attempt_id - ); + // Process through Direct with Shadow UCS + (GatewaySystem::ShadowUnifiedConnectorService, _) => { + process_through_direct_with_shadow_unified_connector_service( + state, + req_state, + merchant_context, + connector, + operation, + payment_data, + customer, + call_connector_action, + validate_result, + schedule_time, + header_payload, + frm_suggestion, + business_profile, + is_retry_payment, + all_keys_required, + merchant_connector_account, + router_data, + tokenization_action, + ) + .await + } + } + }) + .await +} - // Update feature metadata to track Direct routing usage for stickiness - update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?; +#[cfg(feature = "v1")] +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +// Helper function to process through UCS +async fn process_through_ucs<'a, F, RouterDReq, ApiRequest, D>( + state: &'a SessionState, + req_state: ReqState, + merchant_context: &'a domain::MerchantContext, + operation: &'a BoxedOperation<'a, F, ApiRequest, D>, + payment_data: &'a mut D, + customer: &Option<domain::Customer>, + validate_result: &'a operations::ValidateResult, + schedule_time: Option<time::PrimitiveDateTime>, + header_payload: HeaderPayload, + frm_suggestion: Option<storage_enums::FrmSuggestion>, + business_profile: &'a domain::Profile, + merchant_connector_account: helpers::MerchantConnectorAccountType, + mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, +) -> RouterResult<( + RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + helpers::MerchantConnectorAccountType, +)> +where + F: Send + Clone + Sync + 'static + 'a, + RouterDReq: Send + Sync + Clone + 'static + 'a + serde::Serialize, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, + D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: + Feature<F, RouterDReq> + Send + Clone + serde::Serialize, + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, +{ + router_env::logger::info!( + "Processing payment through UCS gateway system - payment_id={}, attempt_id={}", + payment_data + .get_payment_intent() + .payment_id + .get_string_repr(), + payment_data.get_payment_attempt().attempt_id + ); - call_connector_service( + // Add task to process tracker if needed + if should_add_task_to_process_tracker(payment_data) { + operation + .to_domain()? + .add_task_to_process_tracker( state, - req_state, - merchant_context, - connector, - operation, - payment_data, - customer, - call_connector_action, - validate_result, + payment_data.get_payment_attempt(), + validate_result.requeue, schedule_time, - header_payload, - frm_suggestion, - business_profile, - is_retry_payment, - all_keys_required, - merchant_connector_account, - router_data, - tokenization_action, ) .await - } - }) + .map_err(|error| logger::error!(process_tracker_error=?error)) + .ok(); + } + + // Update feature metadata to track UCS usage for stickiness + update_gateway_system_in_feature_metadata( + payment_data, + GatewaySystem::UnifiedConnectorService, + )?; + + // Update trackers + (_, *payment_data) = operation + .to_update_tracker()? + .update_trackers( + state, + req_state, + payment_data.clone(), + customer.clone(), + merchant_context.get_merchant_account().storage_scheme, + None, + merchant_context.get_merchant_key_store(), + frm_suggestion, + header_payload.clone(), + ) + .await?; + + // Call UCS + let lineage_ids = grpc_client::LineageIds::new( + business_profile.merchant_id.clone(), + business_profile.get_id().clone(), + ); + + router_data + .call_unified_connector_service( + state, + &header_payload, + lineage_ids, + merchant_connector_account.clone(), + merchant_context, + ExecutionMode::Primary, // UCS is called in primary mode + ) + .await?; + + Ok((router_data, merchant_connector_account)) +} + +#[cfg(feature = "v1")] +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +// Helper function to process through Direct gateway +async fn process_through_direct<'a, F, RouterDReq, ApiRequest, D>( + state: &'a SessionState, + req_state: ReqState, + merchant_context: &'a domain::MerchantContext, + connector: api::ConnectorData, + operation: &'a BoxedOperation<'a, F, ApiRequest, D>, + payment_data: &'a mut D, + customer: &Option<domain::Customer>, + call_connector_action: CallConnectorAction, + validate_result: &'a operations::ValidateResult, + schedule_time: Option<time::PrimitiveDateTime>, + header_payload: HeaderPayload, + frm_suggestion: Option<storage_enums::FrmSuggestion>, + business_profile: &'a domain::Profile, + is_retry_payment: bool, + all_keys_required: Option<bool>, + merchant_connector_account: helpers::MerchantConnectorAccountType, + router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + tokenization_action: TokenizationAction, +) -> RouterResult<( + RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + helpers::MerchantConnectorAccountType, +)> +where + F: Send + Clone + Sync + 'static + 'a, + RouterDReq: Send + Sync + Clone + 'static + 'a + serde::Serialize, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, + D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: + Feature<F, RouterDReq> + Send + Clone + serde::Serialize, + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, +{ + router_env::logger::info!( + "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", + payment_data + .get_payment_intent() + .payment_id + .get_string_repr(), + payment_data.get_payment_attempt().attempt_id + ); + + // Update feature metadata to track Direct routing usage for stickiness + update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?; + + call_connector_service( + state, + req_state, + merchant_context, + connector, + operation, + payment_data, + customer, + call_connector_action, + validate_result, + schedule_time, + header_payload, + frm_suggestion, + business_profile, + is_retry_payment, + all_keys_required, + merchant_connector_account, + router_data, + tokenization_action, + ) + .await +} + +#[cfg(feature = "v1")] +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +// Helper function to process through Direct with Shadow UCS +async fn process_through_direct_with_shadow_unified_connector_service< + 'a, + F, + RouterDReq, + ApiRequest, + D, +>( + state: &'a SessionState, + req_state: ReqState, + merchant_context: &'a domain::MerchantContext, + connector: api::ConnectorData, + operation: &'a BoxedOperation<'a, F, ApiRequest, D>, + payment_data: &'a mut D, + customer: &Option<domain::Customer>, + call_connector_action: CallConnectorAction, + validate_result: &'a operations::ValidateResult, + schedule_time: Option<time::PrimitiveDateTime>, + header_payload: HeaderPayload, + frm_suggestion: Option<storage_enums::FrmSuggestion>, + business_profile: &'a domain::Profile, + is_retry_payment: bool, + all_keys_required: Option<bool>, + merchant_connector_account: helpers::MerchantConnectorAccountType, + router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + tokenization_action: TokenizationAction, +) -> RouterResult<( + RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + helpers::MerchantConnectorAccountType, +)> +where + F: Send + Clone + Sync + 'static + 'a, + RouterDReq: Send + Sync + Clone + 'static + 'a + serde::Serialize, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, + D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: + Feature<F, RouterDReq> + Send + Clone + serde::Serialize, + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, +{ + router_env::logger::info!( + "Processing payment through Direct gateway system with UCS in shadow mode - payment_id={}, attempt_id={}", + payment_data.get_payment_intent().payment_id.get_string_repr(), + payment_data.get_payment_attempt().attempt_id + ); + + // Clone data needed for shadow UCS call + let unified_connector_service_router_data = router_data.clone(); + let unified_connector_service_merchant_connector_account = merchant_connector_account.clone(); + let unified_connector_service_merchant_context = merchant_context.clone(); + let unified_connector_service_header_payload = header_payload.clone(); + let unified_connector_service_state = state.clone(); + + let lineage_ids = grpc_client::LineageIds::new( + business_profile.merchant_id.clone(), + business_profile.get_id().clone(), + ); + + // Update feature metadata to track Direct routing usage for stickiness + update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?; + + // Call Direct connector service + let result = call_connector_service( + state, + req_state, + merchant_context, + connector, + operation, + payment_data, + customer, + call_connector_action, + validate_result, + schedule_time, + header_payload, + frm_suggestion, + business_profile, + is_retry_payment, + all_keys_required, + merchant_connector_account, + router_data, + tokenization_action, + ) + .await?; + + // Spawn shadow UCS call in background + let direct_router_data = result.0.clone(); + tokio::spawn(async move { + execute_shadow_unified_connector_service_call( + unified_connector_service_state, + unified_connector_service_router_data, + direct_router_data, + unified_connector_service_header_payload, + lineage_ids, + unified_connector_service_merchant_connector_account, + unified_connector_service_merchant_context, + ) + .await + }); + + Ok(result) +} + +#[cfg(feature = "v1")] +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +// Helper function to execute shadow UCS call +async fn execute_shadow_unified_connector_service_call<F, RouterDReq>( + state: SessionState, + mut unified_connector_service_router_data: RouterData< + F, + RouterDReq, + router_types::PaymentsResponseData, + >, + direct_router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + header_payload: HeaderPayload, + lineage_ids: grpc_client::LineageIds, + merchant_connector_account: helpers::MerchantConnectorAccountType, + merchant_context: domain::MerchantContext, +) where + F: Send + Clone + Sync + 'static, + RouterDReq: Send + Sync + Clone + 'static + serde::Serialize, + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: + Feature<F, RouterDReq> + Send + Clone + serde::Serialize, + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, +{ + // Call UCS in shadow mode + let _unified_connector_service_result = unified_connector_service_router_data + .call_unified_connector_service( + &state, + &header_payload, + lineage_ids, + merchant_connector_account, + &merchant_context, + ExecutionMode::Shadow, // Shadow mode for UCS + ) + .await + .map_err(|e| logger::debug!("Shadow UCS call failed: {:?}", e)); + + // Compare results + match serialize_router_data_and_send_to_comparison_service( + &state, + direct_router_data, + unified_connector_service_router_data, + ) .await + { + Ok(_) => logger::debug!("Shadow UCS comparison completed successfully"), + Err(e) => logger::debug!("Shadow UCS comparison failed: {:?}", e), + } +} + +async fn serialize_router_data_and_send_to_comparison_service<F, RouterDReq>( + state: &SessionState, + hyperswitch_router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + unified_connector_service_router_data: RouterData< + F, + RouterDReq, + router_types::PaymentsResponseData, + >, +) -> RouterResult<()> +where + F: Send + Clone + Sync + 'static, + RouterDReq: Send + Sync + Clone + 'static + serde::Serialize, +{ + logger::info!("Simulating UCS call for shadow mode comparison"); + let hyperswitch_data = match serde_json::to_value(hyperswitch_router_data) { + Ok(data) => Secret::new(data), + Err(_) => { + logger::debug!("Failed to serialize HS router data"); + return Ok(()); + } + }; + + let unified_connector_service_data = + match serde_json::to_value(unified_connector_service_router_data) { + Ok(data) => Secret::new(data), + Err(_) => { + logger::debug!("Failed to serialize UCS router data"); + return Ok(()); + } + }; + + let comparison_data = ComparisonData { + hyperswitch_data, + unified_connector_service_data, + }; + let _ = send_comparison_data(state, comparison_data) + .await + .map_err(|e| { + logger::debug!("Failed to send comparison data: {:?}", e); + }); + Ok(()) } async fn record_time_taken_with<F, Fut, R>(f: F) -> RouterResult<R> @@ -4818,7 +5171,10 @@ where ) .await?; - let (connector_request, should_continue_further) = if !should_call_unified_connector_service { + let (connector_request, should_continue_further) = if matches!( + should_call_unified_connector_service, + GatewaySystem::Direct | GatewaySystem::ShadowUnifiedConnectorService + ) { let mut should_continue_further = true; let should_continue = match router_data @@ -4875,7 +5231,7 @@ where .await?; record_time_taken_with(|| async { - if should_call_unified_connector_service { + if matches!(should_call_unified_connector_service, GatewaySystem::UnifiedConnectorService) { router_env::logger::info!( "Processing payment through UCS gateway system- payment_id={}, attempt_id={}", payment_data.get_payment_intent().id.get_string_repr(), @@ -4890,6 +5246,7 @@ where lineage_ids, merchant_connector_account_type_details.clone(), merchant_context, + ExecutionMode::Primary, // UCS is called in primary mode ) .await?; @@ -4941,14 +5298,14 @@ where services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { record_time_taken_with(|| async { - if should_call_unified_connector_service( + let execution = should_call_unified_connector_service( state, merchant_context, &router_data, Some(payment_data), ) - .await? - { + .await?; + if matches!(execution, GatewaySystem::UnifiedConnectorService) { router_env::logger::info!( "Executing payment through UCS gateway system - payment_id={}, attempt_id={}", payment_data.get_payment_intent().id.get_string_repr(), @@ -4993,16 +5350,25 @@ where lineage_ids, merchant_connector_account_type_details.clone(), merchant_context, + ExecutionMode::Primary, //UCS is called in primary mode ) .await?; Ok(router_data) } else { - router_env::logger::info!( - "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", - payment_data.get_payment_intent().id.get_string_repr(), - payment_data.get_payment_attempt().id.get_string_repr() - ); + if matches!(execution, GatewaySystem::ShadowUnifiedConnectorService) { + router_env::logger::info!( + "Shadow UCS mode not implemented in v2, processing through direct path - payment_id={}, attempt_id={}", + payment_data.get_payment_intent().id.get_string_repr(), + payment_data.get_payment_attempt().id.get_string_repr() + ); + } else { + router_env::logger::info!( + "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", + payment_data.get_payment_intent().id.get_string_repr(), + payment_data.get_payment_attempt().id.get_string_repr() + ); + } call_connector_service( state, @@ -5094,6 +5460,7 @@ where merchant_connector_account_type_details.clone(), external_vault_merchant_connector_account_type_details.clone(), merchant_context, + ExecutionMode::Primary, //UCS is called in primary mode ) .await?; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 3fd25d05d6e..612f0e36176 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -16,6 +16,7 @@ pub mod setup_mandate_flow; pub mod update_metadata_flow; use async_trait::async_trait; +use common_enums::{self, ExecutionMode}; use common_types::payments::CustomerAcceptance; use external_services::grpc_client; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] @@ -217,6 +218,7 @@ pub trait Feature<F, T> { #[cfg(feature = "v2")] _merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, _merchant_context: &domain::MerchantContext, + _unified_connector_service_execution_mode: ExecutionMode, ) -> RouterResult<()> where F: Clone, @@ -235,6 +237,7 @@ pub trait Feature<F, T> { _merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, _external_vault_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, _merchant_context: &domain::MerchantContext, + _unified_connector_service_execution_mode: ExecutionMode, ) -> RouterResult<()> where F: Clone, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 6ed1613aae2..cbb5b07f857 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -533,6 +533,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, merchant_context: &domain::MerchantContext, + unified_connector_service_execution_mode: enums::ExecutionMode, ) -> RouterResult<()> { if self.request.mandate_id.is_some() { Box::pin(call_unified_connector_service_repeat_payment( @@ -542,6 +543,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu lineage_ids, merchant_connector_account, merchant_context, + unified_connector_service_execution_mode, )) .await } else { @@ -552,6 +554,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu lineage_ids, merchant_connector_account, merchant_context, + unified_connector_service_execution_mode, )) .await } @@ -854,6 +857,7 @@ async fn call_unified_connector_service_authorize( #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType, #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, merchant_context: &domain::MerchantContext, + unified_connector_service_execution_mode: enums::ExecutionMode, ) -> RouterResult<()> { let client = state .grpc_client @@ -881,7 +885,7 @@ async fn call_unified_connector_service_authorize( .flatten() .map(ucs_types::UcsReferenceId::Payment); let headers_builder = state - .get_grpc_headers_ucs() + .get_grpc_headers_ucs(unified_connector_service_execution_mode) .external_vault_proxy_metadata(None) .merchant_reference_id(merchant_order_reference_id) .lineage_ids(lineage_ids); @@ -943,6 +947,7 @@ async fn call_unified_connector_service_repeat_payment( #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType, #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, merchant_context: &domain::MerchantContext, + unified_connector_service_execution_mode: enums::ExecutionMode, ) -> RouterResult<()> { let client = state .grpc_client @@ -970,7 +975,7 @@ async fn call_unified_connector_service_repeat_payment( .flatten() .map(ucs_types::UcsReferenceId::Payment); let headers_builder = state - .get_grpc_headers_ucs() + .get_grpc_headers_ucs(unified_connector_service_execution_mode) .external_vault_proxy_metadata(None) .merchant_reference_id(merchant_order_reference_id) .lineage_ids(lineage_ids); diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs index 601e3ee5c6e..4e66c5deaca 100644 --- a/crates/router/src/core/payments/flows/external_proxy_flow.rs +++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs @@ -374,6 +374,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData> merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, external_vault_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, merchant_context: &domain::MerchantContext, + unified_connector_service_execution_mode: enums::ExecutionMode, ) -> RouterResult<()> { let client = state .grpc_client @@ -411,7 +412,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData> .flatten() .map(ucs_types::UcsReferenceId::Payment); let headers_builder = state - .get_grpc_headers_ucs() + .get_grpc_headers_ucs(unified_connector_service_execution_mode) .external_vault_proxy_metadata(Some(external_vault_proxy_metadata)) .merchant_reference_id(merchant_order_reference_id) .lineage_ids(lineage_ids); diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index eaaa76e3b34..e54a5fd173f 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -1,6 +1,7 @@ use std::{collections::HashMap, str::FromStr}; use async_trait::async_trait; +use common_enums::{self, enums}; use common_utils::{id_type, ucs_types}; use error_stack::ResultExt; use external_services::grpc_client; @@ -234,6 +235,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, merchant_context: &domain::MerchantContext, + unified_connector_service_execution_mode: enums::ExecutionMode, ) -> RouterResult<()> { let connector_name = self.connector.clone(); let connector_enum = common_enums::connector_enums::Connector::from_str(&connector_name) @@ -285,7 +287,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> .flatten() .map(ucs_types::UcsReferenceId::Payment); let header_payload = state - .get_grpc_headers_ucs() + .get_grpc_headers_ucs(unified_connector_service_execution_mode) .external_vault_proxy_metadata(None) .merchant_reference_id(merchant_reference_id) .lineage_ids(lineage_ids); diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index c1c243064c2..2bc69b85939 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -1,6 +1,7 @@ use std::str::FromStr; use async_trait::async_trait; +use common_enums::{self, enums}; use common_types::payments as common_payments_types; use common_utils::{id_type, ucs_types}; use error_stack::ResultExt; @@ -274,6 +275,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, merchant_context: &domain::MerchantContext, + unified_connector_service_execution_mode: enums::ExecutionMode, ) -> RouterResult<()> { let client = state .grpc_client @@ -303,7 +305,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup .flatten() .map(ucs_types::UcsReferenceId::Payment); let header_payload = state - .get_grpc_headers_ucs() + .get_grpc_headers_ucs(unified_connector_service_execution_mode) .external_vault_proxy_metadata(None) .merchant_reference_id(merchant_reference_id) .lineage_ids(lineage_ids); diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 1e7c0ad5460..367abc4f235 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -32,7 +32,7 @@ use crate::{ #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] #[cfg(feature = "v1")] -pub async fn do_gsm_actions<F, ApiRequest, FData, D>( +pub async fn do_gsm_actions<'a, F, ApiRequest, FData, D>( state: &app::SessionState, req_state: ReqState, payment_data: &mut D, @@ -48,8 +48,8 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, D>( business_profile: &domain::Profile, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where - F: Clone + Send + Sync, - FData: Send + Sync + types::Capturable, + F: Clone + Send + Sync + 'static + 'a, + FData: Send + Sync + types::Capturable + Clone + 'static + 'a + serde::Serialize, payments::PaymentResponse: operations::Operation<F, FData>, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> @@ -338,14 +338,14 @@ fn get_flow_name<F>() -> RouterResult<String> { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] -pub async fn do_retry<F, ApiRequest, FData, D>( - state: &routes::SessionState, +pub async fn do_retry<'a, F, ApiRequest, FData, D>( + state: &'a routes::SessionState, req_state: ReqState, - connector: &api::ConnectorData, - operation: &operations::BoxedOperation<'_, F, ApiRequest, D>, - customer: &Option<domain::Customer>, + connector: &'a api::ConnectorData, + operation: &'a operations::BoxedOperation<'a, F, ApiRequest, D>, + customer: &'a Option<domain::Customer>, merchant_context: &domain::MerchantContext, - payment_data: &mut D, + payment_data: &'a mut D, router_data: types::RouterData<F, FData, types::PaymentsResponseData>, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, @@ -356,8 +356,8 @@ pub async fn do_retry<F, ApiRequest, FData, D>( routing_decision: Option<routing_helpers::RoutingDecisionData>, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where - F: Clone + Send + Sync, - FData: Send + Sync + types::Capturable, + F: Clone + Send + Sync + 'static + 'a, + FData: Send + Sync + types::Capturable + Clone + 'static + 'a + serde::Serialize, payments::PaymentResponse: operations::Operation<F, FData>, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index fbfe9cec635..04a3a2e4ef2 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -3,15 +3,25 @@ use std::{str::FromStr, time::Instant}; use api_models::admin; #[cfg(feature = "v2")] use base64::Engine; -use common_enums::{connector_enums::Connector, AttemptStatus, GatewaySystem, PaymentMethodType}; +use common_enums::{ + connector_enums::Connector, AttemptStatus, ExecutionMode, GatewaySystem, PaymentMethodType, +}; #[cfg(feature = "v2")] use common_utils::consts::BASE64_ENGINE; -use common_utils::{errors::CustomResult, ext_traits::ValueExt}; +use common_utils::{ + consts::X_FLOW_NAME, + errors::CustomResult, + ext_traits::ValueExt, + request::{Method, RequestBuilder, RequestContent}, +}; use diesel_models::types::FeatureMetadata; use error_stack::ResultExt; -use external_services::grpc_client::{ - unified_connector_service::{ConnectorAuthMetadata, UnifiedConnectorServiceError}, - LineageIds, +use external_services::{ + grpc_client::{ + unified_connector_service::{ConnectorAuthMetadata, UnifiedConnectorServiceError}, + LineageIds, + }, + http_client, }; use hyperswitch_connectors::utils::CardData; #[cfg(feature = "v2")] @@ -46,6 +56,7 @@ use crate::{ utils::get_flow_name, }, events::connector_api_logs::ConnectorEvent, + headers::{CONTENT_TYPE, X_REQUEST_ID}, routes::SessionState, types::transformers::ForeignTryFrom, }; @@ -64,90 +75,87 @@ type UnifiedConnectorServiceResult = CustomResult< UnifiedConnectorServiceError, >; -/// Generic version of should_call_unified_connector_service that works with any type -/// implementing OperationSessionGetters trait pub async fn should_call_unified_connector_service<F: Clone, T, D>( state: &SessionState, merchant_context: &MerchantContext, router_data: &RouterData<F, T, PaymentsResponseData>, payment_data: Option<&D>, -) -> RouterResult<bool> +) -> RouterResult<GatewaySystem> where D: OperationSessionGetters<F>, { - // Check basic UCS availability first - if state.grpc_client.unified_connector_service_client.is_none() { + // Extract context information + let merchant_id = merchant_context + .get_merchant_account() + .get_id() + .get_string_repr(); + + let connector_name = &router_data.connector; + let connector_enum = Connector::from_str(connector_name) + .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) + .attach_printable_lazy(|| format!("Failed to parse connector name: {}", connector_name))?; + + let payment_method = router_data.payment_method.to_string(); + let flow_name = get_flow_name::<F>()?; + + // Compute all relevant conditions + let ucs_client_available = state.grpc_client.unified_connector_service_client.is_some(); + let ucs_enabled = is_ucs_enabled(state, consts::UCS_ENABLED).await; + + // Log if UCS client is not available + if !ucs_client_available { router_env::logger::debug!( - "Unified Connector Service client is not available, skipping UCS decision" + "UCS client not available - merchant_id={}, connector={}", + merchant_id, + connector_name ); - return Ok(false); } - let ucs_config_key = consts::UCS_ENABLED; - if !is_ucs_enabled(state, ucs_config_key).await { + // Log if UCS is not enabled + if !ucs_enabled { router_env::logger::debug!( - "Unified Connector Service is not enabled, skipping UCS decision" + "UCS not enabled in configuration - merchant_id={}, connector={}", + merchant_id, + connector_name ); - return Ok(false); } - // Apply stickiness logic if payment_data is available - if let Some(payment_data) = payment_data { - let previous_gateway_system = extract_gateway_system_from_payment_intent(payment_data); + let ucs_config = state.conf.grpc_client.unified_connector_service.as_ref(); - match previous_gateway_system { - Some(GatewaySystem::UnifiedConnectorService) => { - // Payment intent previously used UCS, maintain stickiness to UCS - router_env::logger::info!( - "Payment gateway system decision: UCS (sticky) - payment intent previously used UCS" - ); - return Ok(true); - } - Some(GatewaySystem::Direct) => { - // Payment intent previously used Direct, maintain stickiness to Direct (return false for UCS) - router_env::logger::info!( - "Payment gateway system decision: Direct (sticky) - payment intent previously used Direct" - ); - return Ok(false); - } - None => { - // No previous gateway system set, continue with normal gateway system logic - router_env::logger::debug!( - "UCS stickiness: No previous gateway system set, applying normal gateway system logic" - ); - } - } + // Log if UCS configuration is missing + if ucs_config.is_none() { + router_env::logger::debug!( + "UCS configuration not found - merchant_id={}, connector={}", + merchant_id, + connector_name + ); } - // Continue with normal UCS gateway system logic - let merchant_id = merchant_context - .get_merchant_account() - .get_id() - .get_string_repr(); + let ucs_only_connector = + ucs_config.is_some_and(|config| config.ucs_only_connectors.contains(&connector_enum)); - let connector_name = router_data.connector.clone(); - let connector_enum = Connector::from_str(&connector_name) - .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?; + let previous_gateway = payment_data.and_then(extract_gateway_system_from_payment_intent); - let payment_method = router_data.payment_method.to_string(); - let flow_name = get_flow_name::<F>()?; - - let is_ucs_only_connector = state - .conf - .grpc_client - .unified_connector_service - .as_ref() - .is_some_and(|config| config.ucs_only_connectors.contains(&connector_enum)); - - if is_ucs_only_connector { - router_env::logger::info!( - "Payment gateway system decision: UCS (forced) - merchant_id={}, connector={}, payment_method={}, flow={}", - merchant_id, connector_name, payment_method, flow_name - ); - return Ok(true); + // Log previous gateway state + match previous_gateway { + Some(gateway) => { + router_env::logger::debug!( + "Previous gateway system found: {:?} - merchant_id={}, connector={}", + gateway, + merchant_id, + connector_name + ); + } + None => { + router_env::logger::debug!( + "No previous gateway system found (new payment) - merchant_id={}, connector={}", + merchant_id, + connector_name + ); + } } - let config_key = format!( + let rollout_key = format!( "{}_{}_{}_{}_{}", consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX, merchant_id, @@ -155,23 +163,179 @@ where payment_method, flow_name ); + let shadow_rollout_key = format!("{}_shadow", rollout_key); - let should_execute = should_execute_based_on_rollout(state, &config_key).await?; + let rollout_enabled = should_execute_based_on_rollout(state, &rollout_key).await?; + let shadow_rollout_enabled = + should_execute_based_on_rollout(state, &shadow_rollout_key).await?; - // Log gateway system decision - if should_execute { - router_env::logger::info!( - "Payment gateway system decision: UCS - merchant_id={}, connector={}, payment_method={}, flow={}", - merchant_id, connector_name, payment_method, flow_name - ); - } else { - router_env::logger::info!( - "Payment gateway system decision: Direct - merchant_id={}, connector={}, payment_method={}, flow={}", - merchant_id, connector_name, payment_method, flow_name - ); - } + router_env::logger::debug!( + "Rollout status - rollout_enabled={}, shadow_rollout_enabled={}, rollout_key={}, merchant_id={}, connector={}", + rollout_enabled, + shadow_rollout_enabled, + rollout_key, + merchant_id, + connector_name + ); - Ok(should_execute) + // Single decision point using pattern matching + // Tuple structure: (ucs_infrastructure_ready, ucs_only_connector, previous_gateway, shadow_rollout_enabled, rollout_enabled) + let decision = match ( + ucs_client_available && ucs_enabled, + ucs_only_connector, + previous_gateway, + shadow_rollout_enabled, + rollout_enabled, + ) { + // ==================== DIRECT GATEWAY DECISIONS ==================== + // All patterns that result in Direct routing + + // UCS infrastructure not available (any configuration) + // - Client not available OR not enabled + // - Regardless of: ucs_only_connector, previous_gateway, rollouts + (false, _, _, _, _) | + + // UCS available but no rollouts active and no previous gateway + // - Infrastructure ready + // - Not a UCS-only connector + // - New payment (no previous gateway) + // - No shadow rollout + // - No full rollout + (true, false, None, false, false) | + + // UCS available, continuing with Direct, no rollouts + // - Infrastructure ready + // - Not a UCS-only connector + // - Previous gateway was Direct + // - No shadow rollout + // - No full rollout + (true, false, Some(GatewaySystem::Direct), false, false) | + + // UCS available, previous Shadow but rollout ended + // - Infrastructure ready + // - Not a UCS-only connector + // - Previous gateway was Shadow + // - No shadow rollout (ended) + // - No full rollout + (true, false, Some(GatewaySystem::ShadowUnifiedConnectorService), false, false) => { + router_env::logger::debug!( + "Routing to Direct: ucs_ready={}, ucs_only={}, previous={:?}, shadow_rollout={}, full_rollout={} - merchant_id={}, connector={}", + ucs_client_available && ucs_enabled, + ucs_only_connector, + previous_gateway, + shadow_rollout_enabled, + rollout_enabled, + merchant_id, + connector_name + ); + GatewaySystem::Direct + } + + // ==================== SHADOW UCS DECISIONS ==================== + // All patterns that result in Shadow UCS routing + + // Shadow rollout for new payment (no previous gateway) + // - Infrastructure ready + // - Not a UCS-only connector + // - No previous gateway + // - Shadow rollout enabled + // - Full rollout: any (false or true, shadow takes precedence) + (true, false, None, true, _) | + + // Shadow rollout with previous Direct gateway + // - Infrastructure ready + // - Not a UCS-only connector + // - Previous gateway was Direct + // - Shadow rollout enabled + // - Full rollout: any (shadow takes precedence) + (true, false, Some(GatewaySystem::Direct), true, _) | + + // Shadow rollout with previous Shadow gateway (continuation) + // - Infrastructure ready + // - Not a UCS-only connector + // - Previous gateway was Shadow + // - Shadow rollout enabled + // - Full rollout: any + (true, false, Some(GatewaySystem::ShadowUnifiedConnectorService), true, _) => { + router_env::logger::debug!( + "Routing to ShadowUnifiedConnectorService: ucs_ready={}, ucs_only={}, previous={:?}, shadow_rollout={}, full_rollout={} - merchant_id={}, connector={}", + ucs_client_available && ucs_enabled, + ucs_only_connector, + previous_gateway, + shadow_rollout_enabled, + rollout_enabled, + merchant_id, + connector_name + ); + GatewaySystem::ShadowUnifiedConnectorService + } + + // ==================== UNIFIED CONNECTOR SERVICE DECISIONS ==================== + // All patterns that result in UCS routing + + // UCS-only connector (mandatory UCS) + // - Infrastructure ready + // - UCS-only connector flag set + // - Any previous gateway + // - Any shadow rollout state + // - Any full rollout state + (true, true, _, _, _) | + + // Sticky routing: Continue with previous UCS + // - Infrastructure ready + // - Not a UCS-only connector + // - Previous gateway was UCS + // - Any shadow rollout state (doesn't affect existing UCS) + // - Any full rollout state + (true, false, Some(GatewaySystem::UnifiedConnectorService), _, _) | + + // Full rollout: New payment + // - Infrastructure ready + // - Not a UCS-only connector + // - No previous gateway + // - No shadow rollout (shadow would take precedence) + // - Full rollout enabled + (true, false, None, false, true) | + + // Full rollout: Switch from Direct + // - Infrastructure ready + // - Not a UCS-only connector + // - Previous gateway was Direct + // - No shadow rollout (shadow would take precedence) + // - Full rollout enabled + (true, false, Some(GatewaySystem::Direct), false, true) | + + // Full rollout: Promote from Shadow + // - Infrastructure ready + // - Not a UCS-only connector + // - Previous gateway was Shadow + // - Shadow rollout ended (now false) + // - Full rollout enabled + (true, false, Some(GatewaySystem::ShadowUnifiedConnectorService), false, true) => { + router_env::logger::debug!( + "Routing to UnifiedConnectorService: ucs_ready={}, ucs_only={}, previous={:?}, shadow_rollout={}, full_rollout={} - merchant_id={}, connector={}", + ucs_client_available && ucs_enabled, + ucs_only_connector, + previous_gateway, + shadow_rollout_enabled, + rollout_enabled, + merchant_id, + connector_name + ); + GatewaySystem::UnifiedConnectorService + } + }; + + router_env::logger::info!( + "Payment gateway system decision: {:?} - merchant_id={}, connector={}, payment_method={}, flow={}", + decision, + merchant_id, + connector_name, + payment_method, + flow_name + ); + + Ok(decision) } /// Extracts the gateway system from the payment intent's feature metadata @@ -746,7 +910,7 @@ pub async fn call_unified_connector_service_for_webhook( .unwrap_or(consts::PROFILE_ID_UNAVAILABLE.clone()); // Build gRPC headers let grpc_headers = state - .get_grpc_headers_ucs() + .get_grpc_headers_ucs(ExecutionMode::Primary) .lineage_ids(LineageIds::new( merchant_context.get_merchant_account().get_id().clone(), profile_id, @@ -882,7 +1046,7 @@ where std::any::type_name::<T>(), grpc_request_body, "grpc://unified-connector-service".to_string(), - common_utils::request::Method::Post, + Method::Post, payment_id, merchant_id, state.request_id.as_ref(), @@ -909,3 +1073,45 @@ where router_result } + +#[derive(serde::Serialize)] +pub struct ComparisonData { + pub hyperswitch_data: Secret<serde_json::Value>, + pub unified_connector_service_data: Secret<serde_json::Value>, +} + +/// Sends router data comparison to external service +pub async fn send_comparison_data( + state: &SessionState, + comparison_data: ComparisonData, +) -> RouterResult<()> { + // Check if comparison service is enabled + let comparison_config = match state.conf.comparison_service.as_ref() { + Some(comparison_config) => comparison_config, + None => { + tracing::warn!( + "Comparison service configuration missing, skipping comparison data send" + ); + return Ok(()); + } + }; + + let mut request = RequestBuilder::new() + .method(Method::Post) + .url(comparison_config.url.get_string_repr()) + .header(CONTENT_TYPE, "application/json") + .header(X_FLOW_NAME, "router-data") + .set_body(RequestContent::Json(Box::new(comparison_data))) + .build(); + if let Some(req_id) = &state.request_id { + request.add_header(X_REQUEST_ID, masking::Maskable::Normal(req_id.to_string())); + } + + let _ = http_client::send_request(&state.conf.proxy, request, comparison_config.timeout_secs) + .await + .map_err(|e| { + tracing::debug!("Error sending comparison data: {:?}", e); + }); + + Ok(()) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 3a46c1a9767..43e1deb4431 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -5,7 +5,7 @@ use actix_web::{web, Scope}; use api_models::routing::RoutingRetrieveQuery; use api_models::routing::RuleMigrationQuery; #[cfg(feature = "olap")] -use common_enums::TransactionType; +use common_enums::{ExecutionMode, TransactionType}; #[cfg(feature = "partial-auth")] use common_utils::crypto::Blake3; use common_utils::id_type; @@ -157,9 +157,20 @@ impl SessionState { request_id: self.request_id.map(|req_id| (*req_id).to_string()), } } - pub fn get_grpc_headers_ucs(&self) -> GrpcHeadersUcsBuilderInitial { + pub fn get_grpc_headers_ucs( + &self, + unified_connector_service_execution_mode: ExecutionMode, + ) -> GrpcHeadersUcsBuilderInitial { let tenant_id = self.tenant.tenant_id.get_string_repr().to_string(); - GrpcHeadersUcs::builder().tenant_id(tenant_id) + let request_id = self.request_id.map(|req_id| (*req_id).to_string()); + let shadow_mode = match unified_connector_service_execution_mode { + ExecutionMode::Primary => false, + ExecutionMode::Shadow => true, + }; + GrpcHeadersUcs::builder() + .tenant_id(tenant_id) + .request_id(request_id) + .shadow_mode(Some(shadow_mode)) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] pub fn get_recovery_grpc_headers(&self) -> GrpcRecoveryHeaders { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 17150020186..230250400be 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -20,7 +20,9 @@ pub use client::{ApiClient, MockApiClient, ProxyClient}; pub use common_enums::enums::PaymentAction; pub use common_utils::request::{ContentType, Method, Request, RequestBuilder}; use common_utils::{ - consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY}, + consts::{ + DEFAULT_TENANT, TENANT_HEADER, X_CONNECTOR_NAME, X_FLOW_NAME, X_HS_LATENCY, X_REQUEST_ID, + }, errors::{ErrorSwitch, ReportSwitchExt}, request::RequestContent, }; @@ -61,7 +63,7 @@ use crate::{ core::{ api_locking, errors::{self, CustomResult}, - payments, unified_connector_service, + payments, unified_connector_service, utils as core_utils, }, events::{ api_logs::{ApiEvent, ApiEventMetric, ApiEventsType}, @@ -296,10 +298,8 @@ where ("connector", req.connector.to_string()), ( "flow", - std::any::type_name::<T>() - .split("::") - .last() - .unwrap_or_default() + core_utils::get_flow_name::<T>() + .unwrap_or_else(|_| "UnknownFlow".to_string()) ), ), ); @@ -326,7 +326,7 @@ where }; match connector_request { - Some(request) => { + Some(mut request) => { let masked_request_body = match &request.body { Some(request) => match request { RequestContent::Json(i) @@ -341,6 +341,27 @@ where }, None => serde_json::Value::Null, }; + let flow_name = core_utils::get_flow_name::<T>() + .unwrap_or_else(|_| "UnknownFlow".to_string()); + + request.headers.insert(( + X_FLOW_NAME.to_string(), + Maskable::Masked(Secret::new(flow_name.to_string())), + )); + + let connector_name = req.connector.clone(); + request.headers.insert(( + X_CONNECTOR_NAME.to_string(), + Maskable::Masked(Secret::new(connector_name.clone().to_string())), + )); + state.request_id.as_ref().map(|id| { + let request_id = id.to_string(); + request.headers.insert(( + X_REQUEST_ID.to_string(), + Maskable::Normal(request_id.clone()), + )); + request_id + }); let request_url = request.url.clone(); let request_method = request.method; let current_time = Instant::now();
2025-10-06T10:15:21Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added a fork using tokio::spawn and sent the cloned router data to UCS, Added some headers for identification of connector, flow, req-id called the validation service to send both router data for comparison. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e68b151dede97be6270e59502c8b4ec562a549d4
juspay/hyperswitch
juspay__hyperswitch-9679
Bug: [BUG] amount_captured population logic in Cryptopay connector ### Bug Description `amount_captured` is being set from the `price_amount` field for all payment statuses, including incomplete payments like `requires_customer_action`. Cryptopay allows customers to overpay, but the integrity check was throwing errors when `captured_amount > total_capturable_amount` and `is_overcapture_enabled` was false ### Expected Behavior amount_captured should be populated for succeded payments. should not throw errors for overpaid payments ### Actual Behavior `amount_captured` is being set from the `price_amount` field for all payment statuses, including incomplete payments like `requires_customer_action`. overpaid payments response handling throwing integrity check error ### Steps To Reproduce make a overpaid payment & do a psync. ### Context For The Bug _No response_ ### Environment rustc 1.90.0 macos 15.6.1 ### 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/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index a9bc6f27f97..27ccbbf75b6 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -201,8 +201,8 @@ impl<F, T> charges: None, }) }; - match amount_captured_in_minor_units { - Some(minor_amount) => { + match (amount_captured_in_minor_units, status) { + (Some(minor_amount), enums::AttemptStatus::Charged) => { let amount_captured = Some(minor_amount.get_amount_as_i64()); Ok(Self { status, @@ -212,7 +212,7 @@ impl<F, T> ..item.data }) } - None => Ok(Self { + _ => Ok(Self { status, response, ..item.data diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 8c33ce1044a..3a3a4b6fb78 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -180,31 +180,13 @@ where payment_data, ); let total_capturable_amount = payment_data.payment_attempt.get_total_amount(); - let is_overcapture_enabled = *payment_data - .payment_attempt - .is_overcapture_enabled - .as_deref() - .unwrap_or(&false); if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new) - || (is_overcapture_enabled - && captured_amount.is_some_and(|captured_amount| { - MinorUnit::new(captured_amount) > total_capturable_amount - })) + || (captured_amount.is_some_and(|captured_amount| { + MinorUnit::new(captured_amount) > total_capturable_amount + })) { Ok(enums::AttemptStatus::Charged) - } else if captured_amount.is_some_and(|captured_amount| { - MinorUnit::new(captured_amount) > total_capturable_amount - }) { - Err(ApiErrorResponse::IntegrityCheckFailed { - reason: "captured_amount is greater than the total_capturable_amount" - .to_string(), - field_names: "captured_amount".to_string(), - connector_transaction_id: payment_data - .payment_attempt - .connector_transaction_id - .clone(), - })? } else if captured_amount.is_some_and(|captured_amount| { MinorUnit::new(captured_amount) < total_capturable_amount }) { diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index a2958d7508b..7320a2a4f03 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -581,7 +581,7 @@ impl Capturable for PaymentsSyncData { #[cfg(feature = "v1")] fn get_captured_amount<F>( &self, - _amount_captured: Option<i64>, + amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where @@ -591,6 +591,7 @@ impl Capturable for PaymentsSyncData { .payment_attempt .amount_to_capture .or(payment_data.payment_intent.amount_captured) + .or(amount_captured.map(MinorUnit::new)) .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) }
2025-10-05T17:48:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Modified response handling logic to only populate `amount_captured` in router_data when payment status is `Charged`. - Removed the integrity check error that was preventing overpaid payments from being processed correctly. - The `PaymentsSyncData::get_captured_amount` method was ignoring the `amount_captured` parameter and only consulting stored payment data and getting total_amount. To fix this added `.or(amount_captured.map(MinorUnit::new))` to the chain in `PaymentsSyncData::get_captured_amount`, ensuring the method prioritizes amount_captured from router_data similar to PaymentsAuthorizeData before consulting payment_data for total_amount. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context - Previously, `amount_captured` was being set from the `price_amount` field for all payment statuses, including incomplete payments like `requires_customer_action` - Cryptopay allows customers to overpay, but the integrity check was throwing errors when `captured_amount > total_capturable_amount` and `is_overcapture_enabled` was false <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <details> <summary>Create Payment</summary> ```json { "amount": 15, "currency": "USD", "confirm": true, "email": "[email protected]", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "capture_method": "automatic", "payment_method_data": { "crypto": { "pay_currency": "LTC" } } } ``` Response ```json { "payment_id": "pay_nmtnfFNgKIwgtmwwwfeZ", "merchant_id": "merchant_1759732916", "status": "requires_customer_action", "amount": 15, "net_amount": 15, "shipping_cost": null, "amount_capturable": 15, "amount_received": null, "connector": "cryptopay", "client_secret": "pay_nmtnfFNgKIwgtmwwwfeZ_secret_6Ga6ekLlDTUcJVKLE9xd", "created": "2025-10-06T06:46:16.209Z", "currency": "USD", "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": "crypto", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_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_nmtnfFNgKIwgtmwwwfeZ/merchant_1759732916/pay_nmtnfFNgKIwgtmwwwfeZ_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "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": "782f2938-c41d-4be2-b93e-c22709654054", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_nmtnfFNgKIwgtmwwwfeZ_1", "payment_link": null, "profile_id": "pro_idiFBCtfW7ACI2qZSLdk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LB9MXkHZW8HRFzhiyJvY", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T07:01:16.209Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T06:46:16.598Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` </details> <details> <summary>Underpaid Payment Sync</summary> Response ```json { "payment_id": "pay_AQ3kBO4NEV65g4nzsI5H", "merchant_id": "merchant_1759732916", "status": "partially_captured", "amount": 15, "net_amount": 15, "shipping_cost": null, "amount_capturable": 0, "amount_received": 12, "connector": "cryptopay", "client_secret": "pay_AQ3kBO4NEV65g4nzsI5H_secret_ogakUxfaNRXMgwTm2Cx2", "created": "2025-10-06T10:31:46.564Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_AQ3kBO4NEV65g4nzsI5H_1", "status": "partial_charged", "amount": 15, "order_tax_amount": null, "currency": "USD", "connector": "cryptopay", "error_message": null, "payment_method": "crypto", "connector_transaction_id": "8157c59c-7ef1-4520-adc0-ff505d67c4c2", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-10-06T10:31:46.567Z", "modified_at": "2025-10-06T10:41:51.594Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "reference_id": "pay_AQ3kBO4NEV65g4nzsI5H_1", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "crypto", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "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": "redirect_to_url", "payment_method_type": "crypto_currency", "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": "8157c59c-7ef1-4520-adc0-ff505d67c4c2", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_AQ3kBO4NEV65g4nzsI5H_1", "payment_link": null, "profile_id": "pro_idiFBCtfW7ACI2qZSLdk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LB9MXkHZW8HRFzhiyJvY", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T10:46:46.564Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T10:41:51.594Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` </details> <details> <summary>Overpaid Payment sync</summary> Response ```json { "payment_id": "pay_GDtiguqwSEiybP9S2Pgc", "merchant_id": "merchant_1759732916", "status": "succeeded", "amount": 15, "net_amount": 15, "shipping_cost": null, "amount_capturable": 0, "amount_received": 17, "connector": "cryptopay", "client_secret": "pay_GDtiguqwSEiybP9S2Pgc_secret_yVeHrITuZPa434ZYDMN4", "created": "2025-10-06T06:42:08.937Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_GDtiguqwSEiybP9S2Pgc_1", "status": "charged", "amount": 15, "order_tax_amount": null, "currency": "USD", "connector": "cryptopay", "error_message": null, "payment_method": "crypto", "connector_transaction_id": "98c30587-0544-4c2f-949e-923965773a87", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-10-06T06:42:08.940Z", "modified_at": "2025-10-06T06:45:42.581Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "reference_id": "pay_GDtiguqwSEiybP9S2Pgc_1", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "crypto", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "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": "redirect_to_url", "payment_method_type": "crypto_currency", "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": "98c30587-0544-4c2f-949e-923965773a87", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_GDtiguqwSEiybP9S2Pgc_1", "payment_link": null, "profile_id": "pro_idiFBCtfW7ACI2qZSLdk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LB9MXkHZW8HRFzhiyJvY", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T06:57:08.936Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T06:45:42.581Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` </details> <details> <summary>Exact amount paid Payment Sync</summary> Response ```json { "payment_id": "pay_0yVxECTGSurN7u9hMe1j", "merchant_id": "merchant_1759732916", "status": "succeeded", "amount": 15, "net_amount": 15, "shipping_cost": null, "amount_capturable": 0, "amount_received": 15, "connector": "cryptopay", "client_secret": "pay_0yVxECTGSurN7u9hMe1j_secret_i3GfK1Km0iitrQx66IgF", "created": "2025-10-10T07:49:43.268Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_0yVxECTGSurN7u9hMe1j_1", "status": "charged", "amount": 15, "order_tax_amount": null, "currency": "USD", "connector": "cryptopay", "error_message": null, "payment_method": "crypto", "connector_transaction_id": "af24ef5c-f51c-43de-9c73-732ac3c4857d", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-10-10T07:49:43.275Z", "modified_at": "2025-10-10T07:55:00.411Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "reference_id": "pay_0yVxECTGSurN7u9hMe1j_1", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "crypto", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "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": "redirect_to_url", "payment_method_type": "crypto_currency", "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": "af24ef5c-f51c-43de-9c73-732ac3c4857d", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_0yVxECTGSurN7u9hMe1j_1", "payment_link": null, "profile_id": "pro_idiFBCtfW7ACI2qZSLdk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LB9MXkHZW8HRFzhiyJvY", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-10T08:04:43.267Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-10T07:55:00.412Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": null, "mit_category": null } ``` </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c815d253ccd50b6f5e54bd7dd6fb7c5954cebb0c
juspay/hyperswitch
juspay__hyperswitch-9660
Bug: refactor(routing): update configs on updation of mca
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 30f70943487..9652bfdd529 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -23,7 +23,7 @@ use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::types as pm_auth_types; use uuid::Uuid; -use super::routing::helpers::{redact_cgraph_cache, update_default_fallback_on_mca_update}; +use super::routing::helpers::redact_cgraph_cache; #[cfg(any(feature = "v1", feature = "v2"))] use crate::types::transformers::ForeignFrom; use crate::{ @@ -2873,7 +2873,7 @@ pub async fn update_connector( let updated_mca = db .update_merchant_connector_account( key_manager_state, - mca, + mca.clone(), payment_connector.into(), &key_store, ) @@ -2894,8 +2894,33 @@ pub async fn update_connector( // redact cgraph cache on connector updation redact_cgraph_cache(&state, merchant_id, &profile_id).await?; - // update default fallback config - update_default_fallback_on_mca_update(&state, merchant_id, &profile_id, &updated_mca).await?; + // redact routing cache on connector updation + #[cfg(feature = "v1")] + let merchant_config = MerchantDefaultConfigUpdate { + routable_connector: &Some( + common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| { + errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector_name", + } + })?, + ), + merchant_connector_id: &mca.get_id(), + store: db, + merchant_id, + profile_id: &mca.profile_id, + transaction_type: &mca.connector_type.into(), + }; + + #[cfg(feature = "v1")] + if req.disabled.unwrap_or(false) { + merchant_config + .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() + .await?; + } else { + merchant_config + .retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists() + .await?; + } let response = updated_mca.foreign_try_into()?; diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 03e24ca2bf1..e5671e2edb3 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -2,9 +2,11 @@ //! //! Functions that are used to perform the retrieval of merchant's //! routing dict, configs, defaults +use std::fmt::Debug; +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +use std::str::FromStr; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use std::sync::Arc; -use std::{fmt::Debug, str::FromStr}; #[cfg(feature = "v1")] use api_models::open_router; @@ -2788,50 +2790,3 @@ pub async fn redact_routing_cache( Ok(()) } - -pub async fn update_default_fallback_on_mca_update( - state: &SessionState, - merchant_id: &id_type::MerchantId, - profile_id: &id_type::ProfileId, - updated_mca: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, -) -> RouterResult<()> { - let db = state.store.as_ref(); - let merchant_id_str = merchant_id.get_string_repr(); - let profile_id_str = profile_id.get_string_repr(); - let txn_type = &storage::enums::TransactionType::from(updated_mca.connector_type); - - let mut connectors = get_merchant_default_config(db, merchant_id_str, txn_type).await?; - - let choice = routing_types::RoutableConnectorChoice { - choice_kind: routing_types::RoutableChoiceKind::FullStruct, - connector: api_models::enums::RoutableConnectors::from_str( - &updated_mca.connector_name.to_string(), - ) - .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) - .attach_printable(format!( - "Unable to parse RoutableConnectors from connector: {}", - updated_mca.connector_name - ))?, - merchant_connector_id: Some(updated_mca.get_id().clone()), - }; - - if updated_mca.disabled.unwrap_or(false) - || updated_mca.status == api_models::enums::ConnectorStatus::Inactive - { - // remove if disabled - connectors.retain(|c| c.merchant_connector_id != Some(updated_mca.get_id().clone())); - } else { - // ensure it is present if enabled - if !connectors.contains(&choice) { - connectors.push(choice); - } - } - - // update merchant config - update_merchant_default_config(db, merchant_id_str, connectors.clone(), txn_type).await?; - - // update profile config - update_merchant_default_config(db, profile_id_str, connectors, txn_type).await?; - - Ok(()) -}
2025-10-07T19:17:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request refactors how the default fallback routing configuration is updated when a merchant connector account is modified. Instead of calling the old helper function, the logic is now handled through a new `MerchantDefaultConfigUpdate` struct with methods that more explicitly update or remove the connector from the routing algorithm, depending on whether the connector is disabled. The changes also ensure that the connector update uses a clone of the merchant connector account object. **Routing configuration update refactor:** * Replaces the old `update_default_fallback_on_mca_update` helper with explicit logic using the `MerchantDefaultConfigUpdate` struct, which updates or deletes the connector from the default fallback routing algorithm based on the connector's status. This makes the update process more modular and easier to maintain. [[1]](diffhunk://#diff-7e1b4a44fadc4de1af2a6abeb318b3ddf044177c44ba00731c33dbf4cdce92b7L2894-R2920) [[2]](diffhunk://#diff-ea48d33e52b2cb7edbbba1d236b55f946fdb2c178f8c76f4226818b3630c4658L2791-L2837) * Removes the now-unused `update_default_fallback_on_mca_update` function from `routing/helpers.rs`. **Code quality and correctness:** * Ensures the `update_merchant_connector_account` call receives a clone of the `mca` object, preventing potential issues with ownership or mutation. * Cleans up imports by removing the now-unused `update_default_fallback_on_mca_update` import. <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
27a7845a26e37dc160d38641c93a1aea21692395
juspay/hyperswitch
juspay__hyperswitch-9675
Bug: [feature] add mit payment s2s call and invoice sync job to subscription webhook Create Mit payment handler in subscription invoice_handler.rs and add create_invoice_sync_job after updating the invoice with the payment ID
diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs index 9378d7796f4..2829d58b883 100644 --- a/crates/api_models/src/subscription.rs +++ b/crates/api_models/src/subscription.rs @@ -5,6 +5,7 @@ use utoipa::ToSchema; use crate::{ enums as api_enums, + mandates::RecurringDetails, payments::{Address, PaymentMethodDataRequest}, }; @@ -279,6 +280,17 @@ pub struct PaymentResponseData { pub payment_method_type: Option<api_enums::PaymentMethodType>, pub client_secret: Option<String>, } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct CreateMitPaymentRequestData { + pub amount: MinorUnit, + pub currency: api_enums::Currency, + pub confirm: bool, + pub customer_id: Option<common_utils::id_type::CustomerId>, + pub recurring_details: Option<RecurringDetails>, + pub off_session: Option<bool>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionRequest { /// Client secret for SDK based interaction. diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index b1859cc6c28..b9053b46bc5 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; -pub use super::connector_enums::RoutableConnectors; +pub use super::connector_enums::{InvoiceStatus, RoutableConnectors}; #[doc(hidden)] pub mod diesel_exports { pub use super::{ @@ -9598,3 +9598,23 @@ pub enum GooglePayCardFundingSource { #[serde(other)] Unknown, } + +impl From<IntentStatus> for InvoiceStatus { + fn from(value: IntentStatus) -> Self { + match value { + IntentStatus::Succeeded => Self::InvoicePaid, + IntentStatus::RequiresCapture + | IntentStatus::PartiallyCaptured + | IntentStatus::PartiallyCapturedAndCapturable + | IntentStatus::PartiallyAuthorizedAndRequiresCapture + | IntentStatus::Processing + | IntentStatus::RequiresCustomerAction + | IntentStatus::RequiresConfirmation + | IntentStatus::RequiresPaymentMethod => Self::PaymentPending, + IntentStatus::RequiresMerchantAction => Self::ManualReview, + IntentStatus::Cancelled | IntentStatus::CancelledPostCapture => Self::PaymentCanceled, + IntentStatus::Expired => Self::PaymentPendingTimeout, + IntentStatus::Failed | IntentStatus::Conflicted => Self::PaymentFailed, + } + } +} diff --git a/crates/diesel_models/src/invoice.rs b/crates/diesel_models/src/invoice.rs index 8ffd54c288d..59ef0b272d5 100644 --- a/crates/diesel_models/src/invoice.rs +++ b/crates/diesel_models/src/invoice.rs @@ -57,6 +57,7 @@ pub struct InvoiceUpdate { pub status: Option<String>, pub payment_method_id: Option<String>, pub modified_at: time::PrimitiveDateTime, + pub payment_intent_id: Option<common_utils::id_type::PaymentId>, } impl InvoiceNew { @@ -98,10 +99,15 @@ impl InvoiceNew { } impl InvoiceUpdate { - pub fn new(payment_method_id: Option<String>, status: Option<InvoiceStatus>) -> Self { + pub fn new( + payment_method_id: Option<String>, + status: Option<InvoiceStatus>, + payment_intent_id: Option<common_utils::id_type::PaymentId>, + ) -> Self { Self { payment_method_id, status: status.map(|status| status.to_string()), + payment_intent_id, modified_at: common_utils::date_time::now(), } } diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 1ec8514fc65..2d3fd649669 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -354,6 +354,7 @@ pub async fn confirm_subscription( &state, invoice.id, payment_response.payment_method_id.clone(), + Some(payment_response.payment_id.clone()), invoice_details .clone() .and_then(|invoice| invoice.status) diff --git a/crates/router/src/core/subscription/invoice_handler.rs b/crates/router/src/core/subscription/invoice_handler.rs index 3809474acff..8cc026fb373 100644 --- a/crates/router/src/core/subscription/invoice_handler.rs +++ b/crates/router/src/core/subscription/invoice_handler.rs @@ -77,11 +77,13 @@ impl InvoiceHandler { state: &SessionState, invoice_id: common_utils::id_type::InvoiceId, payment_method_id: Option<Secret<String>>, + payment_intent_id: Option<common_utils::id_type::PaymentId>, status: connector_enums::InvoiceStatus, ) -> errors::RouterResult<diesel_models::invoice::Invoice> { let update_invoice = diesel_models::invoice::InvoiceUpdate::new( payment_method_id.as_ref().map(|id| id.peek()).cloned(), Some(status), + payment_intent_id, ); state .store @@ -255,4 +257,31 @@ impl InvoiceHandler { .attach_printable("invoices: unable to create invoice sync job in database")?; Ok(()) } + + pub async fn create_mit_payment( + &self, + state: &SessionState, + amount: MinorUnit, + currency: common_enums::Currency, + payment_method_id: &str, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let mit_payment_request = subscription_types::CreateMitPaymentRequestData { + amount, + currency, + confirm: true, + customer_id: Some(self.subscription.customer_id.clone()), + recurring_details: Some(api_models::mandates::RecurringDetails::PaymentMethodId( + payment_method_id.to_owned(), + )), + off_session: Some(true), + }; + + payments_api_client::PaymentsApiClient::create_mit_payment( + state, + mit_payment_request, + self.merchant_account.get_id().get_string_repr(), + self.profile.get_id().get_string_repr(), + ) + .await + } } diff --git a/crates/router/src/core/subscription/payments_api_client.rs b/crates/router/src/core/subscription/payments_api_client.rs index e483469be96..e530a5843c8 100644 --- a/crates/router/src/core/subscription/payments_api_client.rs +++ b/crates/router/src/core/subscription/payments_api_client.rs @@ -192,4 +192,27 @@ impl PaymentsApiClient { ) .await } + + pub async fn create_mit_payment( + state: &SessionState, + request: subscription_types::CreateMitPaymentRequestData, + merchant_id: &str, + profile_id: &str, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let base_url = &state.conf.internal_services.payments_base_url; + let url = format!("{}/payments", base_url); + + Self::make_payment_api_call( + state, + services::Method::Post, + url, + Some(common_utils::request::RequestContent::Json(Box::new( + request, + ))), + "Create MIT Payment", + merchant_id, + profile_id, + ) + .await + } } diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index f207c243d26..657655c25bf 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -2622,7 +2622,7 @@ async fn subscription_incoming_webhook_flow( .await .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?; - let invoice_handler = subscription_with_handler.get_invoice_handler(profile); + let invoice_handler = subscription_with_handler.get_invoice_handler(profile.clone()); let payment_method_id = subscription_with_handler .subscription @@ -2635,7 +2635,7 @@ async fn subscription_incoming_webhook_flow( logger::info!("Payment method ID found: {}", payment_method_id); - let _invoice_new = invoice_handler + let invoice_entry = invoice_handler .create_invoice_entry( &state, billing_connector_mca_id.clone(), @@ -2648,5 +2648,33 @@ async fn subscription_incoming_webhook_flow( ) .await?; + let payment_response = invoice_handler + .create_mit_payment( + &state, + mit_payment_data.amount_due, + mit_payment_data.currency_code, + &payment_method_id.clone(), + ) + .await?; + + let updated_invoice = invoice_handler + .update_invoice( + &state, + invoice_entry.id.clone(), + payment_response.payment_method_id.clone(), + Some(payment_response.payment_id.clone()), + InvoiceStatus::from(payment_response.status), + ) + .await?; + + invoice_handler + .create_invoice_sync_job( + &state, + &updated_invoice, + mit_payment_data.invoice_id.get_string_repr().to_string(), + connector, + ) + .await?; + Ok(WebhookResponseTracker::NoEffect) } diff --git a/crates/router/src/workflows/invoice_sync.rs b/crates/router/src/workflows/invoice_sync.rs index ec2d2d7a913..c6daab02116 100644 --- a/crates/router/src/workflows/invoice_sync.rs +++ b/crates/router/src/workflows/invoice_sync.rs @@ -202,6 +202,7 @@ impl<'a> InvoiceSyncHandler<'a> { self.state, self.invoice.id.to_owned(), None, + None, common_enums::connector_enums::InvoiceStatus::from(invoice_sync_status), ) .await
2025-10-04T20:28:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pr completes [9400](https://github.com/juspay/hyperswitch/pull/9400) This pr adds support to do MIT payment for subscription and adds an invoice sync job Created Mit payment handler in subscription invoice_handler.rs and added create_invoice_sync_job after updating the invoice with the payment ID ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ``` Enable internal API key Auth by changing config/development.toml [internal_merchant_id_profile_id_auth] enabled = true internal_api_key = "test_internal_api_key" ``` 1. Create Merchant, API key, Payment connector, Billing Connector 2. Update profile to set the billing processor Request ``` curl --location 'http://localhost:8080/account/merchant_1759125756/business_profile/pro_71jcERFiZERp44d8fuSJ' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_0RJW0cwZDeGfSkod0eJWOkfZHK0PCoZtDYJJ1FxeHqhHky1VNPU6nkgFQiTFSDvA' \ --data '{ "billing_processor_id": "mca_NLnCEvS2DfuHWHFVa09o" }' ``` Response ``` {"merchant_id":"merchant_1759125756","profile_id":"pro_71jcERFiZERp44d8fuSJ","profile_name":"US_default","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"ZFjTKSE1EYiXaPcRhacrwlNh4wieUorlmP7r2uSHI8fyHigGmNCKY2hqVtzAq51m","redirect_to_merchant_with_http_post":false,"webhook_details":{"webhook_version":"1.0.1","webhook_username":"ekart_retail","webhook_password":"password_ekart@123","webhook_url":null,"payment_created_enabled":true,"payment_succeeded_enabled":true,"payment_failed_enabled":true,"payment_statuses_enabled":null,"refund_statuses_enabled":null,"payout_statuses_enabled":null},"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":null,"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":false,"payout_link_config":null,"outgoing_webhook_custom_http_headers":null,"tax_connector_id":null,"is_tax_connector_enabled":false,"is_network_tokenization_enabled":false,"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,"is_debit_routing_enabled":false,"merchant_business_country":null,"is_pre_network_tokenization_enabled":false,"acquirer_configs":null,"is_iframe_redirection_enabled":null,"merchant_category_code":null,"merchant_country_code":null,"dispute_polling_interval":null,"is_manual_retry_enabled":null,"always_enable_overcapture":null,"is_external_vault_enabled":"skip","external_vault_connector_details":null,"billing_processor_id":"mca_NLnCEvS2DfuHWHFVa09o"} ``` 3. Create Customer Request ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_0RJW0cwZDeGfSkod0eJWOkfZHK0PCoZtDYJJ1FxeHqhHky1VNPU6nkgFQiTFSDvA' \ --data-raw '{ "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` { "customer_id": "cus_OYy3hzTTt04Enegu3Go3", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-29T14:45:14.430Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null } ``` 7. Subscription create and confirm Request ``` curl --location 'http://localhost:8080/subscriptions' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_MiKOgwbj84jJ095MoWdj' \ --header 'api-key: dev_I62cGvBVijteiN61aMcAOeYvXpO8s36gT8BFvPznYYDXF4GFtVtjzgiel9oIpvUK' \ --data '{ "item_price_id": "cbdemo_enterprise-suite-monthly", "customer_id": "cus_efEv4nqfrYEo8wSKZ10C", "description": "Hello this is description", "merchant_reference_id": "mer_ref_1759334677", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com", "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" } } } }' ``` Response ``` { "id": "sub_CkPzNaFAyxzX2WwdKFCr", "merchant_reference_id": "mer_ref_1759334529", "status": "active", "plan_id": null, "price_id": null, "coupon": null, "profile_id": "pro_MiKOgwbj84jJ095MoWdj", "payment": { "payment_id": "sub_pay_KXEtoTxvu0EsadB5wxNn", "status": "succeeded", "amount": 14100, "currency": "INR", "connector": "stripe", "payment_method_id": "pm_bDPHgNaP7UZGjtZ7QPrS", "payment_experience": null, "error_code": null, "error_message": null }, "customer_id": "cus_uBtUJLSVSICr8ctmoL8i", "invoice": { "id": "invoice_Ht72m0Enqy4YOGRKAtbZ", "subscription_id": "sub_CkPzNaFAyxzX2WwdKFCr", "merchant_id": "merchant_1759157014", "profile_id": "pro_MiKOgwbj84jJ095MoWdj", "merchant_connector_id": "mca_oMyzcBFcpfISftwDDVuG", "payment_intent_id": "sub_pay_KXEtoTxvu0EsadB5wxNn", "payment_method_id": null, "customer_id": "cus_uBtUJLSVSICr8ctmoL8i", "amount": 14100, "currency": "INR", "status": "payment_pending" }, "billing_processor_subscription_id": "sub_CkPzNaFAyxzX2WwdKFCr" } ``` incoming webhook for chargebee ``` curl --location 'http://localhost:8080/webhooks/merchant_1758710612/mca_YH3XxYGMv6IbKD0icBie' \ --header 'api-key: dev_5LNrrMNqyyFle8hvMssLob9pFq6OIEh0Vl3DqZttFXiDe7wrrScUePEYrIiYfSKT' \ --header 'Content-Type: application/json' \ --header 'authorization: Basic aHlwZXJzd2l0Y2g6aHlwZXJzd2l0Y2g=' \ --data-raw '{ "api_version": "v2", "content": { "invoice": { "adjustment_credit_notes": [], "amount_adjusted": 0, "amount_due": 14100, "amount_paid": 0, "amount_to_collect": 14100, "applied_credits": [], "base_currency_code": "INR", "channel": "web", "credits_applied": 0, "currency_code": "INR", "customer_id": "gaurav_test", "date": 1758711043, "deleted": false, "due_date": 1758711043, "dunning_attempts": [], "exchange_rate": 1.0, "first_invoice": false, "generated_at": 1758711043, "has_advance_charges": false, "id": "3", "is_gifted": false, "issued_credit_notes": [], "line_items": [ { "amount": 14100, "customer_id": "gaurav_test", "date_from": 1758711043, "date_to": 1761303043, "description": "Enterprise Suite Monthly", "discount_amount": 0, "entity_id": "cbdemo_enterprise-suite-monthly", "entity_type": "plan_item_price", "id": "li_169vD0Uxi8JBp46g", "is_taxed": false, "item_level_discount_amount": 0, "object": "line_item", "pricing_model": "flat_fee", "quantity": 1, "subscription_id": "169vD0Uxi8JB746e", "tax_amount": 0, "tax_exempt_reason": "tax_not_configured", "unit_amount": 14100 } ], "linked_orders": [], "linked_payments": [], "net_term_days": 0, "new_sales_amount": 14100, "object": "invoice", "price_type": "tax_exclusive", "recurring": true, "reference_transactions": [], "resource_version": 1758711043846, "round_off_amount": 0, "site_details_at_creation": { "timezone": "Asia/Calcutta" }, "status": "payment_due", "sub_total": 14100, "subscription_id": "169vD0Uxi8JB746e", "tax": 0, "term_finalized": true, "total": 14100, "updated_at": 1758711043, "write_off_amount": 0 } }, "event_type": "invoice_generated", "id": "ev_169vD0Uxi8JDf46i", "object": "event", "occurred_at": 1758711043, "source": "admin_console", "user": "[email protected]", "webhook_status": "scheduled", "webhooks": [ { "id": "whv2_169mYOUxi3nvkZ8v", "object": "webhook", "webhook_status": "scheduled" } ] }' ``` response 200 ok ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> invoice sync finished <img width="1504" height="463" alt="image" src="https://github.com/user-attachments/assets/13e1469d-bb39-4484-b350-5ee278c66a3a" /> Record back successful <img width="1200" height="115" alt="image" src="https://github.com/user-attachments/assets/d221b8da-44dc-4790-86be-70dfd9f601df" /> invoice table entry <img width="668" height="402" alt="image" src="https://github.com/user-attachments/assets/29e59bea-dd08-4ae1-8e88-495abdaf8735" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c172f03c31e9b29b69490c7c5dfb3b4c78206f79
juspay/hyperswitch
juspay__hyperswitch-9642
Bug: [FEAT]: [Customer] Add search support to Customer API by Customer_ID ### Feature Description Currently, the Customer List API (/api/customers/list?limit=20&offset=0) does not support search functionality, which forces the dashboard to display customers without the ability to search dynamically. We want to enhance this API to support search across multiple fields so that users can quickly locate a customer. Supported fields for full text match: customer_id: "cust_abcdefgh" name: "venu" email: "[email protected]" phone: "+91234567890" ### Possible Implementation Add a search bar in the Dashboard UI for the Customer List page. The search bar should allow merchants to search using customer_id (partial or full match). Pass the search query to the backend API via query parameter, for example: ``` bash GET: /api/customers/list?limit=20&offset=0&customer_id=cus_12345 ``` ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index 19016e292a8..62fd000ddb8 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -52,6 +52,8 @@ pub struct CustomerListRequest { /// Limit #[schema(example = 32)] pub limit: Option<u16>, + /// Unique identifier for a customer + pub customer_id: Option<id_type::CustomerId>, } #[cfg(feature = "v1")] diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rs index def8d77fe7a..a6121d408c2 100644 --- a/crates/diesel_models/src/query/customers.rs +++ b/crates/diesel_models/src/query/customers.rs @@ -20,6 +20,7 @@ impl CustomerNew { pub struct CustomerListConstraints { pub limit: i64, pub offset: Option<i64>, + pub customer_id: Option<id_type::CustomerId>, } impl Customer { @@ -54,19 +55,66 @@ impl Customer { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } + #[cfg(feature = "v1")] pub async fn list_by_merchant_id( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, constraints: CustomerListConstraints, ) -> StorageResult<Vec<Self>> { - generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( - conn, - dsl::merchant_id.eq(merchant_id.to_owned()), - Some(constraints.limit), - constraints.offset, - Some(dsl::created_at), - ) - .await + if let Some(customer_id) = constraints.customer_id { + let predicate = dsl::merchant_id + .eq(merchant_id.clone()) + .and(dsl::customer_id.eq(customer_id)); + generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( + conn, + predicate, + Some(constraints.limit), + constraints.offset, + Some(dsl::created_at), + ) + .await + } else { + let predicate = dsl::merchant_id.eq(merchant_id.clone()); + generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( + conn, + predicate, + Some(constraints.limit), + constraints.offset, + Some(dsl::created_at), + ) + .await + } + } + + #[cfg(feature = "v2")] + pub async fn list_by_merchant_id( + conn: &PgPooledConn, + merchant_id: &id_type::MerchantId, + constraints: CustomerListConstraints, + ) -> StorageResult<Vec<Self>> { + if let Some(customer_id) = constraints.customer_id { + let predicate = dsl::merchant_id + .eq(merchant_id.clone()) + .and(dsl::merchant_reference_id.eq(customer_id)); + generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( + conn, + predicate, + Some(constraints.limit), + constraints.offset, + Some(dsl::created_at), + ) + .await + } else { + let predicate = dsl::merchant_id.eq(merchant_id.clone()); + generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( + conn, + predicate, + Some(constraints.limit), + constraints.offset, + Some(dsl::created_at), + ) + .await + } } #[cfg(feature = "v2")] diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 5a88cb6cd48..720296cdcac 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -538,6 +538,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { pub struct CustomerListConstraints { pub limit: u16, pub offset: Option<u32>, + pub customer_id: Option<id_type::CustomerId>, } impl From<CustomerListConstraints> for query::CustomerListConstraints { @@ -545,6 +546,7 @@ impl From<CustomerListConstraints> for query::CustomerListConstraints { Self { limit: i64::from(value.limit), offset: value.offset.map(i64::from), + customer_id: value.customer_id, } } } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index ffc44781037..09f12d62ba0 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -590,6 +590,7 @@ pub async fn list_customers( .limit .unwrap_or(crate::consts::DEFAULT_LIST_API_LIMIT), offset: request.offset, + customer_id: request.customer_id, }; let domain_customers = db diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index e2680666e4d..bea3ff4e58e 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -54,6 +54,7 @@ pub async fn rust_locker_migration( let constraints = CustomerListConstraints { limit: u16::MAX, offset: None, + customer_id: None, }; let domain_customers = db
2025-09-30T08:46:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR introduces improvements to the **Customer page API**: Added **search bar functionality** to filter customers by `customer_id`. These changes enhance API usability and improve performance when handling large customer datasets. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Search functionality allows **direct lookup by `customer_id`**, making customer retrieval faster and more user-friendly. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Executed the following API call to fetch the list of roles: Before: No search bar for the searching Items. ```bash curl --location 'http://localhost:8080/customers/list?limit=50&offset=0' \ --header 'Accept: application/json' \ --header 'api-key: <YOUR_API_KEY>' \ --header 'Content-Type: application/json' \ --data-binary '@' ``` Response: ```json [ { "customer_id": "cus_123", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T08:05:42.489Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_124", "name": "Venu Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:34:15.146Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_125", "name": "Venu Madhav", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:34:23.527Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_126", "name": "Bandarupalli", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:34:39.328Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_127", "name": "venu 2", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:35:06.393Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_128", "name": "venu 3", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:35:15.853Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_129", "name": "venu 4", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:35:21.549Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_129", "name": "venu 5", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:35:27.178Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_130", "name": "venu 6", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:35:51.674Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_131", "name": "venu 7", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:35:56.948Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_132", "name": "venu 8", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:36:03.017Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_133", "name": "venu 9", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T09:36:08.331Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_134", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null, "description": null, "address": null, "created_at": "2025-09-24T10:29:03.242Z", "metadata": null, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_135", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1", "description": null, "address": null, "created_at": "2025-09-24T10:30:14.808Z", "metadata": null, "default_payment_method_id": "pm_wQqUQeEP9YgJCLpa8NkG", "tax_registration_id": null }, { "customer_id": "cus_136", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1234", "description": null, "address": null, "created_at": "2025-09-24T13:49:24.111Z", "metadata": null, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_137", "name": "venu 10", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-25T13:25:45.670Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_138", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null, "description": null, "address": null, "created_at": "2025-09-25T13:39:37.242Z", "metadata": null, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_139", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null, "description": null, "address": null, "created_at": "2025-09-25T13:39:54.772Z", "metadata": null, "default_payment_method_id": null, "tax_registration_id": null }, { "customer_id": "cus_140", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null, "description": null, "address": null, "created_at": "2025-09-25T13:42:24.499Z", "metadata": null, "default_payment_method_id": null, "tax_registration_id": null } ] ``` After adding the customer_id search feature ```bash curl --location 'http://localhost:8080/customers/list?limit=50&offset=0&customer_id=cus_123' \ --header 'Accept: application/json' \ --header 'api-key: <YOUR_API_KEY>' \ --header 'Content-Type: application/json' \ --data-binary '@' ``` Response ```json [ { "customer_id": "cus_123", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-24T08:05:42.489Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
2d580b3afbca861028e010853dc33c75818c9288
juspay/hyperswitch
juspay__hyperswitch-9636
Bug: Add estimate endpoint
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index a2d643ca109..2c2eefe9259 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -44,7 +44,6 @@ pub mod relay; #[cfg(feature = "v2")] pub mod revenue_recovery_data_backfill; pub mod routing; -#[cfg(feature = "v1")] pub mod subscription; pub mod surcharge_decision_configs; pub mod three_ds_decision_rule; diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs index 2829d58b883..f7c33bd37ca 100644 --- a/crates/api_models/src/subscription.rs +++ b/crates/api_models/src/subscription.rs @@ -446,3 +446,52 @@ pub struct Invoice { } impl ApiEventMetric for ConfirmSubscriptionResponse {} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct EstimateSubscriptionQuery { + /// Identifier for the associated subscription plan. + pub plan_id: Option<String>, + + /// Identifier for the associated item_price_id for the subscription. + pub item_price_id: String, + + /// Idenctifier for the coupon code for the subscription. + pub coupon_code: Option<String>, +} + +impl ApiEventMetric for EstimateSubscriptionQuery {} + +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct EstimateSubscriptionResponse { + /// Estimated amount to be charged for the invoice. + pub amount: MinorUnit, + /// Currency for the amount. + pub currency: api_enums::Currency, + /// Identifier for the associated plan_id. + pub plan_id: Option<String>, + /// Identifier for the associated item_price_id for the subscription. + pub item_price_id: Option<String>, + /// Idenctifier for the coupon code for the subscription. + pub coupon_code: Option<String>, + /// Identifier for customer. + pub customer_id: Option<common_utils::id_type::CustomerId>, + pub line_items: Vec<SubscriptionLineItem>, +} + +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct SubscriptionLineItem { + /// Unique identifier for the line item. + pub item_id: String, + /// Type of the line item. + pub item_type: String, + /// Description of the line item. + pub description: String, + /// Amount for the line item. + pub amount: MinorUnit, + /// Currency for the line item + pub currency: common_enums::Currency, + /// Quantity of the line item. + pub quantity: i64, +} + +impl ApiEventMetric for EstimateSubscriptionResponse {} diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index f3e935c6dd5..70e14870ffb 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -1212,11 +1212,26 @@ impl ) -> CustomResult<String, errors::ConnectorError> { let metadata: chargebee::ChargebeeMetadata = utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?; - let url = self - .base_url(connectors) - .to_string() - .replace("{{merchant_endpoint_prefix}}", metadata.site.peek()); - Ok(format!("{url}v2/estimates/create_subscription_for_items")) + + let site = metadata.site.peek(); + + let mut base = self.base_url(connectors).to_string(); + + base = base.replace("{{merchant_endpoint_prefix}}", site); + base = base.replace("$", site); + + if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') { + return Err(errors::ConnectorError::InvalidConnectorConfig { + config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).", + } + .into()); + } + + if !base.ends_with('/') { + base.push('/'); + } + + Ok(format!("{base}v2/estimates/create_subscription_for_items")) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 324418e22b7..cbc5c4ab45b 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -1036,6 +1036,7 @@ impl<F, T> currency: estimate.subscription_estimate.currency_code, next_billing_at: estimate.subscription_estimate.next_billing_at, credits_applied: Some(estimate.invoice_estimate.credits_applied), + customer_id: Some(estimate.invoice_estimate.customer_id), line_items: estimate .invoice_estimate .line_items @@ -1215,6 +1216,7 @@ impl #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ChargebeeSubscriptionEstimateRequest { + #[serde(rename = "subscription_items[item_price_id][0]")] pub price_id: String, } @@ -1351,8 +1353,8 @@ pub struct SubscriptionEstimate { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct InvoiceEstimate { pub recurring: bool, - #[serde(with = "common_utils::custom_serde::iso8601")] - pub date: PrimitiveDateTime, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub date: Option<PrimitiveDateTime>, pub price_type: String, pub sub_total: MinorUnit, pub total: MinorUnit, @@ -1361,7 +1363,7 @@ pub struct InvoiceEstimate { pub amount_due: MinorUnit, /// type of the object will be `invoice_estimate` pub object: String, - pub customer_id: String, + pub customer_id: CustomerId, pub line_items: Vec<LineItem>, pub currency_code: enums::Currency, pub round_off_amount: MinorUnit, @@ -1370,10 +1372,10 @@ pub struct InvoiceEstimate { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LineItem { pub id: String, - #[serde(with = "common_utils::custom_serde::iso8601")] - pub date_from: PrimitiveDateTime, - #[serde(with = "common_utils::custom_serde::iso8601")] - pub date_to: PrimitiveDateTime, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub date_from: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub date_to: Option<PrimitiveDateTime>, pub unit_amount: MinorUnit, pub quantity: i64, pub amount: MinorUnit, diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs index 7280a2f3cca..722d627cb35 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs @@ -174,7 +174,9 @@ pub struct GetSubscriptionPlanPricesData { } #[derive(Debug, Clone)] -pub struct GetSubscriptionEstimateData; +pub struct GetSubscriptionEstimateData { + pub connector_meta_data: Option<pii::SecretSerdeValue>, +} #[derive(Debug, Clone)] pub struct UasFlowData { diff --git a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs index 183b2f7ed38..4e5f58a8907 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs @@ -36,7 +36,6 @@ pub enum SubscriptionStatus { Created, } -#[cfg(feature = "v1")] impl From<SubscriptionStatus> for api_models::subscription::SubscriptionStatus { fn from(status: SubscriptionStatus) -> Self { match status { @@ -82,7 +81,6 @@ pub struct SubscriptionPlanPrices { pub trial_period_unit: Option<PeriodUnit>, } -#[cfg(feature = "v1")] impl From<SubscriptionPlanPrices> for api_models::subscription::SubscriptionPlanPrices { fn from(item: SubscriptionPlanPrices) -> Self { Self { @@ -106,7 +104,6 @@ pub enum PeriodUnit { Year, } -#[cfg(feature = "v1")] impl From<PeriodUnit> for api_models::subscription::PeriodUnit { fn from(unit: PeriodUnit) -> Self { match unit { @@ -128,8 +125,28 @@ pub struct GetSubscriptionEstimateResponse { pub currency: Currency, pub next_billing_at: Option<PrimitiveDateTime>, pub line_items: Vec<SubscriptionLineItem>, + pub customer_id: Option<id_type::CustomerId>, } +impl From<GetSubscriptionEstimateResponse> + for api_models::subscription::EstimateSubscriptionResponse +{ + fn from(value: GetSubscriptionEstimateResponse) -> Self { + Self { + amount: value.total, + currency: value.currency, + plan_id: None, + item_price_id: None, + coupon_code: None, + customer_id: value.customer_id, + line_items: value + .line_items + .into_iter() + .map(api_models::subscription::SubscriptionLineItem::from) + .collect(), + } + } +} #[derive(Debug, Clone)] pub struct SubscriptionLineItem { pub item_id: String, @@ -141,3 +158,16 @@ pub struct SubscriptionLineItem { pub quantity: i64, pub pricing_model: Option<String>, } + +impl From<SubscriptionLineItem> for api_models::subscription::SubscriptionLineItem { + fn from(value: SubscriptionLineItem) -> Self { + Self { + item_id: value.item_id, + description: value.description, + item_type: value.item_type, + amount: value.amount, + currency: value.currency, + quantity: value.quantity, + } + } +} diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index 9d27c6daa75..f1c70fe1f62 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -11,10 +11,11 @@ use hyperswitch_domain_models::{ flow_common_types::{ AccessTokenFlowData, AuthenticationTokenFlowData, BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData, ExternalAuthenticationFlowData, - ExternalVaultProxyFlowData, FilesFlowData, GetSubscriptionPlanPricesData, - GetSubscriptionPlansData, GiftCardBalanceCheckFlowData, InvoiceRecordBackData, - MandateRevokeFlowData, PaymentFlowData, RefundFlowData, SubscriptionCreateData, - SubscriptionCustomerData, UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, + ExternalVaultProxyFlowData, FilesFlowData, GetSubscriptionEstimateData, + GetSubscriptionPlanPricesData, GetSubscriptionPlansData, GiftCardBalanceCheckFlowData, + InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, + SubscriptionCreateData, SubscriptionCustomerData, UasFlowData, VaultConnectorFlowData, + WebhookSourceVerifyData, }, RouterDataV2, }, @@ -895,6 +896,7 @@ default_router_data_conversion!(GetSubscriptionPlansData); default_router_data_conversion!(GetSubscriptionPlanPricesData); default_router_data_conversion!(SubscriptionCreateData); default_router_data_conversion!(SubscriptionCustomerData); +default_router_data_conversion!(GetSubscriptionEstimateData); impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for UasFlowData { fn from_old_router_data( diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 2d3fd649669..8066d48d356 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -422,3 +422,27 @@ pub async fn get_subscription( subscription.to_subscription_response(), )) } + +pub async fn get_estimate( + state: SessionState, + merchant_context: MerchantContext, + profile_id: common_utils::id_type::ProfileId, + query: subscription_types::EstimateSubscriptionQuery, +) -> RouterResponse<subscription_types::EstimateSubscriptionResponse> { + let profile = + SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) + .await + .attach_printable("subscriptions: failed to find business profile in get_estimate")?; + let billing_handler = BillingHandler::create( + &state, + merchant_context.get_merchant_account(), + merchant_context.get_merchant_key_store(), + None, + profile, + ) + .await?; + let estimate = billing_handler + .get_subscription_estimate(&state, query) + .await?; + Ok(ApplicationResponse::Json(estimate.into())) +} diff --git a/crates/router/src/core/subscription/billing_processor_handler.rs b/crates/router/src/core/subscription/billing_processor_handler.rs index 2e1d3b7ff7e..aa361ef8ce9 100644 --- a/crates/router/src/core/subscription/billing_processor_handler.rs +++ b/crates/router/src/core/subscription/billing_processor_handler.rs @@ -5,8 +5,8 @@ use common_utils::{ext_traits::ValueExt, pii}; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ - GetSubscriptionPlanPricesData, GetSubscriptionPlansData, InvoiceRecordBackData, - SubscriptionCreateData, SubscriptionCustomerData, + GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, + InvoiceRecordBackData, SubscriptionCreateData, SubscriptionCustomerData, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions as subscription_request_types, @@ -20,7 +20,10 @@ use hyperswitch_domain_models::{ use super::errors; use crate::{ - core::payments as payments_core, routes::SessionState, services, types::api as api_types, + core::{payments as payments_core, subscription::subscription_types}, + routes::SessionState, + services, + types::api as api_types, }; pub struct BillingHandler { @@ -283,6 +286,45 @@ impl BillingHandler { } } + pub async fn get_subscription_estimate( + &self, + state: &SessionState, + estimate_request: subscription_types::EstimateSubscriptionQuery, + ) -> errors::RouterResult<subscription_response_types::GetSubscriptionEstimateResponse> { + let estimate_req = subscription_request_types::GetSubscriptionEstimateRequest { + price_id: estimate_request.item_price_id.clone(), + }; + + let router_data = self.build_router_data( + state, + estimate_req, + GetSubscriptionEstimateData { + connector_meta_data: self.connector_metadata.clone(), + }, + )?; + let connector_integration = self.connector_data.connector.get_connector_integration(); + + let response = Box::pin(self.call_connector( + state, + router_data, + "get subscription estimate from connector", + connector_integration, + )) + .await?; + + match response { + Ok(response_data) => Ok(response_data), + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: self.connector_data.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + } + .into()), + } + } + pub async fn get_subscription_plans( &self, state: &SessionState, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 20ae7ddce02..7fdf59c2718 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1187,6 +1187,7 @@ impl Subscription { subscription::create_subscription(state, req, payload) }), )) + .service(web::resource("/estimate").route(web::get().to(subscription::get_estimate))) .service( web::resource("/plans").route(web::get().to(subscription::get_subscription_plans)), ) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 87513e6e23a..da8a2a23ec2 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -91,6 +91,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ConfirmSubscription | Flow::CreateAndConfirmSubscription | Flow::GetSubscription + | Flow::GetSubscriptionEstimate | Flow::GetPlansForSubscription => Self::Subscription, Flow::RetrieveForexFlow => Self::Forex, Flow::AddToBlocklist => Self::Blocklist, diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs index 46432810450..735f530d3c2 100644 --- a/crates/router/src/routes/subscription.rs +++ b/crates/router/src/routes/subscription.rs @@ -7,6 +7,7 @@ use std::str::FromStr; use actix_web::{web, HttpRequest, HttpResponse, Responder}; use api_models::subscription as subscription_types; +use error_stack::report; use hyperswitch_domain_models::errors; use router_env::{ tracing::{self, instrument}, @@ -252,3 +253,40 @@ pub async fn create_and_confirm_subscription( )) .await } + +/// add support for get subscription estimate +#[instrument(skip_all)] +pub async fn get_estimate( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<subscription_types::EstimateSubscriptionQuery>, +) -> impl Responder { + let flow = Flow::GetSubscriptionEstimate; + let profile_id = match extract_profile_id(&req) { + Ok(id) => id, + Err(response) => return response, + }; + let api_auth = auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }; + let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { + Ok(auth) => auth, + Err(err) => return oss_api::log_and_return_error_response(report!(err)), + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + query.into_inner(), + |state, auth: auth::AuthenticationData, query, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + subscription::get_estimate(state, merchant_context, profile_id.clone(), query) + }, + &*auth_type, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 5200047db57..5366efcf365 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -273,6 +273,8 @@ pub enum Flow { CreateAndConfirmSubscription, /// Get Subscription flow GetSubscription, + /// Get Subscription estimate flow + GetSubscriptionEstimate, /// Create dynamic routing CreateDynamicRoutingConfig, /// Toggle dynamic routing
2025-10-01T08:59:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add support in subscription to get an estimate for the provided plan_price ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create merchant, API Key, billing processor 2. GET subscription estimate Request ``` curl --location 'http://localhost:8080/subscriptions/estimate?item_price_id=standard-plan-USD-Monthly' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_BSjmSsJE4oqVfDdiJViI' \ --header 'api-key: dev_4IM0uzCEoKQ9lkSaTUEceuErgHTSnZhcc0CsjiSc1P2jVv5W4p9nYumBWwnJLqLb' ``` Response ``` { "amount": 1200, "currency": "USD", "plan_id": null, "item_price_id": null, "coupon_code": null, "customer_id": "Azyd6UUz25MpkdBC", "line_items": [ { "item_id": "standard-plan-USD-Monthly", "item_type": "plan_item_price", "description": "Standard Plan", "amount": 1200, "currency": "USD", "quantity": 1 } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b52aafa8873fc4704bd69014cc457daf32d5523c
juspay/hyperswitch
juspay__hyperswitch-9634
Bug: Nexixpay MIT & order_id fix 1. We should use same order id of max length 18 among multiple payment calls made to nexi for an order. 2. Capture and Cancel calls for manual MITs are failing as we don't store connector_metadata in nexi mandate response.
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 2cf30de8edf..ff8dbad6424 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -29,7 +29,6 @@ use hyperswitch_domain_models::{ }; use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors}; use masking::{ExposeInterface, Secret}; -use rand::distributions::{Alphanumeric, DistString}; use serde::{Deserialize, Serialize}; use strum::Display; @@ -43,10 +42,6 @@ use crate::{ }, }; -fn get_random_string() -> String { - Alphanumeric.sample_string(&mut rand::thread_rng(), MAX_ORDER_ID_LENGTH) -} - #[derive(Clone, Copy, Debug)] enum AddressKind { Billing, @@ -541,6 +536,28 @@ pub fn get_error_response( } } +fn get_nexi_order_id(payment_id: &str) -> CustomResult<String, errors::ConnectorError> { + if payment_id.len() > MAX_ORDER_ID_LENGTH { + if payment_id.starts_with("pay_") { + Ok(payment_id + .chars() + .take(MAX_ORDER_ID_LENGTH) + .collect::<String>()) + } else { + Err(error_stack::Report::from( + errors::ConnectorError::MaxFieldLengthViolated { + field_name: "payment_id".to_string(), + connector: "Nexixpay".to_string(), + max_length: MAX_ORDER_ID_LENGTH, + received_length: payment_id.len(), + }, + )) + } + } else { + Ok(payment_id.to_string()) + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDSAuthData { @@ -714,22 +731,7 @@ impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaym fn try_from( item: &NexixpayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let order_id = if item.router_data.payment_id.len() > MAX_ORDER_ID_LENGTH { - if item.router_data.payment_id.starts_with("pay_") { - get_random_string() - } else { - return Err(error_stack::Report::from( - errors::ConnectorError::MaxFieldLengthViolated { - field_name: "payment_id".to_string(), - connector: "Nexixpay".to_string(), - max_length: MAX_ORDER_ID_LENGTH, - received_length: item.router_data.payment_id.len(), - }, - )); - } - } else { - item.router_data.payment_id.clone() - }; + let order_id = get_nexi_order_id(&item.router_data.payment_id)?; let billing_address = get_validated_billing_address(item.router_data)?; let shipping_address = get_validated_shipping_address(item.router_data)?; @@ -1124,6 +1126,22 @@ impl<F> NexixpayPaymentsResponse::MandateResponse(ref mandate_response) => { let status = AttemptStatus::from(mandate_response.operation.operation_result.clone()); + let is_auto_capture = item.data.request.is_auto_capture()?; + let operation_id = mandate_response.operation.operation_id.clone(); + 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 + })); match status { AttemptStatus::Failure => { let response = Err(get_error_response( @@ -1143,7 +1161,7 @@ impl<F> ), redirection_data: Box::new(None), mandate_reference: Box::new(None), - connector_metadata: None, + connector_metadata, network_txn_id: None, connector_response_reference_id: Some( mandate_response.operation.order_id.clone(), @@ -1318,22 +1336,7 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>> )?; let capture_type = get_nexixpay_capture_type(item.router_data.request.capture_method)?; - let order_id = if item.router_data.payment_id.len() > MAX_ORDER_ID_LENGTH { - if item.router_data.payment_id.starts_with("pay_") { - get_random_string() - } else { - return Err(error_stack::Report::from( - errors::ConnectorError::MaxFieldLengthViolated { - field_name: "payment_id".to_string(), - connector: "Nexixpay".to_string(), - max_length: MAX_ORDER_ID_LENGTH, - received_length: item.router_data.payment_id.len(), - }, - )); - } - } else { - item.router_data.payment_id.clone() - }; + let order_id = get_nexi_order_id(&item.router_data.payment_id)?; let amount = item.amount.clone(); let billing_address = get_validated_billing_address(item.router_data)?;
2025-10-01T11:07:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Use same order_id or max length 18 for all payment calls associated with an merchant order. We need to store connector_metadata in case of MIT payments also so that MIT payments can be manually captured or cancelled later. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Curls for testing with response: Payments create: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_n5vnntb0V5gRjNMdwTnPXweumExJV6vYon3lVNzW2BoA3F4S4V0PXDHK3lW7gWHh' \ --data-raw '{ "amount": 3545, "currency": "EUR", "profile_id":"pro_QEwjCvFhpcLC2azRNZEf", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111 1111 1111 1111", "card_exp_month": "03", "card_exp_year": "30", "card_cvc": "737" } }, "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "setup_future_usage": "off_session", "customer": { "id": "customerssh", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "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", "country": "BR", "zip": "94122", "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": "BR", "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 }' ``` Response: ``` {"payment_id":"pay_cfn9IZqdJU58r5Hc5A8T","merchant_id":"merchant_1759144749","status":"requires_customer_action","amount":3545,"net_amount":3545,"shipping_cost":null,"amount_capturable":3545,"amount_received":null,"connector":"nexixpay","client_secret":"pay_cfn9IZqdJU58r5Hc5A8T_secret_SXeMcpBgyEL2zoVijZ9E","created":"2025-10-01T12:45:53.600Z","currency":"EUR","customer_id":"customerssh","customer":{"id":"customerssh","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":"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":"30","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":"token_nVp5RBRCLCFnQQH82Y5F","shipping":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"billing":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":[{"sku":null,"upc":null,"brand":null,"amount":3545,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Apple iphone 15","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":null,"product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":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":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_cfn9IZqdJU58r5Hc5A8T/merchant_1759144749/pay_cfn9IZqdJU58r5Hc5A8T_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":"customerssh","created_at":1759322753,"expires":1759326353,"secret":"epk_dfc71e93bf654eaabccbfcbcf83fa3e0"},"manual_retry_allowed":null,"connector_transaction_id":"pay_cfn9IZqdJU58r5","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":{"order_category":"pay"},"braintree":null,"adyen":null},"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_cfn9IZqdJU58r5","payment_link":null,"profile_id":"pro_QEwjCvFhpcLC2azRNZEf","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_lJPT4aN2CbXmgSAFDmCT","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-10-01T13:00:53.600Z","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_channel":null,"payment_method_id":"pm_AHMtQP8Qp9y1L8wy2hNi","network_transaction_id":null,"payment_method_status":"inactive","updated":"2025-10-01T12:45:56.426Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"request_extended_authorization":null,"capture_before":null,"merchant_order_reference_id":"test_ord","order_tax_amount":null,"connector_mandate_id":"qAhdJaa3HvEeMxexwg","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` Payments retrieve Response: ``` {"payment_id":"pay_cfn9IZqdJU58r5Hc5A8T","merchant_id":"merchant_1759144749","status":"succeeded","amount":3545,"net_amount":3545,"shipping_cost":null,"amount_capturable":0,"amount_received":3545,"connector":"nexixpay","client_secret":"pay_cfn9IZqdJU58r5Hc5A8T_secret_SXeMcpBgyEL2zoVijZ9E","created":"2025-10-01T12:45:53.600Z","currency":"EUR","customer_id":"customerssh","customer":{"id":"customerssh","name":"John Doe","email":"[email protected]","phone":"9999999999","phone_country_code":"+1"},"description":"Its my first payment request","refunds":null,"disputes":null,"attempts":[{"attempt_id":"pay_cfn9IZqdJU58r5Hc5A8T_1","status":"charged","amount":3545,"order_tax_amount":null,"currency":"EUR","connector":"nexixpay","error_message":null,"payment_method":"card","connector_transaction_id":"pay_cfn9IZqdJU58r5","capture_method":"automatic","authentication_type":"three_ds","created_at":"2025-10-01T12:45:53.601Z","modified_at":"2025-10-01T12:46:51.867Z","cancellation_reason":null,"mandate_id":null,"error_code":null,"payment_token":"token_nVp5RBRCLCFnQQH82Y5F","connector_metadata":{"psyncFlow":"Authorize","cancelOperationId":null,"threeDSAuthResult":{"authenticationValue":"AAkBBzglVwAAAA3Zl4J0dQAAAAA="},"captureOperationId":"804610282286352749","threeDSAuthResponse":"notneeded","authorizationOperationId":"804610282286352749"},"payment_experience":null,"payment_method_type":"credit","reference_id":"pay_cfn9IZqdJU58r5","unified_code":null,"unified_message":null,"client_source":null,"client_version":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":"30","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":"token_nVp5RBRCLCFnQQH82Y5F","shipping":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"billing":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":[{"sku":null,"upc":null,"brand":null,"amount":3545,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Apple iphone 15","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":null,"product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":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":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":null,"connector_transaction_id":"pay_cfn9IZqdJU58r5","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":{"order_category":"pay"},"braintree":null,"adyen":null},"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_cfn9IZqdJU58r5","payment_link":null,"profile_id":"pro_QEwjCvFhpcLC2azRNZEf","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_lJPT4aN2CbXmgSAFDmCT","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-10-01T13:00:53.600Z","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_channel":null,"payment_method_id":"pm_AHMtQP8Qp9y1L8wy2hNi","network_transaction_id":null,"payment_method_status":"active","updated":"2025-10-01T12:46:51.868Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"request_extended_authorization":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,"is_iframe_redirection_enabled":null,"whole_connector_response":null,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` MIT call: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_n5vnntb0V5gRjNMdwTnPXweumExJV6vYon3lVNzW2BoA3F4S4V0PXDHK3lW7gWHh' \ --data '{ "amount": 3545, "currency": "EUR", "confirm": true, "customer_id": "customerssh", "capture_method": "manual", "recurring_details": { "type": "payment_method_id", "data": "pm_AHMtQP8Qp9y1L8wy2hNi" }, "off_session": true }' ``` Response: ``` {"payment_id":"pay_qBDBW4zQXKiwHnhTRX0Q","merchant_id":"merchant_1759144749","status":"requires_capture","amount":3545,"net_amount":3545,"shipping_cost":null,"amount_capturable":3545,"amount_received":null,"connector":"nexixpay","client_secret":"pay_qBDBW4zQXKiwHnhTRX0Q_secret_yvNWTrkL2gCyNEJGNa29","created":"2025-10-01T12:49:57.717Z","currency":"EUR","customer_id":"customerssh","customer":{"id":"customerssh","name":"John Doe","email":"[email protected]","phone":"9999999999","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","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":"30","card_holder_name":"joseph 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":"9999999999","return_url":null,"authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"customerssh","created_at":1759322997,"expires":1759326597,"secret":"epk_f372c1555499482683008ee1d2de5fe9"},"manual_retry_allowed":null,"connector_transaction_id":"pay_qBDBW4zQXKiwHn","frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_qBDBW4zQXKiwHn","payment_link":null,"profile_id":"pro_QEwjCvFhpcLC2azRNZEf","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_lJPT4aN2CbXmgSAFDmCT","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-10-01T13:04:57.717Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_AHMtQP8Qp9y1L8wy2hNi","network_transaction_id":null,"payment_method_status":"active","updated":"2025-10-01T12:49:59.679Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"request_extended_authorization":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"qAhdJaa3HvEeMxexwg","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` Cancel Call: ``` curl --location 'http://localhost:8080/payments/pay_qBDBW4zQXKiwHnhTRX0Q/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_n5vnntb0V5gRjNMdwTnPXweumExJV6vYon3lVNzW2BoA3F4S4V0PXDHK3lW7gWHh' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` Response: ``` {"payment_id":"pay_qBDBW4zQXKiwHnhTRX0Q","merchant_id":"merchant_1759144749","status":"processing","amount":3545,"net_amount":3545,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"nexixpay","client_secret":"pay_qBDBW4zQXKiwHnhTRX0Q_secret_yvNWTrkL2gCyNEJGNa29","created":"2025-10-01T12:49:57.717Z","currency":"EUR","customer_id":"customerssh","customer":{"id":"customerssh","name":"John Doe","email":"[email protected]","phone":"9999999999","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","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":"30","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"}},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"9999999999","return_url":null,"authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":"requested_by_customer","error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":null,"connector_transaction_id":"pay_qBDBW4zQXKiwHn","frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_qBDBW4zQXKiwHn","payment_link":null,"profile_id":"pro_QEwjCvFhpcLC2azRNZEf","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_lJPT4aN2CbXmgSAFDmCT","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-10-01T13:04:57.717Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_AHMtQP8Qp9y1L8wy2hNi","network_transaction_id":null,"payment_method_status":null,"updated":"2025-10-01T12:51:38.055Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"request_extended_authorization":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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` Payments retrieve Response: ``` {"payment_id":"pay_qBDBW4zQXKiwHnhTRX0Q","merchant_id":"merchant_1759144749","status":"cancelled","amount":3545,"net_amount":3545,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"nexixpay","client_secret":"pay_qBDBW4zQXKiwHnhTRX0Q_secret_yvNWTrkL2gCyNEJGNa29","created":"2025-10-01T12:49:57.717Z","currency":"EUR","customer_id":"customerssh","customer":{"id":"customerssh","name":"John Doe","email":"[email protected]","phone":"9999999999","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"attempts":[{"attempt_id":"pay_qBDBW4zQXKiwHnhTRX0Q_1","status":"pending","amount":3545,"order_tax_amount":null,"currency":"EUR","connector":"nexixpay","error_message":null,"payment_method":"card","connector_transaction_id":"pay_qBDBW4zQXKiwHn","capture_method":"manual","authentication_type":"no_three_ds","created_at":"2025-10-01T12:49:57.717Z","modified_at":"2025-10-01T12:51:38.055Z","cancellation_reason":"requested_by_customer","mandate_id":null,"error_code":null,"payment_token":null,"connector_metadata":{"psyncFlow":"Cancel","cancelOperationId":"6dc6af6b-37b9-4aa6-8bf1-0d52ae064e8d","threeDSAuthResult":null,"captureOperationId":null,"threeDSAuthResponse":null,"authorizationOperationId":"486536903848752749"},"payment_experience":null,"payment_method_type":"credit","reference_id":"pay_qBDBW4zQXKiwHn","unified_code":null,"unified_message":null,"client_source":null,"client_version":null}],"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","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":"30","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"}},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"9999999999","return_url":null,"authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":"requested_by_customer","error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":null,"connector_transaction_id":"pay_qBDBW4zQXKiwHn","frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_qBDBW4zQXKiwHn","payment_link":null,"profile_id":"pro_QEwjCvFhpcLC2azRNZEf","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_lJPT4aN2CbXmgSAFDmCT","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-10-01T13:04:57.717Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_AHMtQP8Qp9y1L8wy2hNi","network_transaction_id":null,"payment_method_status":"active","updated":"2025-10-01T12:52:35.250Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"request_extended_authorization":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"CEivq9z9Q2r87ktZQG","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` Authorize call <img width="1728" height="474" alt="image" src="https://github.com/user-attachments/assets/f58993b2-549f-4d70-9230-03dd03895b3c" /> Complete authorize call: <img width="1728" height="474" alt="image" src="https://github.com/user-attachments/assets/c9245cf3-1714-4b6a-8bca-c836c819f821" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9312cfa3c85e350c12bd64306037a72753b532bd
juspay/hyperswitch
juspay__hyperswitch-9681
Bug: [FEATURE] Finix non3ds card ### Feature Description Implement non3ds card for finix ### Possible Implementation Void, refund, auth, capture, tokenization, customer create ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index bde1e29ba78..765eb9b6d26 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -442,6 +442,10 @@ debit = { country = "US, CA", currency = "CAD,USD"} [pm_filters.facilitapay] pix = { country = "BR", currency = "BRL" } +[pm_filters.finix] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -875,6 +879,7 @@ stripe = { long_lived_token = false, payment_method = "wallet", payment_method_t billwerk = {long_lived_token = false, payment_method = "card"} globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } +finix= { long_lived_token = false, payment_method = "card" } [webhooks] outgoing_enabled = true diff --git a/config/deployments/production.toml b/config/deployments/production.toml index e078e4c50cf..546e0be8da3 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -525,6 +525,10 @@ debit = { country = "US, CA", currency = "CAD,USD"} [pm_filters.facilitapay] pix = { country = "BR", currency = "BRL" } +[pm_filters.finix] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -884,6 +888,7 @@ stripe = { long_lived_token = false, payment_method = "wallet", payment_method_t billwerk = {long_lived_token = false, payment_method = "card"} globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } +finix= { long_lived_token = false, payment_method = "card" } [webhooks] outgoing_enabled = true diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 4c777e8a62f..fe15c0be287 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -507,6 +507,10 @@ debit = { country = "US, CA", currency = "CAD,USD"} [pm_filters.facilitapay] pix = { country = "BR", currency = "BRL" } +[pm_filters.finix] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -890,6 +894,7 @@ stripe = { long_lived_token = false, payment_method = "wallet", payment_method_t billwerk = {long_lived_token = false, payment_method = "card"} globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } +finix= { long_lived_token = false, payment_method = "card" } [webhooks] outgoing_enabled = true diff --git a/config/development.toml b/config/development.toml index 6d468c4656d..9e634a02d21 100644 --- a/config/development.toml +++ b/config/development.toml @@ -711,6 +711,10 @@ debit = { country = "AD,AT,AU,BE,BG,CA,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GG,GI,GR,HK [pm_filters.facilitapay] pix = { country = "BR", currency = "BRL" } +[pm_filters.finix] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -1021,6 +1025,7 @@ gocardless = { long_lived_token = true, payment_method = "bank_debit" } billwerk = { long_lived_token = false, payment_method = "card" } dwolla = { long_lived_token = true, payment_method = "bank_debit" } globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" } +finix= { long_lived_token = false, payment_method = "card" } [temp_locker_enable_config] stripe = { payment_method = "bank_transfer" } diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 532123c3501..579f37c5825 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -96,6 +96,7 @@ pub enum RoutableConnectors { Ebanx, Elavon, Facilitapay, + Finix, Fiserv, Fiservemea, Fiuu, @@ -274,6 +275,7 @@ pub enum Connector { Ebanx, Elavon, Facilitapay, + Finix, Fiserv, Fiservemea, Fiuu, @@ -476,6 +478,7 @@ impl Connector { | Self::Ebanx | Self::Elavon | Self::Facilitapay + | Self::Finix | Self::Fiserv | Self::Fiservemea | Self::Fiuu @@ -664,6 +667,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Ebanx => Self::Ebanx, RoutableConnectors::Elavon => Self::Elavon, RoutableConnectors::Facilitapay => Self::Facilitapay, + RoutableConnectors::Finix => Self::Finix, RoutableConnectors::Fiserv => Self::Fiserv, RoutableConnectors::Fiservemea => Self::Fiservemea, RoutableConnectors::Fiuu => Self::Fiuu, @@ -804,6 +808,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Ebanx => Ok(Self::Ebanx), Connector::Elavon => Ok(Self::Elavon), Connector::Facilitapay => Ok(Self::Facilitapay), + Connector::Finix => Ok(Self::Finix), 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 95594dfb4af..694946c4233 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -499,6 +499,7 @@ impl ConnectorConfig { Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Elavon => Ok(connector_data.elavon), Connector::Facilitapay => Ok(connector_data.facilitapay), + Connector::Finix => Ok(connector_data.finix), 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 027c82e3af8..b4fc51bb2d6 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7236,9 +7236,28 @@ required = true type = "Text" [finix] -[finix.connector_auth.HeaderKey] -api_key = "API Key" - +[finix.connector_auth.SignatureKey] +api_key = "Username" +api_secret = "Password" +key1 = "Merchant Id" +[[finix.credit]] +payment_method_type = "Mastercard" +[[finix.credit]] +payment_method_type = "Visa" +[[finix.credit]] +payment_method_type = "AmericanExpress" +[[finix.credit]] +payment_method_type = "Discover" +[[finix.credit]] +payment_method_type = "JCB" +[[finix.credit]] +payment_method_type = "DinersClub" +[[finix.credit]] +payment_method_type = "UnionPay" +[[finix.credit]] +payment_method_type = "Interac" +[[finix.credit]] +payment_method_type = "Maestro" [loonio] [loonio.connector_auth.BodyKey] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 93d7d1f26e7..40c2a9824fb 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5974,8 +5974,29 @@ required = true type = "Text" [finix] -[finix.connector_auth.HeaderKey] -api_key = "API Key" +[finix.connector_auth.SignatureKey] +api_key = "Username" +api_secret = "Password" +key1 = "Merchant Id" +[[finix.credit]] +payment_method_type = "Mastercard" +[[finix.credit]] +payment_method_type = "Visa" +[[finix.credit]] +payment_method_type = "AmericanExpress" +[[finix.credit]] +payment_method_type = "Discover" +[[finix.credit]] +payment_method_type = "JCB" +[[finix.credit]] +payment_method_type = "DinersClub" +[[finix.credit]] +payment_method_type = "UnionPay" +[[finix.credit]] +payment_method_type = "Interac" +[[finix.credit]] +payment_method_type = "Maestro" + [loonio] [loonio.connector_auth.BodyKey] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 77ade3ef742..bf8b119a006 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7199,7 +7199,6 @@ label = "Site where transaction is initiated" placeholder = "Enter site where transaction is initiated" required = true type = "Text" - [gigadat_payout] [gigadat_payout.connector_auth.SignatureKey] api_key = "Access Token" @@ -7215,8 +7214,28 @@ required = true type = "Text" [finix] -[finix.connector_auth.HeaderKey] -api_key = "API Key" +[finix.connector_auth.SignatureKey] +api_key = "Username" +api_secret = "Password" +key1 = "Merchant Id" +[[finix.credit]] +payment_method_type = "Mastercard" +[[finix.credit]] +payment_method_type = "Visa" +[[finix.credit]] +payment_method_type = "AmericanExpress" +[[finix.credit]] +payment_method_type = "Discover" +[[finix.credit]] +payment_method_type = "JCB" +[[finix.credit]] +payment_method_type = "DinersClub" +[[finix.credit]] +payment_method_type = "UnionPay" +[[finix.credit]] +payment_method_type = "Interac" +[[finix.credit]] +payment_method_type = "Maestro" [loonio] diff --git a/crates/hyperswitch_connectors/src/connectors/finix.rs b/crates/hyperswitch_connectors/src/connectors/finix.rs index d42f50a1532..d47f03adf65 100644 --- a/crates/hyperswitch_connectors/src/connectors/finix.rs +++ b/crates/hyperswitch_connectors/src/connectors/finix.rs @@ -2,7 +2,8 @@ pub mod transformers; use std::sync::LazyLock; -use common_enums::{enums, ConnectorIntegrationStatus}; +use base64::Engine; +use common_enums::{enums, CaptureMethod, ConnectorIntegrationStatus, PaymentMethodType}; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, @@ -17,18 +18,20 @@ use hyperswitch_domain_models::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, + CreateConnectorCustomer, }, 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, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -72,11 +75,175 @@ impl api::Refund for Finix {} impl api::RefundExecute for Finix {} impl api::RefundSync for Finix {} impl api::PaymentToken for Finix {} +impl api::ConnectorCustomer for Finix {} + +impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> + for Finix +{ + fn get_headers( + &self, + req: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>, + 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: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/identities", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = finix::FinixRouterData::try_from((MinorUnit::zero(), req))?; + let connector_req = finix::FinixCreateIdentityRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>, + 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: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult< + RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>, + errors::ConnectorError, + > { + let response: finix::FinixIdentityResponse = res + .response + .parse_struct("Finix IdentityResponse") + .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<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Finix { - // Not Implemented (R) + fn get_headers( + &self, + req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>, + 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: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/payment_instruments", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = finix::FinixRouterData::try_from((MinorUnit::zero(), req))?; + let connector_req = + finix::FinixCreatePaymentInstrumentRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::TokenizationType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::TokenizationType::get_headers(self, req, connectors)?) + .set_body(types::TokenizationType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult< + RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>, + errors::ConnectorError, + > { + let response: finix::FinixInstrumentResponse = res + .response + .parse_struct("Finix InstrumentResponse") + .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<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Finix @@ -121,9 +288,19 @@ impl ConnectorCommon for Finix { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = finix::FinixAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let credentials = format!( + "{}:{}", + auth.finix_user_name.clone().expose(), + auth.finix_password.clone().expose() + ); + let encoded = format!( + "Basic {:}", + base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes()) + ); + Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), + encoded.into_masked(), )]) } @@ -142,9 +319,9 @@ impl ConnectorCommon for Finix { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response.get_code(), + message: response.get_message(), + reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, @@ -158,7 +335,7 @@ impl ConnectorCommon for Finix { impl ConnectorValidation for Finix { fn validate_mandate_payment( &self, - _pm_type: Option<enums::PaymentMethodType>, + _pm_type: Option<PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { match pm_data { @@ -204,10 +381,16 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, - _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let flow = match req.request.capture_method.unwrap_or_default() { + CaptureMethod::Automatic | CaptureMethod::SequentialAutomatic => "transfers", + CaptureMethod::Manual | CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => { + "authorizations" + } + }; + Ok(format!("{}/{}", self.base_url(connectors), flow)) } fn get_request_body( @@ -221,7 +404,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req.request.currency, )?; - let connector_router_data = finix::FinixRouterData::from((amount, req)); + let connector_router_data = finix::FinixRouterData::try_from((amount, req))?; let connector_req = finix::FinixPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -260,11 +443,14 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .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, - }) + finix::get_finix_response( + ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + finix::FinixFlow::get_flow_for_auth(data.request.capture_method.unwrap_or_default()), + ) } fn get_error_response( @@ -291,10 +477,24 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fin 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)?; + match finix::FinixId::from(connector_transaction_id) { + transformers::FinixId::Auth(id) => Ok(format!( + "{}/authorizations/{}", + self.base_url(connectors), + id + )), + transformers::FinixId::Transfer(id) => { + Ok(format!("{}/transfers/{}", self.base_url(connectors), id)) + } + } } fn build_request( @@ -324,11 +524,18 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fin .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, - }) + let response_id = response.id.clone(); + finix::get_finix_response( + ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + match finix::FinixId::from(response_id) { + finix::FinixId::Auth(_) => finix::FinixFlow::Auth, + finix::FinixId::Transfer(_) => finix::FinixFlow::Transfer, + }, + ) } fn get_error_response( @@ -355,18 +562,30 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn get_url( &self, - _req: &PaymentsCaptureRouterData, - _connectors: &Connectors, + req: &PaymentsCaptureRouterData, + 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.clone(); + Ok(format!( + "{}/authorizations/{}", + self.base_url(connectors), + connector_transaction_id + )) } fn get_request_body( &self, - _req: &PaymentsCaptureRouterData, + req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, + req.request.currency, + )?; + let connector_router_data = finix::FinixRouterData::try_from((amount, req))?; + let connector_req = finix::FinixCaptureRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -376,7 +595,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() - .method(Method::Post) + .method(Method::Put) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( @@ -397,15 +616,18 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: finix::FinixPaymentsResponse = res .response - .parse_struct("Finix PaymentsCaptureResponse") + .parse_struct("Finix 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, - }) + finix::get_finix_response( + ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + finix::FinixFlow::Capture, + ) } fn get_error_response( @@ -417,7 +639,89 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Finix {} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Finix { + fn get_headers( + &self, + req: &PaymentsCancelRouterData, + 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: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_transaction_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}/authorizations/{}", + self.base_url(connectors), + connector_transaction_id + )) + } + + fn get_request_body( + &self, + _req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = finix::FinixCancelRequest { void_me: true }; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Put) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(types::PaymentsVoidType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + let response: finix::FinixPaymentsResponse = res + .response + .parse_struct("Finix PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + finix::get_finix_response( + ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + finix::FinixFlow::Transfer, + ) + } + + 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<Execute, RefundsData, RefundsResponseData> for Finix { fn get_headers( @@ -434,10 +738,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Finix { 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!( + "{}/transfers/{}/reversals", + self.base_url(connectors), + req.request.connector_transaction_id + )) } fn get_request_body( @@ -451,8 +759,8 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Finix { req.request.currency, )?; - let connector_router_data = finix::FinixRouterData::from((refund_amount, req)); - let connector_req = finix::FinixRefundRequest::try_from(&connector_router_data)?; + let connector_router_data = finix::FinixRouterData::try_from((refund_amount, req))?; + let connector_req = finix::FinixCreateRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -481,9 +789,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Finix { event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: finix::RefundResponse = res + let response: finix::FinixPaymentsResponse = res .response - .parse_struct("finix RefundResponse") + .parse_struct("FinixPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -518,10 +826,19 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Finix { 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 + .connector_refund_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; + Ok(format!( + "{}/transfers/{}", + self.base_url(connectors), + refund_id + )) } fn build_request( @@ -548,9 +865,9 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Finix { event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: finix::RefundResponse = res + let response: finix::FinixPaymentsResponse = res .response - .parse_struct("finix RefundSyncResponse") + .parse_struct("FinixPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -594,8 +911,61 @@ impl webhooks::IncomingWebhook for Finix { } } -static FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = - LazyLock::new(SupportedPaymentMethods::new); +static FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let default_capture_methods = vec![CaptureMethod::Automatic, CaptureMethod::Manual]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::Maestro, + ]; + + let mut finix_supported_payment_methods = SupportedPaymentMethods::new(); + + finix_supported_payment_methods.add( + common_enums::PaymentMethod::Card, + PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: default_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(), + }, + ), + ), + }, + ); + finix_supported_payment_methods.add( + common_enums::PaymentMethod::Card, + PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: default_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(), + }, + ), + ), + }, + ); + finix_supported_payment_methods +}); static FINIX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Finix", @@ -618,4 +988,11 @@ impl ConnectorSpecifications for Finix { fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&FINIX_SUPPORTED_WEBHOOK_FLOWS) } + + fn should_call_connector_customer( + &self, + _payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + ) -> bool { + true + } } diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs index b09f6ee47b9..f9e76be04a3 100644 --- a/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs @@ -1,120 +1,337 @@ -use common_enums::enums; +pub mod request; +pub mod response; +use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2, CountryAlpha3}; use common_utils::types::MinorUnit; 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}, + router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData}, + router_flow_types::{ + self as flows, + refunds::{Execute, RSync}, + Authorize, Capture, + }, + router_request_types::{ + ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCaptureData, RefundsData, ResponseId, + }, + router_response_types::{ + ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData, + }, + types::RefundsRouterData, }; -use hyperswitch_interfaces::errors; +use hyperswitch_interfaces::{consts, errors::ConnectorError}; use masking::Secret; -use serde::{Deserialize, Serialize}; +pub use request::*; +pub use response::*; -use crate::types::{RefundsResponseRouterData, ResponseRouterData}; +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + unimplemented_payment_method, + utils::{ + get_unimplemented_payment_method_error_message, AddressDetailsData, CardData, + RouterData as _, + }, +}; -//TODO: Fill the struct with respective fields -pub struct FinixRouterData<T> { - pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. - pub router_data: T, +pub struct FinixRouterData<'a, Flow, Req, Res> { + pub amount: MinorUnit, + pub router_data: &'a RouterData<Flow, Req, Res>, + pub merchant_id: Secret<String>, } -impl<T> From<(MinorUnit, T)> for FinixRouterData<T> { - fn from((amount, item): (MinorUnit, T)) -> Self { - //Todo : use utils to convert the amount to the type of amount that a connector accepts - Self { +impl<'a, Flow, Req, Res> TryFrom<(MinorUnit, &'a RouterData<Flow, Req, Res>)> + for FinixRouterData<'a, Flow, Req, Res> +{ + type Error = error_stack::Report<ConnectorError>; + + fn try_from(value: (MinorUnit, &'a RouterData<Flow, Req, Res>)) -> Result<Self, Self::Error> { + let (amount, router_data) = value; + let auth = FinixAuthType::try_from(&router_data.connector_auth_type)?; + + Ok(Self { amount, - router_data: item, - } + router_data, + merchant_id: auth.merchant_id, + }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] -pub struct FinixPaymentsRequest { - amount: MinorUnit, - card: FinixCard, +impl + TryFrom< + &FinixRouterData< + '_, + flows::CreateConnectorCustomer, + ConnectorCustomerData, + PaymentsResponseData, + >, + > for FinixCreateIdentityRequest +{ + type Error = error_stack::Report<ConnectorError>; + fn try_from( + item: &FinixRouterData< + '_, + flows::CreateConnectorCustomer, + ConnectorCustomerData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let customer_data: &ConnectorCustomerData = &item.router_data.request; + let personal_address = item.router_data.get_optional_billing().and_then(|address| { + let billing = address.address.as_ref(); + billing.map(|billing_address| FinixAddress { + line1: billing_address.get_optional_line1(), + line2: billing_address.get_optional_line2(), + city: billing_address.get_optional_city(), + region: billing_address.get_optional_state(), + postal_code: billing_address.get_optional_zip(), + country: billing_address + .get_optional_country() + .map(CountryAlpha2::from_alpha2_to_alpha3), + }) + }); + let entity = FinixIdentityEntity { + phone: customer_data.phone.clone(), + first_name: item.router_data.get_optional_billing_first_name(), + last_name: item.router_data.get_optional_billing_last_name(), + email: item.router_data.get_optional_billing_email(), + personal_address, + }; + + Ok(Self { + entity, + tags: None, + identity_type: FinixIdentityType::PERSONAL, + }) + } } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct FinixCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, +impl<F, T> TryFrom<ResponseRouterData<F, FinixIdentityResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<ConnectorError>; + fn try_from( + item: ResponseRouterData<F, FinixIdentityResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id(item.response.id), + )), + ..item.data + }) + } } -impl TryFrom<&FinixRouterData<&PaymentsAuthorizeRouterData>> for FinixPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &FinixRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { +impl TryFrom<&FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsResponseData>> + for FinixPaymentsRequest +{ + type Error = error_stack::Report<ConnectorError>; + fn try_from( + item: &FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + if matches!( + item.router_data.auth_type, + enums::AuthenticationType::ThreeDs + ) { + return Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("finix"), + ) + .into()); + } match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( - "Card payment method not implemented".to_string(), + PaymentMethodData::Card(_) => { + let source = item.router_data.get_payment_method_token()?; + Ok(Self { + amount: item.amount, + currency: item.router_data.request.currency, + source: match source { + PaymentMethodToken::Token(token) => token, + PaymentMethodToken::ApplePayDecrypt(_) => Err( + unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"), + )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Stax"))? + } + PaymentMethodToken::GooglePayDecrypt(_) => { + Err(unimplemented_payment_method!("Google Pay", "Stax"))? + } + }, + merchant: item.merchant_id.clone(), + tags: None, + three_d_secure: None, + }) + } + _ => Err( + ConnectorError::NotImplemented("Payment method not supported".to_string()).into(), + ), + } + } +} + +impl TryFrom<&FinixRouterData<'_, Capture, PaymentsCaptureData, PaymentsResponseData>> + for FinixCaptureRequest +{ + type Error = error_stack::Report<ConnectorError>; + fn try_from( + item: &FinixRouterData<'_, Capture, PaymentsCaptureData, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + capture_amount: item.router_data.request.minor_amount_to_capture, + }) + } +} + +impl + TryFrom< + &FinixRouterData< + '_, + flows::PaymentMethodToken, + PaymentMethodTokenizationData, + PaymentsResponseData, + >, + > for FinixCreatePaymentInstrumentRequest +{ + type Error = error_stack::Report<ConnectorError>; + fn try_from( + item: &FinixRouterData< + '_, + flows::PaymentMethodToken, + PaymentMethodTokenizationData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let tokenization_data = &item.router_data.request; + + match &tokenization_data.payment_method_data { + PaymentMethodData::Card(card_data) => { + Ok(Self { + instrument_type: FinixPaymentInstrumentType::PaymentCard, + name: card_data.card_holder_name.clone(), + number: Some(Secret::new(card_data.card_number.clone().get_card_no())), + security_code: Some(card_data.card_cvc.clone()), + expiration_month: Some(card_data.get_expiry_month_as_i8()?), + expiration_year: Some(card_data.get_expiry_year_as_4_digit_i32()?), + identity: item.router_data.get_connector_customer_id()?, // This would come from a previously created identity + tags: None, + address: None, + card_brand: None, // Finix determines this from the card number + card_type: None, // Finix determines this from the card number + additional_data: None, + }) + } + _ => Err(ConnectorError::NotImplemented( + "Payment method not supported for tokenization".to_string(), ) .into()), - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } -//TODO: Fill the struct with respective fields -// Auth Struct -pub struct FinixAuthType { - pub(super) api_key: Secret<String>, +// Implement response handling for tokenization +impl<F, T> TryFrom<ResponseRouterData<F, FinixInstrumentResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<ConnectorError>; + fn try_from( + item: ResponseRouterData<F, FinixInstrumentResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: AttemptStatus::Charged, + response: Ok(PaymentsResponseData::TokenizationResponse { + token: item.response.id, + }), + ..item.data + }) + } } +// Auth Struct + impl TryFrom<&ConnectorAuthType> for FinixAuthType { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<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(), + ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self { + finix_user_name: api_key.clone(), + finix_password: api_secret.clone(), + merchant_id: key1.clone(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum FinixPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, -} -impl From<FinixPaymentStatus> for common_enums::AttemptStatus { - fn from(item: FinixPaymentStatus) -> Self { - match item { - FinixPaymentStatus::Succeeded => Self::Charged, - FinixPaymentStatus::Failed => Self::Failure, - FinixPaymentStatus::Processing => Self::Authorizing, +fn get_attempt_status(state: FinixState, flow: FinixFlow, is_void: Option<bool>) -> AttemptStatus { + if is_void == Some(true) { + return match state { + FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => { + AttemptStatus::VoidFailed + } + FinixState::PENDING => AttemptStatus::Voided, + FinixState::SUCCEEDED => AttemptStatus::Voided, + }; + } + match (flow, state) { + (FinixFlow::Auth, FinixState::PENDING) => AttemptStatus::AuthenticationPending, + (FinixFlow::Auth, FinixState::SUCCEEDED) => AttemptStatus::Authorized, + (FinixFlow::Auth, FinixState::FAILED) => AttemptStatus::AuthorizationFailed, + (FinixFlow::Auth, FinixState::CANCELED) | (FinixFlow::Auth, FinixState::UNKNOWN) => { + AttemptStatus::AuthorizationFailed } + (FinixFlow::Transfer, FinixState::PENDING) => AttemptStatus::Pending, + (FinixFlow::Transfer, FinixState::SUCCEEDED) => AttemptStatus::Charged, + (FinixFlow::Transfer, FinixState::FAILED) + | (FinixFlow::Transfer, FinixState::CANCELED) + | (FinixFlow::Transfer, FinixState::UNKNOWN) => AttemptStatus::Failure, + (FinixFlow::Capture, FinixState::PENDING) => AttemptStatus::Pending, + (FinixFlow::Capture, FinixState::SUCCEEDED) => AttemptStatus::Pending, // Psync with Transfer id can determine actuall success + (FinixFlow::Capture, FinixState::FAILED) + | (FinixFlow::Capture, FinixState::CANCELED) + | (FinixFlow::Capture, FinixState::UNKNOWN) => AttemptStatus::Failure, } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct FinixPaymentsResponse { - status: FinixPaymentStatus, - id: String, -} - -impl<F, T> TryFrom<ResponseRouterData<F, FinixPaymentsResponse, T, PaymentsResponseData>> - for RouterData<F, T, PaymentsResponseData> -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: ResponseRouterData<F, FinixPaymentsResponse, 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), +pub(crate) fn get_finix_response<F, T>( + router_data: ResponseRouterData<F, FinixPaymentsResponse, T, PaymentsResponseData>, + finix_flow: FinixFlow, +) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<ConnectorError>> { + let status = get_attempt_status( + router_data.response.state.clone(), + finix_flow, + router_data.response.is_void, + ); + Ok(RouterData { + status, + response: if router_data.response.state.is_failure() { + Err(ErrorResponse { + code: router_data + .response + .failure_code + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: router_data + .response + .messages + .map_or(consts::NO_ERROR_MESSAGE.to_string(), |msg| msg.join(",")), + reason: router_data.response.failure_message, + status_code: router_data.http_code, + attempt_status: Some(status), + connector_transaction_id: Some(router_data.response.id.clone()), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + router_data + .response + .transfer + .unwrap_or(router_data.response.id), + ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, @@ -122,96 +339,82 @@ impl<F, T> TryFrom<ResponseRouterData<F, FinixPaymentsResponse, T, PaymentsRespo connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, - }), - ..item.data - }) - } + }) + }, + ..router_data.data + }) } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct FinixRefundRequest { - pub amount: MinorUnit, -} - -impl<F> TryFrom<&FinixRouterData<&RefundsRouterData<F>>> for FinixRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &FinixRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { - Ok(Self { - amount: item.amount.to_owned(), - }) +impl<F> TryFrom<&FinixRouterData<'_, F, RefundsData, RefundsResponseData>> + for FinixCreateRefundRequest +{ + type Error = error_stack::Report<ConnectorError>; + fn try_from( + item: &FinixRouterData<'_, F, RefundsData, RefundsResponseData>, + ) -> Result<Self, Self::Error> { + let refund_amount = item.router_data.request.minor_refund_amount; + Ok(Self::new(refund_amount)) } } -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, -} - -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { +impl From<FinixState> for enums::RefundStatus { + fn from(item: FinixState) -> Self { match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping + FinixState::PENDING => Self::Pending, + FinixState::SUCCEEDED => Self::Success, + FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => Self::Failure, } } } -//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>; +impl TryFrom<RefundsResponseRouterData<Execute, FinixPaymentsResponse>> + for RefundsRouterData<Execute> +{ + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, FinixPaymentsResponse>, ) -> 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), + refund_status: enums::RefundStatus::from(item.response.state), }), ..item.data }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<RSync, FinixPaymentsResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, FinixPaymentsResponse>, ) -> 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), + refund_status: enums::RefundStatus::from(item.response.state), }), ..item.data }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] -pub struct FinixErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, - pub network_advice_code: Option<String>, - pub network_decline_code: Option<String>, - pub network_error_message: Option<String>, +impl FinixErrorResponse { + pub fn get_message(&self) -> String { + self.embedded + .as_ref() + .and_then(|embedded| embedded.errors.as_ref()) + .and_then(|errors| errors.first()) + .and_then(|error| error.message.clone()) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()) + } + + pub fn get_code(&self) -> String { + self.embedded + .as_ref() + .and_then(|embedded| embedded.errors.as_ref()) + .and_then(|errors| errors.first()) + .and_then(|error| error.code.clone()) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()) + } } diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs new file mode 100644 index 00000000000..703c12aa84e --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs @@ -0,0 +1,213 @@ +use std::collections::HashMap; + +use common_enums::Currency; +use common_utils::{pii::Email, types::MinorUnit}; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use super::*; +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixPaymentsRequest { + pub amount: MinorUnit, + pub currency: Currency, + pub source: Secret<String>, + pub merchant: Secret<String>, + pub tags: Option<FinixTags>, + pub three_d_secure: Option<FinixThreeDSecure>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixCaptureRequest { + pub capture_amount: MinorUnit, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixCancelRequest { + pub void_me: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixCaptureAuthorizationRequest { + pub amount: Option<MinorUnit>, + pub tags: Option<FinixTags>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixCreateIdentityRequest { + pub entity: FinixIdentityEntity, + pub tags: Option<FinixTags>, + #[serde(rename = "type")] + pub identity_type: FinixIdentityType, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixIdentityEntity { + pub phone: Option<Secret<String>>, + pub first_name: Option<Secret<String>>, + pub last_name: Option<Secret<String>>, + pub email: Option<Email>, + pub personal_address: Option<FinixAddress>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixCreatePaymentInstrumentRequest { + #[serde(rename = "type")] + pub instrument_type: FinixPaymentInstrumentType, + pub name: Option<Secret<String>>, + pub number: Option<Secret<String>>, + pub security_code: Option<Secret<String>>, + pub expiration_month: Option<Secret<i8>>, + pub expiration_year: Option<Secret<i32>>, + pub identity: String, + pub tags: Option<FinixTags>, + pub address: Option<FinixAddress>, + pub card_brand: Option<String>, + pub card_type: Option<FinixCardType>, + pub additional_data: Option<HashMap<String, String>>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixCreateRefundRequest { + pub refund_amount: MinorUnit, +} + +impl FinixCreateRefundRequest { + pub fn new(refund_amount: MinorUnit) -> Self { + Self { refund_amount } + } +} + +// ---------- COMMON ENUMS + +#[derive(Debug, Clone)] +pub enum FinixId { + Auth(String), + Transfer(String), +} + +impl From<String> for FinixId { + fn from(id: String) -> Self { + if id.starts_with("AU") { + Self::Auth(id) + } else if id.starts_with("TR") { + Self::Transfer(id) + } else { + // Default to Auth if the prefix doesn't match + Self::Auth(id) + } + } +} + +impl std::fmt::Display for FinixId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Auth(id) => write!(f, "{}", id), + Self::Transfer(id) => write!(f, "{}", id), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum FinixState { + PENDING, + SUCCEEDED, + FAILED, + CANCELED, + #[serde(other)] + UNKNOWN, + // RETURNED +} +impl FinixState { + pub fn is_failure(&self) -> bool { + match self { + Self::PENDING | Self::SUCCEEDED => false, + Self::FAILED | Self::CANCELED | Self::UNKNOWN => true, + } + } +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum FinixPaymentType { + DEBIT, + CREDIT, + REVERSAL, + FEE, + ADJUSTMENT, + DISPUTE, + RESERVE, + SETTLEMENT, + #[serde(other)] + UNKNOWN, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum FinixPaymentInstrumentType { + #[serde(rename = "PAYMENT_CARD")] + PaymentCard, + + #[serde(rename = "BANK_ACCOUNT")] + BankAccount, + #[serde(other)] + Unknown, +} + +/// Represents the type of a payment card. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum FinixCardType { + DEBIT, + CREDIT, + PREPAID, + #[serde(other)] + UNKNOWN, +} + +/// 3D Secure authentication details. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixThreeDSecure { + pub authenticated: Option<bool>, + pub liability_shift: Option<Secret<String>>, + pub version: Option<String>, + pub eci: Option<Secret<String>>, + pub cavv: Option<Secret<String>>, + pub xid: Option<Secret<String>>, +} + +/// Key-value pair tags. +pub type FinixTags = HashMap<String, String>; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FinixAddress { + pub line1: Option<Secret<String>>, + pub line2: Option<Secret<String>>, + pub city: Option<String>, + pub region: Option<Secret<String>>, + pub postal_code: Option<Secret<String>>, + pub country: Option<CountryAlpha3>, +} + +/// The type of the business. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum FinixIdentityType { + PERSONAL, +} + +pub enum FinixFlow { + Auth, + Transfer, + Capture, +} + +impl FinixFlow { + pub fn get_flow_for_auth(capture_method: CaptureMethod) -> Self { + match capture_method { + CaptureMethod::SequentialAutomatic | CaptureMethod::Automatic => Self::Transfer, + CaptureMethod::Manual | CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => { + Self::Auth + } + } + } +} +pub struct FinixAuthType { + pub finix_user_name: Secret<String>, + pub finix_password: Secret<String>, + pub merchant_id: Secret<String>, +} diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers/response.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers/response.rs new file mode 100644 index 00000000000..9f29d9a75f5 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers/response.rs @@ -0,0 +1,79 @@ +use std::collections::HashMap; + +use common_enums::Currency; +use common_utils::types::MinorUnit; +use serde::{Deserialize, Serialize}; + +use super::*; +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct FinixPaymentsResponse { + pub id: String, + pub created_at: Option<String>, + pub updated_at: Option<String>, + pub application: Option<Secret<String>>, + pub amount: MinorUnit, + pub captured_amount: Option<MinorUnit>, + pub currency: Currency, + pub is_void: Option<bool>, + pub source: Option<Secret<String>>, + pub state: FinixState, + pub failure_code: Option<String>, + pub messages: Option<Vec<String>>, + pub failure_message: Option<String>, + pub transfer: Option<String>, + pub tags: FinixTags, + #[serde(rename = "type")] + pub payment_type: Option<FinixPaymentType>, + // pub trace_id: String, + pub three_d_secure: Option<FinixThreeDSecure>, + // Add other fields from the API response as needed. +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct FinixIdentityResponse { + pub id: String, + pub created_at: Option<String>, + pub updated_at: Option<String>, + pub application: Option<String>, + pub entity: Option<HashMap<String, serde_json::Value>>, + pub tags: Option<FinixTags>, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct FinixInstrumentResponse { + pub id: String, + pub created_at: String, + pub updated_at: String, + pub application: String, + pub identity: Option<String>, + #[serde(rename = "type")] + pub instrument_type: FinixPaymentInstrumentType, + pub tags: Option<FinixTags>, + pub card_type: Option<FinixCardType>, + pub card_brand: Option<String>, + pub fingerprint: Option<String>, + pub address: Option<FinixAddress>, + pub name: Option<Secret<String>>, + pub currency: Option<Currency>, + pub enabled: bool, +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct FinixErrorResponse { + // pub status_code: u16, + pub total: Option<i64>, + #[serde(rename = "_embedded")] + pub embedded: Option<FinixErrorEmbedded>, +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct FinixErrorEmbedded { + pub errors: Option<Vec<FinixError>>, +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct FinixError { + // pub logref: Option<String>, + pub message: Option<String>, + pub code: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index e7e39adaf81..6e90dc71988 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -1474,7 +1474,6 @@ macro_rules! default_imp_for_create_customer { } default_imp_for_create_customer!( - connectors::Finix, connectors::Vgs, connectors::Aci, connectors::Adyen, diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index bcd766b1168..60da39983f5 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -586,6 +586,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { paytm::transformers::PaytmAuthType::try_from(self.auth_type)?; Ok(()) } + api_enums::Connector::Finix => { + finix::transformers::FinixAuthType::try_from(self.auth_type)?; + Ok(()) + } } } } diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index 5587462df82..75716196edb 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -254,6 +254,9 @@ impl ConnectorData { enums::Connector::Facilitapay => { Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new()))) } + enums::Connector::Finix => { + Ok(ConnectorEnum::Old(Box::new(connector::Finix::new()))) + } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index 20bb99a6bc6..aad8362e7e0 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -172,6 +172,9 @@ impl FeatureMatrixConnectorData { enums::Connector::Facilitapay => { Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new()))) } + enums::Connector::Finix => { + Ok(ConnectorEnum::Old(Box::new(connector::Finix::new()))) + } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index 1455b3a8718..305262d4e70 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -61,6 +61,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Elavon => Self::Elavon, api_enums::Connector::Facilitapay => Self::Facilitapay, + api_enums::Connector::Finix => Self::Finix, api_enums::Connector::Fiserv => Self::Fiserv, api_enums::Connector::Fiservemea => Self::Fiservemea, api_enums::Connector::Fiuu => Self::Fiuu,
2025-10-06T07:49:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Implementation of Payment,Refund,void , customer create , tokenization for non3ds cards for finix ## Test cases <details> <summary> Payment : Automatic </summary> ## Request ```json { "amount": 689, "customer_id":"hello_world", "currency": "USD", "confirm": true, "capture_method": "automatic", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", // "connector":["paypal_test","stripe_test"], "billing": { "address": { "zip": "560095", "country": "IN", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "payment_method_data": { "card": { "card_number": "5200828282828210", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } } } ``` ## Response ```json { "payment_id": "pay_pVWtQXnwq32dc3OdqqQo", "merchant_id": "merchant_1759477997", "status": "succeeded", "amount": 689, "net_amount": 689, "shipping_cost": null, "amount_capturable": 0, "amount_received": 689, "connector": "finix", "client_secret": "pay_pVWtQXnwq32dc3OdqqQo_secret_oYqnSGx6ktsh1jv0HF3Y", "created": "2025-10-06T10:17:24.054Z", "currency": "USD", "customer_id": "hello_world", "customer": { "id": "hello_world", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "8210", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520082", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "IN", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "hello_world", "created_at": 1759745843, "expires": 1759749443, "secret": "epk_6f24c6ad6c29447e8e6cb37f9431a152" }, "manual_retry_allowed": null, "connector_transaction_id": "TRmJxabrSYTSjGxnqthW8nkK", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_GjR7afeLzCXVYhe62xl8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bSuyBQOAy40vpxbsiOCR", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T10:32:24.054Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T10:17:26.710Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` </details> <details> <summary> Payment : Manual </summary> ```json { "amount": 689, "customer_id":"hello_world", "currency": "USD", "confirm": true, "capture_method": "manual", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", // "connector":["paypal_test","stripe_test"], "billing": { "address": { "zip": "560095", "country": "IN", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "payment_method_data": { "card": { "card_number": "5200828282828210", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } } } ``` ```json { "payment_id": "pay_A8v0P3KgtB5w7mZaWO3t", "merchant_id": "merchant_1759477997", "status": "requires_capture", "amount": 689, "net_amount": 689, "shipping_cost": null, "amount_capturable": 689, "amount_received": null, "connector": "finix", "client_secret": "pay_A8v0P3KgtB5w7mZaWO3t_secret_jjLo36Con9BduAYRKTUP", "created": "2025-10-06T10:18:12.998Z", "currency": "USD", "customer_id": "hello_world", "customer": { "id": "hello_world", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "8210", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520082", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "IN", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "hello_world", "created_at": 1759745892, "expires": 1759749492, "secret": "epk_5946337c7bf3422db4549d97b25c6c30" }, "manual_retry_allowed": null, "connector_transaction_id": "AUaokdvtqphbiksg4FAxfZf9", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_GjR7afeLzCXVYhe62xl8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bSuyBQOAy40vpxbsiOCR", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T10:33:12.998Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T10:18:14.166Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` ## Capture ```sh curl --location 'localhost:8080/payments/pay_A8v0P3KgtB5w7mZaWO3t/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_3cGokW5MFJmBnLTLmcS2EKAODQblXknbM6XCjDHLipq0CmLrUu3LNsIyFCDwgOwH' \ --data '{ "amount": 689 }' ``` ```json { "payment_id": "pay_A8v0P3KgtB5w7mZaWO3t", "merchant_id": "merchant_1759477997", "status": "succeeded", "amount": 689, "net_amount": 689, "shipping_cost": null, "amount_capturable": 0, "amount_received": 689, "connector": "finix", "client_secret": "pay_A8v0P3KgtB5w7mZaWO3t_secret_jjLo36Con9BduAYRKTUP", "created": "2025-10-06T10:18:12.998Z", "currency": "USD", "customer_id": "hello_world", "customer": { "id": "hello_world", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "8210", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520082", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "IN", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "AUaokdvtqphbiksg4FAxfZf9", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_GjR7afeLzCXVYhe62xl8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bSuyBQOAy40vpxbsiOCR", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T10:33:12.998Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T10:18:48.481Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` </details> <details> <summary> Void </summary> Make Auth call ```json curl --location 'localhost:8080/payments/pay_InDxLEmz9xZ9AF6xfgYc/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_3cGokW5MFJmBnLTLmcS2EKAODQblXknbM6XCjDHLipq0CmLrUu3LNsIyFCDwgOwH' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` ```json { "payment_id": "pay_InDxLEmz9xZ9AF6xfgYc", "merchant_id": "merchant_1759477997", "status": "cancelled", "amount": 689, "net_amount": 689, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "finix", "client_secret": "pay_InDxLEmz9xZ9AF6xfgYc_secret_CSRpGCjsWQu3t6q1SZbM", "created": "2025-10-06T10:20:46.718Z", "currency": "USD", "customer_id": "hello_world", "customer": { "id": "hello_world", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "8210", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520082", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "IN", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": "requested_by_customer", "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "AU5zeQMv2WYgNKyo8fNh2or5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_GjR7afeLzCXVYhe62xl8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bSuyBQOAy40vpxbsiOCR", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T10:35:46.718Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T10:20:52.789Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` </details> <details> <summary>Refund</summary> make a payment capture ```json { "payment_id": "pay_K7EmavhAOgxV3pOMGHGL", "merchant_id": "merchant_1759477997", "status": "succeeded", "amount": 400, "net_amount": 400, "shipping_cost": null, "amount_capturable": 0, "amount_received": 400, "connector": "finix", "client_secret": "pay_K7EmavhAOgxV3pOMGHGL_secret_vOfMeE36wQUhik3cS5Nu", "created": "2025-10-06T10:22:02.926Z", "currency": "USD", "customer_id": "hello_world", "customer": { "id": "hello_world", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "8210", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520082", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "IN", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "hello_world", "created_at": 1759746122, "expires": 1759749722, "secret": "epk_47435b2e06634545a0d2d0c534e0a881" }, "manual_retry_allowed": null, "connector_transaction_id": "TRaB2ZZji4QoFwuKCC4mwfi9", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_GjR7afeLzCXVYhe62xl8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bSuyBQOAy40vpxbsiOCR", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-10-06T10:37:02.926Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-10-06T10:22:05.203Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` ## Refund ```sh curl --location 'localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_3cGokW5MFJmBnLTLmcS2EKAODQblXknbM6XCjDHLipq0CmLrUu3LNsIyFCDwgOwH' \ --data '{ "payment_id": "pay_K7EmavhAOgxV3pOMGHGL", "amount":389 }' ``` ```json { "refund_id": "ref_OL9OI4S00JxqZZk0l9j1", "payment_id": "pay_K7EmavhAOgxV3pOMGHGL", "amount": 389, "currency": "USD", "status": "pending", "reason": null, "metadata": null, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-10-06T10:22:49.992Z", "updated_at": "2025-10-06T10:22:50.684Z", "connector": "finix", "profile_id": "pro_GjR7afeLzCXVYhe62xl8", "merchant_connector_id": "mca_bSuyBQOAy40vpxbsiOCR", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` Make Rsync ```sh curl --location 'localhost:8080/refunds/ref_OL9OI4S00JxqZZk0l9j1?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_3cGokW5MFJmBnLTLmcS2EKAODQblXknbM6XCjDHLipq0CmLrUu3LNsIyFCDwgOwH' ``` ```json { "refund_id": "ref_OL9OI4S00JxqZZk0l9j1", "payment_id": "pay_K7EmavhAOgxV3pOMGHGL", "amount": 389, "currency": "USD", "status": "succeeded", "reason": null, "metadata": null, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-10-06T10:22:49.992Z", "updated_at": "2025-10-06T10:23:20.589Z", "connector": "finix", "profile_id": "pro_GjR7afeLzCXVYhe62xl8", "merchant_connector_id": "mca_bSuyBQOAy40vpxbsiOCR", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <img width="995" height="1008" alt="Screenshot 2025-10-06 at 2 51 30 PM" src="https://github.com/user-attachments/assets/fe013d3c-a608-4b89-9072-dd83b8f1c0dd" /> <img width="1010" height="995" alt="Screenshot 2025-10-06 at 2 51 42 PM" src="https://github.com/user-attachments/assets/5c4a923a-d9d3-4fce-b7a9-0cf9d152caa6" /> <img width="867" height="951" alt="Screenshot 2025-10-06 at 2 52 03 PM" src="https://github.com/user-attachments/assets/f85c3460-0f51-436b-90ff-2f9dfddfe1e2" /> <img width="1279" height="972" alt="Screenshot 2025-10-06 at 3 04 12 PM" src="https://github.com/user-attachments/assets/279759b8-5ed3-4cc2-9298-38cfffd704e4" /> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="848" height="734" alt="Screenshot 2025-10-09 at 3 58 18 PM" src="https://github.com/user-attachments/assets/063679ca-8e53-44de-8862-10e29eddbfbf" /> - Mandates ,CIT and NIT, 3ds not implemented - Refunds will be pending first and then success after a min do rsync as attached in example. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
6173586eeb567733195c3ad6bf2876be384d7d3c
juspay/hyperswitch
juspay__hyperswitch-9627
Bug: [REFACTOR] add webhook_url for v2 tunnel add support for create_webhook_url for v2 tunnel flow.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 840cdf7a1de..9a7eb4ca8cd 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5933,6 +5933,10 @@ pub struct PaymentsConfirmIntentRequest { /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, + + /// The webhook endpoint URL to receive payment status notifications + #[schema(value_type = Option<String>, example = "https://merchant.example.com/webhooks/payment")] + pub webhook_url: Option<common_utils::types::Url>, } // Serialize is implemented because, this will be serialized in the api events. @@ -6173,6 +6177,10 @@ pub struct PaymentsRequest { /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, + + /// The webhook endpoint URL to receive payment status notifications + #[schema(value_type = Option<String>, example = "https://merchant.example.com/webhooks/payment")] + pub webhook_url: Option<common_utils::types::Url>, } #[cfg(feature = "v2")] @@ -6228,6 +6236,7 @@ impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { merchant_connector_details: request.merchant_connector_details.clone(), return_raw_connector_response: request.return_raw_connector_response, split_payment_method_data: None, + webhook_url: request.webhook_url.clone(), } } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index b1f7a4745e1..a01efdf0749 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -944,6 +944,8 @@ where pub payment_method: Option<payment_methods::PaymentMethod>, pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, pub external_vault_pmd: Option<payment_method_data::ExternalVaultPaymentMethodData>, + /// The webhook url of the merchant, to which the connector will send the webhook. + pub webhook_url: Option<String>, } #[cfg(feature = "v2")] diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index a7d23edde09..2e1b2d7f999 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -3438,6 +3438,7 @@ fn construct_zero_auth_payments_request( merchant_connector_details: None, return_raw_connector_response: None, enable_partial_authorization: None, + webhook_url: None, }) } diff --git a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs index 7d40bb81c28..4e4302b1d5a 100644 --- a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs +++ b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs @@ -298,6 +298,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ExternalVaultP payment_method: None, merchant_connector_details: None, external_vault_pmd: payment_method_data, + webhook_url: None, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; 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 9720cee1d9a..c66ad2299a5 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -276,6 +276,10 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir payment_method: None, merchant_connector_details, external_vault_pmd: None, + webhook_url: request + .webhook_url + .as_ref() + .map(|url| url.get_string_repr().to_string()), }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs index c53aff42b51..ceae5d850f8 100644 --- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs +++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs @@ -269,6 +269,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsR payment_method: None, merchant_connector_details: None, external_vault_pmd: None, + webhook_url: None, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 8467a17e12e..540b6d3df28 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -333,8 +333,9 @@ pub async fn construct_payment_router_data_for_authorize<'a>( &attempt.merchant_id, merchant_connector_account.get_id().get_string_repr(), )), - // TODO: Implement for connectors that require a webhook URL to be included in the request payload. - domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { + payment_data.webhook_url + } }; let router_return_url = payment_data @@ -585,8 +586,9 @@ pub async fn construct_external_vault_proxy_payment_router_data<'a>( &attempt.merchant_id, merchant_connector_account.get_id().get_string_repr(), )), - // TODO: Implement for connectors that require a webhook URL to be included in the request payload. - domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { + payment_data.webhook_url.clone() + } }; let router_return_url = payment_data @@ -1417,9 +1419,8 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( &attempt.merchant_id, merchant_connector_account.get_id().get_string_repr(), )), - // TODO: Implement for connectors that require a webhook URL to be included in the request payload. domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { - todo!("Add webhook URL to request for this connector") + payment_data.webhook_url } };
2025-09-30T10:48:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds support for webhook_url in v2 PaymentsRequest. It allows merchants to pass their own webhook URL instead of creating one in Hyperswitch. This change is applicable only to v2 tunnel flow. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested Phonepe through UCS Payment Create ``` curl --location 'http://localhost:8080/v2/payments' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_zjXchnTKtjXfUfQ9FJEL' \ --header 'X-Merchant-Id: cloth_seller_Zoo9KadtslxR8ICC7dB6' \ --header 'x-tenant-id: public' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "INR" }, "merchant_connector_details": { "connector_name": "phonepe", "merchant_connector_creds": { "auth_type": "SignatureKey", "api_key": "_", "key1": "_", "api_secret": "_" } }, "return_url": "https://api-ns2.juspay.in/v2/pay/response/irctc", "merchant_reference_id": "phonepeirctc1759229122", "capture_method":"automatic", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "success@razorpay" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" } }, "browser_info": { "user_agent": "Dalvik/2.1.0", "referer": "abcd.com", "ip_address": "157.51.3.204" }, "payment_method_subtype": "upi_collect", "payment_method_type": "upi", "return_raw_connector_response": true, "webhook_url": "https://v2/pay/response/irctc" }' ``` Response ``` { "id": "12345_pay_01999962cf7d7e03b33e9ec92da6330c", "status": "requires_customer_action", "amount": { "order_amount": 100, "currency": "INR", "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": "phonepe", "created": "2025-09-30T06:50:13.764Z", "modified_at": "2025-09-30T06:50:15.068Z", "payment_method_data": { "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" } }, "payment_method_type": "upi", "payment_method_subtype": "upi_collect", "connector_transaction_id": "OMO2509301220148555398840", "connector_reference_id": "phonepeirctc1759215013", "merchant_connector_id": null, "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://api-ns2.juspay.in/v2/pay/response/irctc", "authentication_type": null, "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null, "merchant_reference_id": "phonepeirctc1759215013", "raw_connector_response": "{\"success\":true,\"code\":\"PAYMENT_INITIATED\",\"message\":\"Payment initiated\",\"data\":{\"merchantId\":\"JUSPAONLINE\",\"merchantTransactionId\":\"phonepeirctc1759215013\",\"transactionId\":\"OMO2509301220148555398840\",\"instrumentResponse\":{\"type\":\"UPI_COLLECT\"}}}", "feature_metadata": null, "metadata": null } ``` Verify webhook url in UCS logs <img width="1648" height="247" alt="image" src="https://github.com/user-attachments/assets/d6beabd5-e13a-41bd-9188-53994f38ccb3" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9312cfa3c85e350c12bd64306037a72753b532bd
juspay/hyperswitch
juspay__hyperswitch-9623
Bug: [ENHANCEMENT] payout updates Creating this ticket for 1. Adding currency as a rule for payout routing 2. Updating Sepa to SepaBankTransfer for dynamic required fields
diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs index 7df086fdbcb..62dbefab3f3 100644 --- a/crates/euclid/src/frontend/dir.rs +++ b/crates/euclid/src/frontend/dir.rs @@ -836,6 +836,14 @@ pub enum PayoutDirKeyKind { #[serde(rename = "amount")] PayoutAmount, + #[strum( + serialize = "currency", + detailed_message = "Currency used for the payout", + props(Category = "Order details") + )] + #[serde(rename = "currency")] + PayoutCurrency, + #[strum( serialize = "payment_method", detailed_message = "Different modes of payout - eg. cards, wallets, banks", @@ -874,6 +882,8 @@ pub enum PayoutDirValue { BusinessLabel(types::StrValue), #[serde(rename = "amount")] PayoutAmount(types::NumValue), + #[serde(rename = "currency")] + PayoutCurrency(enums::PaymentCurrency), #[serde(rename = "payment_method")] PayoutType(common_enums::PayoutType), #[serde(rename = "wallet")] diff --git a/crates/euclid/src/types.rs b/crates/euclid/src/types.rs index 99b94f2a67b..44d0816be29 100644 --- a/crates/euclid/src/types.rs +++ b/crates/euclid/src/types.rs @@ -55,6 +55,9 @@ pub enum EuclidKey { PaymentAmount, #[strum(serialize = "currency")] PaymentCurrency, + #[cfg(feature = "payouts")] + #[strum(serialize = "payout_currency")] + PayoutCurrency, #[strum(serialize = "country", to_string = "business_country")] BusinessCountry, #[strum(serialize = "billing_country")] @@ -149,6 +152,8 @@ impl EuclidKey { Self::CaptureMethod => DataType::EnumVariant, Self::PaymentAmount => DataType::Number, Self::PaymentCurrency => DataType::EnumVariant, + #[cfg(feature = "payouts")] + Self::PayoutCurrency => DataType::EnumVariant, Self::BusinessCountry => DataType::EnumVariant, Self::BillingCountry => DataType::EnumVariant, Self::MandateType => DataType::EnumVariant, @@ -274,6 +279,8 @@ pub enum EuclidValue { MandateType(enums::MandateType), PaymentAmount(NumValue), PaymentCurrency(enums::Currency), + #[cfg(feature = "payouts")] + PayoutCurrency(enums::Currency), BusinessCountry(enums::Country), BillingCountry(enums::Country), BusinessLabel(StrValue), @@ -309,6 +316,8 @@ impl EuclidValue { Self::CaptureMethod(_) => EuclidKey::CaptureMethod, Self::PaymentAmount(_) => EuclidKey::PaymentAmount, Self::PaymentCurrency(_) => EuclidKey::PaymentCurrency, + #[cfg(feature = "payouts")] + Self::PayoutCurrency(_) => EuclidKey::PayoutCurrency, Self::BusinessCountry(_) => EuclidKey::BusinessCountry, Self::BillingCountry(_) => EuclidKey::BillingCountry, Self::BusinessLabel(_) => EuclidKey::BusinessLabel, diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index c0e58520c71..2aaee43f7eb 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -445,6 +445,7 @@ pub fn get_payout_variant_values(key: &str) -> Result<JsValue, JsValue> { let variants: &[&str] = match key { dir::PayoutDirKeyKind::BusinessCountry => dir_enums::BusinessCountry::VARIANTS, dir::PayoutDirKeyKind::BillingCountry => dir_enums::BillingCountry::VARIANTS, + dir::PayoutDirKeyKind::PayoutCurrency => dir_enums::PaymentCurrency::VARIANTS, dir::PayoutDirKeyKind::PayoutType => dir_enums::PayoutType::VARIANTS, dir::PayoutDirKeyKind::WalletType => dir_enums::PayoutWalletType::VARIANTS, dir::PayoutDirKeyKind::BankTransferType => dir_enums::PayoutBankTransferType::VARIANTS, diff --git a/crates/router/src/configs/defaults/payout_required_fields.rs b/crates/router/src/configs/defaults/payout_required_fields.rs index d6b316c42b4..24c13ec5396 100644 --- a/crates/router/src/configs/defaults/payout_required_fields.rs +++ b/crates/router/src/configs/defaults/payout_required_fields.rs @@ -38,7 +38,7 @@ impl Default for PayoutRequiredFields { // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, - PaymentMethodType::Sepa, + PaymentMethodType::SepaBankTransfer, ), // Ebanx get_connector_payment_method_type_fields( @@ -117,7 +117,7 @@ fn get_billing_details_for_payment_method( ]); // Add first_name for bank payouts only - if payment_method_type == PaymentMethodType::Sepa { + if payment_method_type == PaymentMethodType::SepaBankTransfer { fields.insert( "billing.address.first_name".to_string(), RequiredFieldInfo { @@ -209,7 +209,7 @@ fn get_connector_payment_method_type_fields( }, ) } - PaymentMethodType::Sepa => { + PaymentMethodType::SepaBankTransfer => { common_fields.extend(get_sepa_fields()); ( payment_method_type,
2025-09-30T10:54:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds two changes 1. Updates `Sepa` to `SepaBankTransfer` for dynamic required fields for payouts 2. Adds PayoutCurrency as a rule to be set while configuring payout routing on dashboard ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 3. `crates/router/src/configs` 4. `loadtest/config` --> ## Motivation and Context Two things - 1. Allows for configuring currency as a rule for payout routing 2. Sends back required fields in the response for `sepa_bank_transfer` ## How did you test it? <details> <summary>Create a payout link</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_ps5hUWh9tfDFtu9IO0MAaK3tbLTAWscvZlCanmGmTELIWPYCJPWVHkUXWeEGDWig' \ --data '{"merchant_order_reference_id":"ref123","amount":213,"currency":"EUR","customer_id":"cus_uEIQdrEFaB5iVfAUSTrU","description":"Its my first payout request","entity_type":"Individual","auto_fulfill":true,"session_expiry":1000000,"profile_id":"pro_0U7D6dU6lAplreXCcFs6","payout_link":true,"return_url":"https://www.google.com","payout_link_config":{"form_layout":"tabs","theme":"#0066ff","logo":"https://hyperswitch.io/favicon.ico","merchant_name":"HyperSwitch Inc.","test_mode":true},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"London","zip":"94122","country":"NL","first_name":"John","last_name":"Nether"}}}' Response {"payout_id":"payout_Eyodo5H37xucxcfnGhJR","merchant_id":"merchant_1759230162","merchant_order_reference_id":"ref123","amount":213,"currency":"EUR","connector":null,"payout_type":null,"payout_method_data":null,"billing":{"address":{"city":"London","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":null,"first_name":"John","last_name":"Nether","origin_zip":null},"phone":null,"email":null},"auto_fulfill":true,"customer_id":"cus_uEIQdrEFaB5iVfAUSTrU","customer":{"id":"cus_uEIQdrEFaB5iVfAUSTrU","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_Eyodo5H37xucxcfnGhJR_secret_ht1Pkut3UyldsRln2A8w","return_url":"https://www.google.com","business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":false,"metadata":{},"merchant_connector_id":null,"status":"requires_payout_method_data","error_message":null,"error_code":null,"profile_id":"pro_0U7D6dU6lAplreXCcFs6","created":"2025-09-30T11:03:02.998Z","connector_transaction_id":null,"priority":null,"payout_link":{"payout_link_id":"payout_link_oI2b4wNeAez056omVVCT","link":"http://localhost:8080/payout_link/merchant_1759230162/payout_Eyodo5H37xucxcfnGhJR?locale=en"},"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":null} </details> <details> <summary>Required fields embedded in payout links</summary> Expectation - `sepa_bank_transfer` must not be null "enabled_payment_methods_with_required_fields": [ { "payment_method": "card", "payment_method_types_info": [ { "payment_method_type": "credit", "required_fields": { "payout_method_data.card.card_holder_name": { "required_field": "payout_method_data.card.card_holder_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "payout_method_data.card.card_number": { "required_field": "payout_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "billing_address_city", "field_type": "text", "value": "London" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "billing_address_line1", "field_type": "text", "value": "1467" }, "payout_method_data.card.expiry_year": { "required_field": "payout_method_data.card.expiry_year", "display_name": "exp_year", "field_type": "user_card_expiry_year", "value": null }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "billing_address_country", "field_type": { "user_address_country": { "options": [ "ES", "SK", "AT", "NL", "DE", "BE", "FR", "FI", "PT", "IE", "EE", "LT", "LV", "IT", "CZ", "DE", "HU", "NO", "PL", "SE", "GB", "CH" ] } }, "value": "NL" }, "billing.address.line2": { "required_field": "billing.address.line2", "display_name": "billing_address_line2", "field_type": "text", "value": "Harrison Street" }, "payout_method_data.card.expiry_month": { "required_field": "payout_method_data.card.expiry_month", "display_name": "exp_month", "field_type": "user_card_expiry_month", "value": null } } }, { "payment_method_type": "debit", "required_fields": { "payout_method_data.card.card_number": { "required_field": "payout_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "billing_address_line1", "field_type": "text", "value": "1467" }, "payout_method_data.card.expiry_month": { "required_field": "payout_method_data.card.expiry_month", "display_name": "exp_month", "field_type": "user_card_expiry_month", "value": null }, "payout_method_data.card.expiry_year": { "required_field": "payout_method_data.card.expiry_year", "display_name": "exp_year", "field_type": "user_card_expiry_year", "value": null }, "payout_method_data.card.card_holder_name": { "required_field": "payout_method_data.card.card_holder_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "billing_address_country", "field_type": { "user_address_country": { "options": [ "ES", "SK", "AT", "NL", "DE", "BE", "FR", "FI", "PT", "IE", "EE", "LT", "LV", "IT", "CZ", "DE", "HU", "NO", "PL", "SE", "GB", "CH" ] } }, "value": "NL" }, "billing.address.line2": { "required_field": "billing.address.line2", "display_name": "billing_address_line2", "field_type": "text", "value": "Harrison Street" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "billing_address_city", "field_type": "text", "value": "London" } } } ] }, { "payment_method": "bank_transfer", "payment_method_types_info": [ { "payment_method_type": "sepa_bank_transfer", "required_fields": { "billing.address.line2": { "required_field": "billing.address.line2", "display_name": "billing_address_line2", "field_type": "text", "value": "Harrison Street" }, "billing.address.city": { "required_field": "billing.address.city", "display_name": "billing_address_city", "field_type": "text", "value": "London" }, "billing.address.line1": { "required_field": "billing.address.line1", "display_name": "billing_address_line1", "field_type": "text", "value": "1467" }, "payout_method_data.bank.iban": { "required_field": "payout_method_data.bank.iban", "display_name": "iban", "field_type": "text", "value": null }, "billing.address.first_name": { "required_field": "billing.address.first_name", "display_name": "billing_address_first_name", "field_type": "text", "value": "John" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "billing_address_country", "field_type": { "user_address_country": { "options": [ "ES", "SK", "AT", "NL", "DE", "BE", "FR", "FI", "PT", "IE", "EE", "LT", "LV", "IT", "CZ", "DE", "HU", "NO", "PL", "SE", "GB", "CH" ] } }, "value": "NL" }, "payout_method_data.bank.bic": { "required_field": "payout_method_data.bank.bic", "display_name": "bic", "field_type": "text", "value": null } } }, { "payment_method_type": "sepa", "required_fields": null } ] } ] </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
efab34f0ef0bd032b049778f18f3cb688faa7fa7
juspay/hyperswitch
juspay__hyperswitch-9631
Bug: [FEATURE]: [Nuvei] add payout flows Add Cards Payout through Nuvei Add Webhook support for Payouts in Nuvei Propagate error from failure response in payouts Create webhook_url in PayoutsData Request to pass to Psp's
diff --git a/config/config.example.toml b/config/config.example.toml index 56da591f1fc..b3c5de5f5e0 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -742,6 +742,10 @@ apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,G google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +[payout_method_filters.nuvei] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } + [pm_filters.stax] credit = { country = "US", currency = "USD" } debit = { country = "US", currency = "USD" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 02ee0124bae..f853f7578f8 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -561,6 +561,10 @@ apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,G google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +[payout_method_filters.nuvei] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } + [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 998986b3829..c5b5fe4baef 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -478,6 +478,9 @@ apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,G google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +[payout_method_filters.nuvei] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 3f16af80c6f..61df894c384 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -541,6 +541,10 @@ apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,G google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +[payout_method_filters.nuvei] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } + [pm_filters.globepay] ali_pay = { country = "GB",currency = "GBP,CNY" } we_chat_pay = { country = "GB",currency = "CNY" } diff --git a/config/development.toml b/config/development.toml index c15532805db..32ef78e0ded 100644 --- a/config/development.toml +++ b/config/development.toml @@ -662,6 +662,9 @@ apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,G google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +[payout_method_filters.nuvei] +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.checkout] debit = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MT,NL,NO,PL,PT,RO,SK,SI,ES,SE,CH,GB,US,AU,HK,SG,SA,AE,BH,MX,AR,CL,CO,PE", currency = "AED,AFN,ALL,AMD,ANG,AOA,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,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,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" } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 0b4d53c1857..edc6bf78759 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -49,6 +49,7 @@ pub enum PayoutConnectors { Cybersource, Ebanx, Nomupay, + Nuvei, Payone, Paypal, Stripe, @@ -75,6 +76,7 @@ impl From<PayoutConnectors> for RoutableConnectors { PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Nomupay => Self::Nomupay, + PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, @@ -92,6 +94,7 @@ impl From<PayoutConnectors> for Connector { PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Nomupay => Self::Nomupay, + PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, @@ -109,6 +112,7 @@ impl TryFrom<Connector> for PayoutConnectors { Connector::Adyenplatform => Ok(Self::Adyenplatform), Connector::Cybersource => Ok(Self::Cybersource), Connector::Ebanx => Ok(Self::Ebanx), + Connector::Nuvei => Ok(Self::Nuvei), Connector::Nomupay => Ok(Self::Nomupay), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index aed9dbf70de..d35ddc09b25 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -308,6 +308,7 @@ pub struct ConnectorConfig { pub noon: Option<ConnectorTomlConfig>, pub nordea: Option<ConnectorTomlConfig>, pub novalnet: Option<ConnectorTomlConfig>, + pub nuvei_payout: Option<ConnectorTomlConfig>, pub nuvei: Option<ConnectorTomlConfig>, pub paybox: Option<ConnectorTomlConfig>, pub payload: Option<ConnectorTomlConfig>, @@ -398,6 +399,7 @@ impl ConnectorConfig { PayoutConnectors::Cybersource => Ok(connector_data.cybersource_payout), PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout), PayoutConnectors::Nomupay => Ok(connector_data.nomupay_payout), + PayoutConnectors::Nuvei => Ok(connector_data.nuvei_payout), PayoutConnectors::Payone => Ok(connector_data.payone_payout), PayoutConnectors::Paypal => Ok(connector_data.paypal_payout), PayoutConnectors::Stripe => Ok(connector_data.stripe_payout), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 4b4bbc6ec83..2c79270cb16 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -3781,7 +3781,49 @@ required=true type="MultiSelect" options=["PAN_ONLY", "CRYPTOGRAM_3DS"] - +[nuvei_payout] +[[nuvei_payout.credit]] + payment_method_type = "Mastercard" +[[nuvei_payout.credit]] + payment_method_type = "Visa" +[[nuvei_payout.credit]] + payment_method_type = "Interac" +[[nuvei_payout.credit]] + payment_method_type = "AmericanExpress" +[[nuvei_payout.credit]] + payment_method_type = "JCB" +[[nuvei_payout.credit]] + payment_method_type = "DinersClub" +[[nuvei_payout.credit]] + payment_method_type = "Discover" +[[nuvei_payout.credit]] + payment_method_type = "CartesBancaires" +[[nuvei_payout.credit]] + payment_method_type = "UnionPay" +[[nuvei_payout.debit]] + payment_method_type = "Mastercard" +[[nuvei_payout.debit]] + payment_method_type = "Visa" +[[nuvei_payout.debit]] + payment_method_type = "Interac" +[[nuvei_payout.debit]] + payment_method_type = "AmericanExpress" +[[nuvei_payout.debit]] + payment_method_type = "JCB" +[[nuvei_payout.debit]] + payment_method_type = "DinersClub" +[[nuvei_payout.debit]] + payment_method_type = "Discover" +[[nuvei_payout.debit]] + payment_method_type = "CartesBancaires" +[[nuvei_payout.debit]] + payment_method_type = "UnionPay" +[nuvei_payout.connector_auth.SignatureKey] +api_key="Merchant ID" +key1="Merchant Site ID" +api_secret="Merchant Secret" +[nuvei_payout.connector_webhook_details] +merchant_secret="Source verification key" [opennode] [[opennode.crypto]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 86eea4d3534..d65208a74b7 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -2908,6 +2908,49 @@ required = true type = "Radio" options = ["Connector","Hyperswitch"] +[nuvei_payout] +[[nuvei_payout.credit]] + payment_method_type = "Mastercard" +[[nuvei_payout.credit]] + payment_method_type = "Visa" +[[nuvei_payout.credit]] + payment_method_type = "Interac" +[[nuvei_payout.credit]] + payment_method_type = "AmericanExpress" +[[nuvei_payout.credit]] + payment_method_type = "JCB" +[[nuvei_payout.credit]] + payment_method_type = "DinersClub" +[[nuvei_payout.credit]] + payment_method_type = "Discover" +[[nuvei_payout.credit]] + payment_method_type = "CartesBancaires" +[[nuvei_payout.credit]] + payment_method_type = "UnionPay" +[[nuvei_payout.debit]] + payment_method_type = "Mastercard" +[[nuvei_payout.debit]] + payment_method_type = "Visa" +[[nuvei_payout.debit]] + payment_method_type = "Interac" +[[nuvei_payout.debit]] + payment_method_type = "AmericanExpress" +[[nuvei_payout.debit]] + payment_method_type = "JCB" +[[nuvei_payout.debit]] + payment_method_type = "DinersClub" +[[nuvei_payout.debit]] + payment_method_type = "Discover" +[[nuvei_payout.debit]] + payment_method_type = "CartesBancaires" +[[nuvei_payout.debit]] + payment_method_type = "UnionPay" +[nuvei_payout.connector_auth.SignatureKey] +api_key="Merchant ID" +key1="Merchant Site ID" +api_secret="Merchant Secret" +[nuvei_payout.connector_webhook_details] +merchant_secret="Source verification key" [opennode] [[opennode.crypto]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 08ae831a52e..e99620c8892 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -3754,6 +3754,49 @@ required = true type = "MultiSelect" options = ["PAN_ONLY", "CRYPTOGRAM_3DS"] +[nuvei_payout] +[[nuvei_payout.credit]] + payment_method_type = "Mastercard" +[[nuvei_payout.credit]] + payment_method_type = "Visa" +[[nuvei_payout.credit]] + payment_method_type = "Interac" +[[nuvei_payout.credit]] + payment_method_type = "AmericanExpress" +[[nuvei_payout.credit]] + payment_method_type = "JCB" +[[nuvei_payout.credit]] + payment_method_type = "DinersClub" +[[nuvei_payout.credit]] + payment_method_type = "Discover" +[[nuvei_payout.credit]] + payment_method_type = "CartesBancaires" +[[nuvei_payout.credit]] + payment_method_type = "UnionPay" +[[nuvei_payout.debit]] + payment_method_type = "Mastercard" +[[nuvei_payout.debit]] + payment_method_type = "Visa" +[[nuvei_payout.debit]] + payment_method_type = "Interac" +[[nuvei_payout.debit]] + payment_method_type = "AmericanExpress" +[[nuvei_payout.debit]] + payment_method_type = "JCB" +[[nuvei_payout.debit]] + payment_method_type = "DinersClub" +[[nuvei_payout.debit]] + payment_method_type = "Discover" +[[nuvei_payout.debit]] + payment_method_type = "CartesBancaires" +[[nuvei_payout.debit]] + payment_method_type = "UnionPay" +[nuvei_payout.connector_auth.SignatureKey] +api_key="Merchant ID" +key1="Merchant Site ID" +api_secret="Merchant Secret" +[nuvei_payout.connector_webhook_details] +merchant_secret="Source verification key" [opennode] [[opennode.crypto]] diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs index 4dd8973bd63..d6a0e677cf3 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs @@ -1,6 +1,8 @@ pub mod transformers; use std::sync::LazyLock; +#[cfg(feature = "payouts")] +use api_models::webhooks::PayoutIdType; use api_models::{ payments::PaymentIdType, webhooks::{IncomingWebhookEvent, RefundIdType}, @@ -44,6 +46,11 @@ use hyperswitch_domain_models::{ PaymentsSyncRouterData, RefundsRouterData, }, }; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::payouts::PoFulfill, router_request_types::PayoutsData, + router_response_types::PayoutsResponseData, types::PayoutsRouterData, +}; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, @@ -164,6 +171,87 @@ impl api::ConnectorAccessToken for Nuvei {} impl api::PaymentsPreProcessing for Nuvei {} impl api::PaymentPostCaptureVoid for Nuvei {} +impl api::Payouts for Nuvei {} +#[cfg(feature = "payouts")] +impl api::PayoutFulfill for Nuvei {} + +#[async_trait::async_trait] +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Nuvei { + fn get_url( + &self, + _req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}ppp/api/v1/payout.do", + ConnectorCommon::base_url(self, connectors) + )) + } + + fn get_headers( + &self, + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_request_body( + &self, + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = nuvei::NuveiPayoutRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::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, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &PayoutsRouterData<PoFulfill>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> { + let response: nuvei::NuveiPayoutResponse = + res.response.parse_struct("NuveiPayoutResponse").switch()?; + 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 Nuvei { fn get_headers( &self, @@ -1025,6 +1113,15 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nuvei { } } +fn has_payout_prefix(id_option: &Option<String>) -> bool { + // - Default value returns false if the Option is `None`. + // - The argument is a closure that runs if the Option is `Some`. + // It takes the contained value (`s`) and its result is returned. + id_option + .as_deref() + .is_some_and(|s| s.starts_with("payout_")) +} + #[async_trait::async_trait] impl IncomingWebhook for Nuvei { fn get_webhook_source_verification_algorithm( @@ -1106,34 +1203,54 @@ impl IncomingWebhook for Nuvei { let webhook = get_webhook_object_from_body(request.body)?; // Extract transaction ID from the webhook match &webhook { - nuvei::NuveiWebhook::PaymentDmn(notification) => match notification.transaction_type { - Some(nuvei::NuveiTransactionType::Auth) - | Some(nuvei::NuveiTransactionType::Sale) - | Some(nuvei::NuveiTransactionType::Settle) - | Some(nuvei::NuveiTransactionType::Void) - | Some(nuvei::NuveiTransactionType::Auth3D) - | Some(nuvei::NuveiTransactionType::InitAuth3D) => { - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - PaymentIdType::ConnectorTransactionId( - notification - .transaction_id - .clone() - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - ), - )) - } - Some(nuvei::NuveiTransactionType::Credit) => { - Ok(api_models::webhooks::ObjectReferenceId::RefundId( - RefundIdType::ConnectorRefundId( - notification - .transaction_id - .clone() - .ok_or(errors::ConnectorError::MissingConnectorRefundID)?, - ), - )) + nuvei::NuveiWebhook::PaymentDmn(notification) => { + // if prefix contains 'payout_' then it is a payout related webhook + if has_payout_prefix(&notification.client_request_id) { + #[cfg(feature = "payouts")] + { + Ok(api_models::webhooks::ObjectReferenceId::PayoutId( + PayoutIdType::PayoutAttemptId( + notification + .client_request_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, + ), + )) + } + #[cfg(not(feature = "payouts"))] + { + Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) + } + } else { + match notification.transaction_type { + Some(nuvei::NuveiTransactionType::Auth) + | Some(nuvei::NuveiTransactionType::Sale) + | Some(nuvei::NuveiTransactionType::Settle) + | Some(nuvei::NuveiTransactionType::Void) + | Some(nuvei::NuveiTransactionType::Auth3D) + | Some(nuvei::NuveiTransactionType::InitAuth3D) => { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + PaymentIdType::ConnectorTransactionId( + notification.transaction_id.clone().ok_or( + errors::ConnectorError::MissingConnectorTransactionID, + )?, + ), + )) + } + Some(nuvei::NuveiTransactionType::Credit) => { + Ok(api_models::webhooks::ObjectReferenceId::RefundId( + RefundIdType::ConnectorRefundId( + notification + .transaction_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorRefundID)?, + ), + )) + } + None => Err(errors::ConnectorError::WebhookEventTypeNotFound.into()), + } } - None => Err(errors::ConnectorError::WebhookEventTypeNotFound.into()), - }, + } nuvei::NuveiWebhook::Chargeback(notification) => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( PaymentIdType::ConnectorTransactionId( @@ -1154,7 +1271,22 @@ impl IncomingWebhook for Nuvei { // Map webhook type to event type match webhook { nuvei::NuveiWebhook::PaymentDmn(notification) => { - if let Some((status, transaction_type)) = + if has_payout_prefix(&notification.client_request_id) { + #[cfg(feature = "payouts")] + { + if let Some((status, transaction_type)) = + notification.status.zip(notification.transaction_type) + { + nuvei::map_notification_to_event_for_payout(status, transaction_type) + } else { + Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) + } + } + #[cfg(not(feature = "payouts"))] + { + Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) + } + } else if let Some((status, transaction_type)) = notification.status.zip(notification.transaction_type) { nuvei::map_notification_to_event(status, transaction_type) diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 39776916056..4cf5c2d9807 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -36,6 +36,10 @@ use hyperswitch_domain_models::{ }, types, }; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::payouts::PoFulfill, router_response_types::PayoutsResponseData, +}; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors::{self}, @@ -44,6 +48,8 @@ use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; +#[cfg(feature = "payouts")] +use crate::{types::PayoutsResponseRouterData, utils::PayoutsData as _}; use crate::{ types::{ PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData, @@ -2320,6 +2326,192 @@ impl TryFrom<&ConnectorAuthType> for NuveiAuthType { } } +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiPayoutRequest { + pub merchant_id: Secret<String>, + pub merchant_site_id: Secret<String>, + pub client_request_id: String, + pub client_unique_id: String, + pub amount: StringMajorUnit, + pub currency: String, + pub user_token_id: CustomerId, + pub time_stamp: String, + pub checksum: Secret<String>, + pub card_data: NuveiPayoutCardData, + pub url_details: NuveiPayoutUrlDetails, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiPayoutUrlDetails { + pub notification_url: String, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiPayoutCardData { + pub card_number: cards::CardNumber, + pub card_holder_name: Secret<String>, + pub expiration_month: Secret<String>, + pub expiration_year: Secret<String>, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum NuveiPayoutResponse { + NuveiPayoutSuccessResponse(NuveiPayoutSuccessResponse), + NuveiPayoutErrorResponse(NuveiPayoutErrorResponse), +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiPayoutSuccessResponse { + pub transaction_id: String, + pub user_token_id: CustomerId, + pub transaction_status: NuveiTransactionStatus, + pub client_unique_id: String, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiPayoutErrorResponse { + pub status: NuveiPaymentStatus, + pub err_code: i64, + pub reason: Option<String>, +} + +#[cfg(feature = "payouts")] +impl TryFrom<api_models::payouts::PayoutMethodData> for NuveiPayoutCardData { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + payout_method_data: api_models::payouts::PayoutMethodData, + ) -> Result<Self, Self::Error> { + match payout_method_data { + api_models::payouts::PayoutMethodData::Card(card_data) => Ok(Self { + card_number: card_data.card_number, + card_holder_name: card_data.card_holder_name.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "customer_id", + }, + )?, + expiration_month: card_data.expiry_month, + expiration_year: card_data.expiry_year, + }), + api_models::payouts::PayoutMethodData::Bank(_) + | api_models::payouts::PayoutMethodData::Wallet(_) => { + Err(errors::ConnectorError::NotImplemented( + "Selected Payout Method is not implemented for Nuvei".to_string(), + ) + .into()) + } + } + } +} + +#[cfg(feature = "payouts")] +impl<F> TryFrom<&types::PayoutsRouterData<F>> for NuveiPayoutRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + let connector_auth: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?; + + let amount = convert_amount( + NUVEI_AMOUNT_CONVERTOR, + item.request.minor_amount, + item.request.destination_currency, + )?; + + let time_stamp = + date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let checksum = encode_payload(&[ + connector_auth.merchant_id.peek(), + connector_auth.merchant_site_id.peek(), + &item.connector_request_reference_id, + &amount.get_amount_as_string(), + &item.request.destination_currency.to_string(), + &time_stamp, + connector_auth.merchant_secret.peek(), + ])?; + + let payout_method_data = item.get_payout_method_data()?; + + let card_data = NuveiPayoutCardData::try_from(payout_method_data)?; + + let customer_details = item.request.get_customer_details()?; + + let url_details = NuveiPayoutUrlDetails { + notification_url: item.request.get_webhook_url()?, + }; + + Ok(Self { + merchant_id: connector_auth.merchant_id, + merchant_site_id: connector_auth.merchant_site_id, + client_request_id: item.connector_request_reference_id.clone(), + client_unique_id: item.connector_request_reference_id.clone(), + amount, + currency: item.request.destination_currency.to_string(), + user_token_id: customer_details.customer_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "customer_id", + }, + )?, + time_stamp, + checksum: Secret::new(checksum), + card_data, + url_details, + }) + } +} + +#[cfg(feature = "payouts")] +impl TryFrom<PayoutsResponseRouterData<PoFulfill, NuveiPayoutResponse>> + for types::PayoutsRouterData<PoFulfill> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: PayoutsResponseRouterData<PoFulfill, NuveiPayoutResponse>, + ) -> Result<Self, Self::Error> { + let response = &item.response; + + match response { + NuveiPayoutResponse::NuveiPayoutSuccessResponse(response_data) => Ok(Self { + response: Ok(PayoutsResponseData { + status: Some(enums::PayoutStatus::from( + response_data.transaction_status.clone(), + )), + connector_payout_id: Some(response_data.transaction_id.clone()), + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + error_code: None, + error_message: None, + }), + ..item.data + }), + NuveiPayoutResponse::NuveiPayoutErrorResponse(error_response_data) => Ok(Self { + response: Ok(PayoutsResponseData { + status: Some(enums::PayoutStatus::from( + error_response_data.status.clone(), + )), + connector_payout_id: None, + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + error_code: Some(error_response_data.err_code.to_string()), + error_message: error_response_data.reason.clone(), + }), + ..item.data + }), + } + } +} + #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum NuveiPaymentStatus { @@ -2358,6 +2550,29 @@ impl From<NuveiTransactionStatus> for enums::AttemptStatus { } } +#[cfg(feature = "payouts")] +impl From<NuveiTransactionStatus> for enums::PayoutStatus { + fn from(item: NuveiTransactionStatus) -> Self { + match item { + NuveiTransactionStatus::Approved => Self::Success, + NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => Self::Failed, + NuveiTransactionStatus::Processing | NuveiTransactionStatus::Pending => Self::Pending, + NuveiTransactionStatus::Redirect => Self::Ineligible, + } + } +} + +#[cfg(feature = "payouts")] +impl From<NuveiPaymentStatus> for enums::PayoutStatus { + fn from(item: NuveiPaymentStatus) -> Self { + match item { + NuveiPaymentStatus::Success => Self::Success, + NuveiPaymentStatus::Failed | NuveiPaymentStatus::Error => Self::Failed, + NuveiPaymentStatus::Processing => Self::Pending, + } + } +} + #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPartialApproval { @@ -3854,6 +4069,24 @@ pub fn map_notification_to_event( } } +#[cfg(feature = "payouts")] +pub fn map_notification_to_event_for_payout( + status: DmnStatus, + transaction_type: NuveiTransactionType, +) -> Result<api_models::webhooks::IncomingWebhookEvent, error_stack::Report<errors::ConnectorError>> +{ + match (status, transaction_type) { + (DmnStatus::Success | DmnStatus::Approved, NuveiTransactionType::Credit) => { + Ok(api_models::webhooks::IncomingWebhookEvent::PayoutSuccess) + } + (DmnStatus::Pending, _) => Ok(api_models::webhooks::IncomingWebhookEvent::PayoutProcessing), + (DmnStatus::Declined | DmnStatus::Error, _) => { + Ok(api_models::webhooks::IncomingWebhookEvent::PayoutFailure) + } + _ => Err(errors::ConnectorError::WebhookEventTypeNotFound.into()), + } +} + pub fn map_dispute_notification_to_event( dispute_code: DisputeUnifiedStatusCode, ) -> Result<api_models::webhooks::IncomingWebhookEvent, error_stack::Report<errors::ConnectorError>> diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index f742437f400..ffd4254840f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -3855,7 +3855,6 @@ default_imp_for_payouts!( connectors::Nmi, connectors::Noon, connectors::Novalnet, - connectors::Nuvei, connectors::Payeezy, connectors::Payload, connectors::Payme, @@ -4430,7 +4429,6 @@ default_imp_for_payouts_fulfill!( connectors::Opayo, connectors::Opennode, connectors::Nmi, - connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 85051693105..f137807a208 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -6397,8 +6397,8 @@ pub trait PayoutsData { &self, ) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error>; fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>; - #[cfg(feature = "payouts")] fn get_payout_type(&self) -> Result<enums::PayoutType, Error>; + fn get_webhook_url(&self) -> Result<String, Error>; } #[cfg(feature = "payouts")] @@ -6420,12 +6420,16 @@ impl PayoutsData for hyperswitch_domain_models::router_request_types::PayoutsDat .clone() .ok_or_else(missing_field_err("vendor_details")) } - #[cfg(feature = "payouts")] fn get_payout_type(&self) -> Result<enums::PayoutType, Error> { self.payout_type .to_owned() .ok_or_else(missing_field_err("payout_type")) } + fn get_webhook_url(&self) -> Result<String, Error> { + self.webhook_url + .to_owned() + .ok_or_else(missing_field_err("webhook_url")) + } } pub trait RevokeMandateRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error>; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 3f9d4f333c2..ac79b5177e7 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -1308,6 +1308,7 @@ pub struct PayoutsData { pub minor_amount: MinorUnit, pub priority: Option<storage_enums::PayoutSendPriority>, pub connector_transfer_method_id: Option<String>, + pub webhook_url: Option<String>, } #[derive(Debug, Default, Clone)] diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 86d9e2c1e64..c132ec8d128 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -1474,8 +1474,8 @@ pub async fn check_payout_eligibility( let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, - error_code: None, - error_message: None, + error_code: payout_response_data.error_code, + error_message: payout_response_data.error_message, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, @@ -1689,8 +1689,8 @@ pub async fn create_payout( let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, - error_code: None, - error_message: None, + error_code: payout_response_data.error_code, + error_message: payout_response_data.error_message, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, @@ -2076,8 +2076,8 @@ pub async fn create_recipient_disburse_account( let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id.clone(), status, - error_code: None, - error_message: None, + error_code: payout_response_data.error_code, + error_message: payout_response_data.error_message, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, @@ -2413,8 +2413,8 @@ pub async fn fulfill_payout( let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, - error_code: None, - error_message: None, + error_code: payout_response_data.error_code, + error_message: payout_response_data.error_message, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index df548fe6401..30bc466063b 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -140,6 +140,15 @@ pub async fn construct_payout_router_data<'a, F>( _ => None, }; + let webhook_url = helpers::create_webhook_url( + &state.base_url, + &merchant_context.get_merchant_account().get_id().to_owned(), + merchant_connector_account + .get_mca_id() + .get_required_value("merchant_connector_id")? + .get_string_repr(), + ); + let connector_transfer_method_id = payout_helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?; @@ -187,6 +196,7 @@ pub async fn construct_payout_router_data<'a, F>( tax_registration_id: c.tax_registration_id.map(Encryptable::into_inner), }), connector_transfer_method_id, + webhook_url: Some(webhook_url), }, response: Ok(types::PayoutsResponseData::default()), access_token: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index b2582d7e3fe..8f1c6c128c2 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -477,6 +477,7 @@ pub trait ConnectorActions: Connector { vendor_details: None, priority: None, connector_transfer_method_id: None, + webhook_url: None, }, payment_info, )
2025-09-30T08:17:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Add Cards Payout through Nuvei - Add Webhook support for Payouts in Nuvei - Propagate error from failure response in payouts - Create webhook_url in PayoutsData Request to pass to Psp's ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested through Postman: Create an MCA (Nuvei): Creata a Card Payouts: ``` curl --location '{{baseUrl}}/payouts/create' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 10, "currency": "EUR", "customer_id": "payout_customer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payout request", "payout_type": "card", "payout_method_data": { "card": { "card_number": "4000027891380961", "expiry_month": "12", "expiry_year": "2025", "card_holder_name": "CL-BRW1" } }, "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "auto_fulfill": true, "confirm": true }' ``` The response should be succeeded and you should receive an webhook ``` { "payout_id": "payout_NOakA22TBihvGMX3h2Qb", "merchant_id": "merchant_1759235409", "merchant_order_reference_id": null, "amount": 10, "currency": "EUR", "connector": "nuvei", "payout_type": "card", "payout_method_data": { "card": { "card_issuer": null, "card_network": null, "card_type": null, "card_issuing_country": null, "bank_code": null, "last4": "0961", "card_isin": "400002", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2025", "card_holder_name": "CL-BRW1" } }, "billing": null, "auto_fulfill": true, "customer_id": "payout_customer", "customer": { "id": "payout_customer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "client_secret": "payout_payout_NOakA22TBihvGMX3h2Qb_secret_jCqeQBT3uVeU77Oth6Pl", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "merchant_connector_id": "mca_cDe3Fa7sUarn7ryqAMOk", "status": "success", "error_message": null, "error_code": null, "profile_id": "pro_9bk44BClwKvHHsVHiRIV", "created": "2025-09-30T12:40:14.361Z", "connector_transaction_id": "7110000000017707955", "priority": null, "payout_link": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "unified_code": null, "unified_message": null, "payout_method_id": "pm_WkPPJd9Tr9Mnmw73fkG5" } ``` Payout success event should be received and webhook should be source verified <img width="1053" height="181" alt="image" src="https://github.com/user-attachments/assets/d1faab18-43ad-4d1b-92cc-1e1a60617d73" /> <img width="1048" height="155" alt="image" src="https://github.com/user-attachments/assets/108502c2-630c-40b7-a1ee-4d794ce53f71" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
efab34f0ef0bd032b049778f18f3cb688faa7fa7
juspay/hyperswitch
juspay__hyperswitch-9616
Bug: [BUG] fix(payments): add connector error details in response when payment void fails ### Bug Description When a payment void fails at the connector level, the error was not being propagated back in the API response. This change ensures connector error details are included in the response, so clients can handle failures appropriately. ### Expected Behavior When a payment void fails at the connector level, the error was not being propagated back in the API response. This change ensures connector error details are included in the response, so clients can handle failures appropriately. ### Actual Behavior Currently error is not coming in payment void if failed at connector level. ### 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/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 7f397d6c60e..229dd6c241b 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4921,6 +4921,9 @@ pub struct PaymentsCancelResponse { /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, + + /// Error details for the payment + pub error: Option<ErrorDetails>, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] @@ -6189,6 +6192,8 @@ pub struct ErrorDetails { pub code: String, /// The error message pub message: String, + /// The detailed error reason that was returned by the connector. + pub reason: Option<String>, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index ad778e9aa74..fd66a8e2894 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -1830,10 +1830,11 @@ impl { fn get_payment_intent_update( &self, - _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, + payment_data: &payments::PaymentCancelData<router_flow_types::Void>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { - let intent_status = common_enums::IntentStatus::from(self.status); + let intent_status = + common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data)); PaymentIntentUpdate::VoidUpdate { status: intent_status, updated_by: storage_scheme.to_string(), @@ -1845,10 +1846,55 @@ impl payment_data: &payments::PaymentCancelData<router_flow_types::Void>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { - PaymentAttemptUpdate::VoidUpdate { - status: self.status, - cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(), - updated_by: storage_scheme.to_string(), + match &self.response { + Err(ref error_response) => { + let ErrorResponse { + code, + message, + reason, + status_code: _, + attempt_status: _, + connector_transaction_id, + network_decline_code, + network_advice_code, + network_error_message, + connector_metadata: _, + } = error_response.clone(); + + // Handle errors exactly + let status = match error_response.attempt_status { + // Use the status sent by connector in error_response if it's present + Some(status) => status, + None => match error_response.status_code { + 500..=511 => common_enums::AttemptStatus::Pending, + _ => common_enums::AttemptStatus::VoidFailed, + }, + }; + + let error_details = ErrorDetails { + code, + message, + reason, + unified_code: None, + unified_message: None, + network_advice_code, + network_decline_code, + network_error_message, + }; + + PaymentAttemptUpdate::ErrorUpdate { + status, + amount_capturable: Some(MinorUnit::zero()), + error: error_details, + updated_by: storage_scheme.to_string(), + connector_payment_id: connector_transaction_id, + } + } + Ok(ref _response) => PaymentAttemptUpdate::VoidUpdate { + status: self.status, + cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(), + updated_by: storage_scheme.to_string(), + }, } } @@ -1872,7 +1918,16 @@ impl &self, _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, ) -> common_enums::AttemptStatus { - // For void operations, return Voided status - common_enums::AttemptStatus::Voided + // For void operations, determine status based on response + match &self.response { + Err(ref error_response) => match error_response.attempt_status { + Some(status) => status, + None => match error_response.status_code { + 500..=511 => common_enums::AttemptStatus::Pending, + _ => common_enums::AttemptStatus::VoidFailed, + }, + }, + Ok(ref _response) => self.status, + } } } diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs index 40be24722a5..bf6aaac1acb 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs @@ -14,6 +14,7 @@ pub struct PaymentFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub connector_customer: Option<String>, + pub connector: String, pub payment_id: String, pub attempt_id: String, pub status: common_enums::AttemptStatus, diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index 3d3219a33f8..6b327f98496 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -218,6 +218,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentF merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone(), connector_customer: old_router_data.connector_customer.clone(), + connector: old_router_data.connector.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), status: old_router_data.status, @@ -264,6 +265,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentF merchant_id, customer_id, connector_customer, + connector, payment_id, attempt_id, status, @@ -299,6 +301,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentF router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.connector_customer = connector_customer; + router_data.connector = connector; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.status = status; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index fa84e149118..fd90ca248eb 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1008,6 +1008,7 @@ pub async fn construct_cancel_router_data_v2<'a>( request: types::PaymentsCancelData, connector_request_reference_id: String, customer_id: Option<common_utils::id_type::CustomerId>, + connector_id: &str, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult< RouterDataV2< @@ -1026,6 +1027,7 @@ pub async fn construct_cancel_router_data_v2<'a>( merchant_id: merchant_account.get_id().clone(), customer_id, connector_customer: None, + connector: connector_id.to_owned(), payment_id: payment_data .payment_attempt .payment_id @@ -1140,6 +1142,7 @@ pub async fn construct_router_data_for_cancel<'a>( request, connector_request_reference_id.clone(), customer_id.clone(), + connector_id, header_payload.clone(), ) .await?; @@ -2169,6 +2172,11 @@ where .connector .as_ref() .and_then(|conn| api_enums::Connector::from_str(conn).ok()); + let error = payment_attempt + .error + .as_ref() + .map(api_models::payments::ErrorDetails::foreign_from); + let response = api_models::payments::PaymentsCancelResponse { id: payment_intent.id.clone(), status: payment_intent.status, @@ -2181,6 +2189,7 @@ where payment_method_subtype: Some(payment_attempt.payment_method_subtype), attempts: None, return_url: payment_intent.return_url.clone(), + error, }; let headers = connector_http_status_code @@ -5972,6 +5981,7 @@ impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::ErrorDet Self { code: error_details.code.to_owned(), message: error_details.message.to_owned(), + reason: error_details.reason.clone(), unified_code: error_details.unified_code.clone(), unified_message: error_details.unified_message.clone(), network_advice_code: error_details.network_advice_code.clone(),
2025-09-29T08:52:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add error details when payment void is failed at connector level and update the status accordingly. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01999518b93e7d92bf68807c23919ddd/cancel' \ --header 'X-Profile-Id: pro_qBLZYRTYcOoyu0qPg4Nn' \ --header 'X-Merchant-Id: cloth_seller_nG8IQZGXCrxMkMyNF6oL' \ --header 'Authorization: api-key=dev_JqT4NtSwFvhxcBGkuWyDTIHvC7tkwp63QoyATDSxZ5X6PzudKWtOkzbJJvwZuRl3' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_JqT4NtSwFvhxcBGkuWyDTIHvC7tkwp63QoyATDSxZ5X6PzudKWtOkzbJJvwZuRl3' \ --data '{ "cancellation_reason": "duplicat" }' ``` Response: ``` { "id": "12345_pay_01999518b93e7d92bf68807c23919ddd", "status": "failed", "cancellation_reason": "duplicat", "amount": { "order_amount": 10000, "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": 10000, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 0 }, "customer_id": "12345_cus_019995055fdd795190c715dccfbcdef4", "connector": "stripe", "created": "2025-09-29T10:50:49.594Z", "payment_method_type": "card", "payment_method_subtype": "credit", "attempts": null, "return_url": null, "error": { "code": "No error code", "message": "No error message", "reason": "Invalid cancellation_reason: must be one of duplicate, fraudulent, requested_by_customer, or abandoned", "unified_code": null, "unified_message": null, "network_advice_code": null, "network_decline_code": null, "network_error_message": null } } ``` Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0199951c2f4274b3b5a2825b0849a279/cancel' \ --header 'X-Profile-Id: pro_qBLZYRTYcOoyu0qPg4Nn' \ --header 'X-Merchant-Id: cloth_seller_nG8IQZGXCrxMkMyNF6oL' \ --header 'Authorization: api-key=dev_JqT4NtSwFvhxcBGkuWyDTIHvC7tkwp63QoyATDSxZ5X6PzudKWtOkzbJJvwZuRl3' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_JqT4NtSwFvhxcBGkuWyDTIHvC7tkwp63QoyATDSxZ5X6PzudKWtOkzbJJvwZuRl3' \ --data '{ "cancellation_reason": "duplicate" }' ``` Response: ``` { "id": "12345_pay_0199951c2f4274b3b5a2825b0849a279", "status": "cancelled", "cancellation_reason": "duplicate", "amount": { "order_amount": 10000, "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": 10000, "amount_to_capture": null, "amount_capturable": 10000, "amount_captured": 0 }, "customer_id": "12345_cus_019995055fdd795190c715dccfbcdef4", "connector": "stripe", "created": "2025-09-29T10:54:36.366Z", "payment_method_type": "card", "payment_method_subtype": "credit", "attempts": null, "return_url": null, "error": null } ``` closes #9616 ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9cd8f001f7360d9b8877fe94b9c185fc237e525c
juspay/hyperswitch
juspay__hyperswitch-9621
Bug: [FEATURE] : [Loonio] Implement interac Bank Redirect Payment Method Implement interac Bank Redirect Payment Method - Payments - Psync
diff --git a/config/config.example.toml b/config/config.example.toml index f584755d516..829a9bcec48 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -253,7 +253,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url= "https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" -loonio.base_url = "https://loonio.ca/" +loonio.base_url = "https://integration.loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index ea34d70769a..b67a323c05c 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -91,7 +91,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url="https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" -loonio.base_url = "https://loonio.ca/" +loonio.base_url = "https://integration.loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" @@ -766,6 +766,9 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C [pm_filters.gigadat] interac = { currency = "CAD"} +[pm_filters.loonio] +interac = { currency = "CAD"} + [payout_method_filters.adyenplatform] sepa = { country = "AT,BE,CH,CZ,DE,EE,ES,FI,FR,GB,HU,IE,IT,LT,LV,NL,NO,PL,PT,SE,SK", currency = "EUR,CZK,DKK,HUF,NOK,PLN,SEK,GBP,CHF" } credit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT,LU,LV,MT,NL,NO,PL,PT,RO,SE,SI,SK,US", currency = "EUR,USD,GBP" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 84adba409b3..f3c97876836 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -791,6 +791,9 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C [pm_filters.gigadat] interac = { currency = "CAD"} +[pm_filters.loonio] +interac = { currency = "CAD"} + [pm_filters.coingate] crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index e5f9c327245..db907d94e3e 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -94,7 +94,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url="https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" -loonio.base_url = "https://loonio.ca/" +loonio.base_url = "https://integration.loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" @@ -801,6 +801,9 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C [pm_filters.gigadat] interac = { currency = "CAD"} +[pm_filters.loonio] +interac = { currency = "CAD"} + [pm_filters.coingate] crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } diff --git a/config/development.toml b/config/development.toml index 1a16b15c42b..e36688974d3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -291,7 +291,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url = "https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" -loonio.base_url = "https://loonio.ca/" +loonio.base_url = "https://integration.loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" @@ -784,6 +784,9 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C [pm_filters.gigadat] interac = { currency = "CAD"} +[pm_filters.loonio] +interac = { currency = "CAD"} + [pm_filters.mollie] credit = { not_available_flows = { capture_method = "manual" } } debit = { not_available_flows = { capture_method = "manual" } } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9d5991a3125..30c9b64bd64 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -179,7 +179,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url="https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" -loonio.base_url = "https://loonio.ca/" +loonio.base_url = "https://integration.loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" @@ -934,6 +934,9 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C [pm_filters.gigadat] interac = { currency = "CAD"} +[pm_filters.loonio] +interac = { currency = "CAD"} + [pm_filters.coingate] crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index a4369cd7862..2db7e7613d8 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -113,6 +113,7 @@ pub enum RoutableConnectors { Itaubank, Jpmorgan, Klarna, + Loonio, Mifinity, Mollie, Moneris, @@ -293,6 +294,7 @@ pub enum Connector { Jpmorgan, Juspaythreedsserver, Klarna, + Loonio, Mifinity, Mollie, Moneris, @@ -491,6 +493,7 @@ impl Connector { | Self::Jpmorgan | Self::Juspaythreedsserver | Self::Klarna + | Self::Loonio | Self::Mifinity | Self::Mollie | Self::Moneris @@ -672,6 +675,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Itaubank => Self::Itaubank, RoutableConnectors::Jpmorgan => Self::Jpmorgan, RoutableConnectors::Klarna => Self::Klarna, + RoutableConnectors::Loonio => Self::Loonio, RoutableConnectors::Mifinity => Self::Mifinity, RoutableConnectors::Mollie => Self::Mollie, RoutableConnectors::Moneris => Self::Moneris, @@ -808,6 +812,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Itaubank => Ok(Self::Itaubank), Connector::Jpmorgan => Ok(Self::Jpmorgan), Connector::Klarna => Ok(Self::Klarna), + Connector::Loonio => Ok(Self::Loonio), Connector::Mifinity => Ok(Self::Mifinity), Connector::Mollie => Ok(Self::Mollie), Connector::Moneris => Ok(Self::Moneris), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index c01ac16c0e1..41d3cb1b5d1 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -511,6 +511,7 @@ impl ConnectorConfig { Connector::Jpmorgan => Ok(connector_data.jpmorgan), Connector::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver), Connector::Klarna => Ok(connector_data.klarna), + Connector::Loonio => Ok(connector_data.loonio), Connector::Mifinity => Ok(connector_data.mifinity), Connector::Mollie => Ok(connector_data.mollie), Connector::Moneris => Ok(connector_data.moneris), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 0f98861cc04..84dfabd1c50 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7187,6 +7187,10 @@ api_key = "API Key" [tesouro.connector_auth.BodyKey] api_key="Client ID" key1="Client Secret" + [loonio] -[loonio.connector_auth.HeaderKey] -api_key = "API Key" +[loonio.connector_auth.BodyKey] +api_key = "Merchant ID" +api_secret = "Merchant Token" +[[loonio.bank_redirect]] +payment_method_type = "interac" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index aea8277906e..b4fcbe8e18c 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5924,6 +5924,10 @@ api_key = "API Key" [tesouro.connector_auth.BodyKey] api_key="Client ID" key1="Client Secret" + [loonio] -[loonio.connector_auth.HeaderKey] -api_key = "API Key" +[loonio.connector_auth.BodyKey] +api_key = "Merchant ID" +api_secret = "Merchant Token" +[[loonio.bank_redirect]] +payment_method_type = "interac" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index f7c7ed3e997..02abf6c2a0f 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7166,6 +7166,10 @@ api_key = "API Key" [tesouro.connector_auth.BodyKey] api_key="Client ID" key1="Client Secret" + [loonio] -[loonio.connector_auth.HeaderKey] -api_key = "API Key" +[loonio.connector_auth.BodyKey] +api_key = "Merchant ID" +api_secret = "Merchant Token" +[[loonio.bank_redirect]] +payment_method_type = "interac" diff --git a/crates/hyperswitch_connectors/src/connectors/loonio.rs b/crates/hyperswitch_connectors/src/connectors/loonio.rs index ad57fad435e..96ee717b862 100644 --- a/crates/hyperswitch_connectors/src/connectors/loonio.rs +++ b/crates/hyperswitch_connectors/src/connectors/loonio.rs @@ -1,13 +1,11 @@ pub mod transformers; -use std::sync::LazyLock; - use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -24,7 +22,8 @@ use hyperswitch_domain_models::{ RefundsData, SetupMandateRequestData, }, router_response_types::{ - ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, @@ -37,11 +36,12 @@ use hyperswitch_interfaces::{ ConnectorValidation, }, configs::Connectors, - errors, + consts as api_consts, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; +use lazy_static::lazy_static; use masking::{ExposeInterface, Mask}; use transformers as loonio; @@ -49,13 +49,13 @@ use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Loonio { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), } impl Loonio { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &FloatMajorUnitForConnector, } } } @@ -121,10 +121,16 @@ impl ConnectorCommon for Loonio { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = loonio::LoonioAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), - )]) + Ok(vec![ + ( + headers::MERCHANTID.to_string(), + auth.merchant_id.expose().into_masked(), + ), + ( + headers::MERCHANT_TOKEN.to_string(), + auth.merchant_token.expose().into_masked(), + ), + ]) } fn build_error_response( @@ -142,9 +148,12 @@ impl ConnectorCommon for Loonio { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response + .error_code + .clone() + .unwrap_or(api_consts::NO_ERROR_CODE.to_string()), + message: response.message.clone(), + reason: Some(response.message.clone()), attempt_status: None, connector_transaction_id: None, network_advice_code: None, @@ -205,9 +214,12 @@ 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!( + "{}api/v1/transactions/incoming/payment_form", + self.base_url(connectors), + )) } fn get_request_body( @@ -222,7 +234,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData )?; let connector_router_data = loonio::LoonioRouterData::from((amount, req)); - let connector_req = loonio::LoonioPaymentsRequest::try_from(&connector_router_data)?; + let connector_req = loonio::LoonioPaymentRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -291,10 +303,14 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Loo 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 base_url = self.base_url(connectors); + let connector_payment_id = req.connector_request_reference_id.clone(); + Ok(format!( + "{base_url}api/v1/transactions/{connector_payment_id}/details" + )) } fn build_request( @@ -318,9 +334,9 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Loo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: loonio::LoonioPaymentsResponse = res + let response: loonio::LoonioTransactionSyncResponse = res .response - .parse_struct("loonio PaymentsSyncResponse") + .parse_struct("loonio LoonioTransactionSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -594,21 +610,36 @@ impl webhooks::IncomingWebhook for Loonio { } } -static LOONIO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = - LazyLock::new(SupportedPaymentMethods::new); - -static LOONIO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Loonio", - description: "Loonio connector", - connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, - integration_status: enums::ConnectorIntegrationStatus::Sandbox, -}; - -static LOONIO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; +lazy_static! { + static ref LOONIO_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; + + let mut gigadat_supported_payment_methods = SupportedPaymentMethods::new(); + gigadat_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Interac, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + gigadat_supported_payment_methods + }; + static ref LOONIO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Loonio", + description: "Loonio is a payment processing platform that provides APIs for deposits and payouts via methods like Interac, PIX, EFT, and credit cards, with webhook support and transaction sync for real-time and manual status tracking.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, + }; + static ref LOONIO_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); +} impl ConnectorSpecifications for Loonio { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&LOONIO_CONNECTOR_INFO) + Some(&*LOONIO_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -616,6 +647,6 @@ impl ConnectorSpecifications for Loonio { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&LOONIO_SUPPORTED_WEBHOOK_FLOWS) + Some(&*LOONIO_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs index 0bdaf494cea..7efc1a895dc 100644 --- a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs @@ -1,28 +1,31 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use std::collections::HashMap; + +use common_enums::{enums, Currency}; +use common_utils::{id_type, pii::Email, request::Method, types::FloatMajorUnit}; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, + payment_method_data::{BankRedirectData, PaymentMethodData}, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; -use crate::types::{RefundsResponseRouterData, ResponseRouterData}; +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{self, PaymentsAuthorizeRequestData, RouterData as _}, +}; -//TODO: Fill the struct with respective fields pub struct LoonioRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: FloatMajorUnit, pub router_data: T, } -impl<T> From<(StringMinorUnit, T)> for LoonioRouterData<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<(FloatMajorUnit, T)> for LoonioRouterData<T> { + fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, @@ -30,80 +33,101 @@ impl<T> From<(StringMinorUnit, T)> for LoonioRouterData<T> { } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] -pub struct LoonioPaymentsRequest { - amount: StringMinorUnit, - card: LoonioCard, -} - -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct LoonioCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, -} - -impl TryFrom<&LoonioRouterData<&PaymentsAuthorizeRouterData>> for LoonioPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &LoonioRouterData<&PaymentsAuthorizeRouterData>, - ) -> Result<Self, Self::Error> { - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( - "Card payment method not implemented".to_string(), - ) - .into()), - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), - } - } -} - -//TODO: Fill the struct with respective fields // Auth Struct pub struct LoonioAuthType { - pub(super) api_key: Secret<String>, + pub(super) merchant_id: Secret<String>, + pub(super) merchant_token: Secret<String>, } impl TryFrom<&ConnectorAuthType> for LoonioAuthType { 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(), + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + merchant_id: api_key.to_owned(), + merchant_token: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum LoonioPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, + +#[derive(Debug, Serialize)] +pub struct LoonioPaymentRequest { + pub currency_code: Currency, + pub customer_profile: LoonioCustomerProfile, + pub amount: FloatMajorUnit, + pub customer_id: id_type::CustomerId, + pub transaction_id: String, + pub payment_method_type: InteracPaymentMethodType, + #[serde(skip_serializing_if = "Option::is_none")] + pub redirect_url: Option<LoonioRedirectUrl>, } -impl From<LoonioPaymentStatus> for common_enums::AttemptStatus { - fn from(item: LoonioPaymentStatus) -> Self { - match item { - LoonioPaymentStatus::Succeeded => Self::Charged, - LoonioPaymentStatus::Failed => Self::Failure, - LoonioPaymentStatus::Processing => Self::Authorizing, +#[derive(Debug, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum InteracPaymentMethodType { + InteracEtransfer, +} + +#[derive(Debug, Serialize)] +pub struct LoonioCustomerProfile { + pub first_name: Secret<String>, + pub last_name: Secret<String>, + pub email: Email, +} + +#[derive(Debug, Serialize)] +pub struct LoonioRedirectUrl { + pub success_url: String, + pub failed_url: String, +} + +impl TryFrom<&LoonioRouterData<&PaymentsAuthorizeRouterData>> for LoonioPaymentRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &LoonioRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => { + let transaction_id = item.router_data.connector_request_reference_id.clone(); + + let customer_profile = LoonioCustomerProfile { + first_name: item.router_data.get_billing_first_name()?, + last_name: item.router_data.get_billing_last_name()?, + email: item.router_data.get_billing_email()?, + }; + + let redirect_url = LoonioRedirectUrl { + success_url: item.router_data.request.get_router_return_url()?, + failed_url: item.router_data.request.get_router_return_url()?, + }; + + Ok(Self { + currency_code: item.router_data.request.currency, + customer_profile, + amount: item.amount, + customer_id: item.router_data.get_customer_id()?, + transaction_id, + payment_method_type: InteracPaymentMethodType::InteracEtransfer, + redirect_url: Some(redirect_url), + }) + } + PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Loonio"), + ))?, + + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Loonio"), + ) + .into()), } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct LoonioPaymentsResponse { - status: LoonioPaymentStatus, - id: String, + pub payment_form: String, } impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResponseData>> @@ -114,10 +138,14 @@ impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResp item: ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), + status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: Box::new(None), + resource_id: ResponseId::ConnectorTransactionId(item.response.payment_form.clone()), + redirection_data: Box::new(Some(RedirectForm::Form { + endpoint: item.response.payment_form, + method: Method::Get, + form_fields: HashMap::new(), + })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, @@ -130,12 +158,48 @@ impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResp } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum LoonioTransactionStatus { + Created, + Prepared, + Pending, + Settled, + Available, + Abandoned, + Rejected, + Failed, + Rollback, + Returned, + Nsf, +} + +impl From<LoonioTransactionStatus> for enums::AttemptStatus { + fn from(item: LoonioTransactionStatus) -> Self { + match item { + LoonioTransactionStatus::Created => Self::AuthenticationPending, + LoonioTransactionStatus::Prepared | LoonioTransactionStatus::Pending => Self::Pending, + LoonioTransactionStatus::Settled | LoonioTransactionStatus::Available => Self::Charged, + LoonioTransactionStatus::Abandoned + | LoonioTransactionStatus::Rejected + | LoonioTransactionStatus::Failed + | LoonioTransactionStatus::Returned + | LoonioTransactionStatus::Nsf => Self::Failure, + LoonioTransactionStatus::Rollback => Self::Voided, + } + } +} + +// Sync Response Structures +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LoonioTransactionSyncResponse { + pub transaction_id: String, + pub state: LoonioTransactionStatus, +} + #[derive(Default, Debug, Serialize)] pub struct LoonioRefundRequest { - pub amount: StringMinorUnit, + pub amount: FloatMajorUnit, } impl<F> TryFrom<&LoonioRouterData<&RefundsRouterData<F>>> for LoonioRefundRequest { @@ -147,6 +211,32 @@ impl<F> TryFrom<&LoonioRouterData<&RefundsRouterData<F>>> for LoonioRefundReques } } +impl<F, T> TryFrom<ResponseRouterData<F, LoonioTransactionSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, LoonioTransactionSyncResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.state), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.transaction_id.clone(), + ), + 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 + }) + } +} + // Type definition for Refund Response #[allow(dead_code)] @@ -207,13 +297,9 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouter } //TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Default, Debug, Serialize, Deserialize)] pub struct LoonioErrorResponse { - pub status_code: u16, - pub code: String, + pub status: u16, + pub error_code: Option<String>, pub message: String, - pub reason: Option<String>, - pub network_advice_code: Option<String>, - pub network_decline_code: Option<String>, - pub network_error_message: Option<String>, } diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index 4bfd7c90558..6cc3757a6a0 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -10,6 +10,8 @@ pub(crate) mod headers { pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key"; pub(crate) const MESSAGE_SIGNATURE: &str = "Message-Signature"; pub(crate) const MERCHANT_ID: &str = "Merchant-ID"; + pub(crate) const MERCHANTID: &str = "MerchantID"; + pub(crate) const MERCHANT_TOKEN: &str = "MerchantToken"; pub(crate) const REQUEST_ID: &str = "request-id"; pub(crate) const NONCE: &str = "nonce"; pub(crate) const TIMESTAMP: &str = "Timestamp"; 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 ea0abe93f84..0981d332d9c 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -2328,6 +2328,18 @@ fn get_bank_redirect_required_fields( vec![], ), ), + ( + Connector::Loonio, + fields( + vec![], + vec![ + RequiredField::BillingEmail, + RequiredField::BillingUserFirstName, + RequiredField::BillingUserLastName, + ], + vec![], + ), + ), ]), ), ]) diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index 8c9ef01017c..009c3612d8d 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -326,6 +326,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { )?; Ok(()) } + api_enums::Connector::Loonio => { + loonio::transformers::LoonioAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Mifinity => { mifinity::transformers::MifinityAuthType::try_from(self.auth_type)?; mifinity::transformers::MifinityConnectorMetadataObject::try_from( diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index 61dcf050479..3cf6ac51a72 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -309,6 +309,9 @@ impl ConnectorData { enums::Connector::Klarna => { Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new()))) } + enums::Connector::Loonio => { + Ok(ConnectorEnum::Old(Box::new(connector::Loonio::new()))) + } enums::Connector::Mollie => { // enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))), Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new()))) diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index 4537b42452f..5063abab7ab 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -227,6 +227,9 @@ impl FeatureMatrixConnectorData { enums::Connector::Klarna => { Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new()))) } + enums::Connector::Loonio => { + Ok(ConnectorEnum::Old(Box::new(connector::Loonio::new()))) + } enums::Connector::Mollie => { // enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))), Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new()))) diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index 7cc41f7bc79..ef7fa0e33df 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -93,6 +93,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { })? } api_enums::Connector::Klarna => Self::Klarna, + api_enums::Connector::Loonio => Self::Loonio, api_enums::Connector::Mifinity => Self::Mifinity, api_enums::Connector::Mollie => Self::Mollie, api_enums::Connector::Moneris => Self::Moneris, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index d01fe5e956e..536d23b8578 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -146,7 +146,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url = "https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" -loonio.base_url = "https://loonio.ca/" +loonio.base_url = "https://integration.loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" @@ -598,6 +598,9 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C [pm_filters.gigadat] interac = { currency = "CAD"} +[pm_filters.loonio] +interac = { currency = "CAD"} + [pm_filters.authorizedotnet] credit = { currency = "CAD,USD" } debit = { currency = "CAD,USD" }
2025-09-30T09:22:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implement interac Bank Redirect Payment Method - Payments - Psync ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? 1. Create MCA for Loonio ``` curl --location 'http://localhost:8080/account/merchant_1759170450/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: _' \ --data '{ "connector_type": "payment_processor", "business_country": "US", "business_label": "food", "connector_name": "loonio", "connector_account_details": { "auth_type": "BodyKey", "api_key": "", "key1": "_" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "interac", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ] }' ``` 2. Create a Interac Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: _' \ --data-raw '{ "amount": 1500, "currency": "CAD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "profile_id": "pro_C15ZRcjRQncWBGB2yuqm", "authentication_type": "three_ds", "payment_method": "bank_redirect", "payment_method_type": "interac", "payment_method_data": { "bank_redirect": { "interac": {} } }, "billing": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "SG", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } }' ``` Response ``` { "payment_id": "pay_pDnVks1Ok2xqEiTKSc3L", "merchant_id": "merchant_1759170450", "status": "failed", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "loonio", "client_secret": "pay_pDnVks1Ok2xqEiTKSc3L_secret_BOt98GDVh1YUREeBj49y", "created": "2025-09-30T09:06:47.208Z", "currency": "CAD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "BSC02005", "error_message": "Input field validation error: 'Missed required field 'transaction_id'.'.", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "interac", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "aaaa", "created_at": 1759223207, "expires": 1759226807, "secret": "epk_e7a1dc4e967a490781a35fe9d93dcf9a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_C15ZRcjRQncWBGB2yuqm", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1D5PxJd9ci3fD8Nj9hKL", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-30T09:21:47.208Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-30T09:06:48.505Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": { "network_advice_code": null } } ``` Complete payment using redirect_url It takes about 1 minute after the redirection for the status to change to succeeded. 3. Do force sync for status get ``` curl --location 'http://localhost:8080/payments/pay_pDnVks1Ok2xqEiTKSc3L?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: _' ``` Response ``` { "payment_id": "pay_hJ7WTdtJEsXcY53E7n0W", "merchant_id": "merchant_1759170450", "status": "succeeded", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1500, "connector": "loonio", "client_secret": "pay_hJ7WTdtJEsXcY53E7n0W_secret_OzW8vHtTkedDIW8yt9Sn", "created": "2025-09-30T08:59:59.957Z", "currency": "CAD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "interac", "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_hJ7WTdtJEsXcY53E7n0W_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_C15ZRcjRQncWBGB2yuqm", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1D5PxJd9ci3fD8Nj9hKL", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-30T09:14:59.957Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-30T09:00:55.783Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
efab34f0ef0bd032b049778f18f3cb688faa7fa7
juspay/hyperswitch
juspay__hyperswitch-9638
Bug: [FEATURE] add cypress tests for void payment in v2 ### Feature Description This implementation adds comprehensive V2 API testing for payment void/cancel operations across different payment states. The feature introduces a new Cypress test suite that validates three critical scenarios: successfully voiding a payment in the requires_capture state `after manual capture confirmation`, attempting to void a payment in the `requires_payment_method` state, and attempting to void a completed payment in the `succeeded` state. ### Possible Implementation A new test file `VoidPayments.cy.js` contains three separate test contexts that verify void behavior across payment states using both manual and automatic capture flows. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js index 3f09a83e804..7090f5a1406 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js @@ -5,7 +5,7 @@ import { getCustomExchange } from "./_Reusable"; const successfulNo3DSCardDetails = { card_number: "4111111111111111", card_exp_month: "08", - card_exp_year: "25", + card_exp_year: "28", card_holder_name: "joseph Doe", card_cvc: "999", }; @@ -13,7 +13,7 @@ const successfulNo3DSCardDetails = { const successfulThreeDSTestCardDetails = { card_number: "4111111111111111", card_exp_month: "10", - card_exp_year: "25", + card_exp_year: "28", card_holder_name: "morino", card_cvc: "999", }; @@ -52,6 +52,36 @@ const multiUseMandateData = { }, }; +const billingAddress = { + address: { + line1: "1467", + line2: "Harrison Street", + line3: "Harrison Street", + city: "San Fransico", + state: "California", + zip: "94122", + country: "US", + first_name: "joseph", + last_name: "Doe", + }, + email: "[email protected]", +}; + +const shippingAddress = { + address: { + line1: "1467", + line2: "Harrison Street", + line3: "Harrison Street", + city: "San Fransico", + state: "California", + zip: "94122", + country: "US", + first_name: "joseph", + last_name: "Doe", + }, + email: "[email protected]", +}; + export const payment_methods_enabled = [ { payment_method_type: "bank_debit", @@ -368,19 +398,7 @@ export const connectorDetails = { pix: {}, }, }, - billing: { - address: { - line1: "1467", - line2: "Harrison Street", - line3: "Harrison Street", - city: "San Fransico", - state: "California", - zip: "94122", - country: "BR", - first_name: "john", - last_name: "doe", - }, - }, + billing: billingAddress, currency: "BRL", }, }), @@ -409,19 +427,7 @@ export const connectorDetails = { }, }, }, - billing: { - address: { - line1: "1467", - line2: "Harrison Street", - line3: "Harrison Street", - city: "San Fransico", - state: "California", - zip: "94122", - country: "NL", - first_name: "john", - last_name: "doe", - }, - }, + billing: billingAddress, }, }), Giropay: getCustomExchange({ @@ -439,19 +445,7 @@ export const connectorDetails = { }, }, }, - billing: { - address: { - line1: "1467", - line2: "Harrison Street", - line3: "Harrison Street", - city: "San Fransico", - state: "California", - zip: "94122", - country: "DE", - first_name: "john", - last_name: "doe", - }, - }, + billing: billingAddress, }, }), Sofort: getCustomExchange({ @@ -466,19 +460,7 @@ export const connectorDetails = { }, }, }, - billing: { - address: { - line1: "1467", - line2: "Harrison Street", - line3: "Harrison Street", - city: "San Fransico", - state: "California", - zip: "94122", - country: "DE", - first_name: "john", - last_name: "doe", - }, - }, + billing: billingAddress, }, }), Eps: getCustomExchange({ @@ -492,19 +474,7 @@ export const connectorDetails = { }, }, }, - billing: { - address: { - line1: "1467", - line2: "Harrison Street", - line3: "Harrison Street", - city: "San Fransico", - state: "California", - zip: "94122", - country: "AT", - first_name: "john", - last_name: "doe", - }, - }, + billing: billingAddress, }, }), Przelewy24: getCustomExchange({ @@ -545,26 +515,19 @@ export const connectorDetails = { }, }, }, - billing: { - address: { - line1: "1467", - line2: "Harrison Street", - line3: "Harrison Street", - city: "San Fransico", - state: "California", - zip: "94122", - country: "PL", - first_name: "john", - last_name: "doe", - }, - }, + billing: billingAddress, }, }), }, card_pm: { PaymentIntent: getCustomExchange({ Request: { - currency: "USD", + amount_details: { + order_amount: 1001, + currency: "USD", + }, + billing: billingAddress, + shipping: shippingAddress, }, Response: { status: 200, @@ -573,6 +536,7 @@ export const connectorDetails = { }, }, }), + PaymentIntentOffSession: getCustomExchange({ Request: { currency: "USD", @@ -583,7 +547,7 @@ export const connectorDetails = { status: "requires_payment_method", }, }, - }), + }), "3DSManualCapture": getCustomExchange({ Request: { payment_method: "card", @@ -608,24 +572,36 @@ export const connectorDetails = { }), No3DSManualCapture: getCustomExchange({ Request: { - payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", + payment_method_type: "card", + payment_method_subtype: "credit", customer_acceptance: null, - setup_future_usage: "on_session", + + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, }, }), No3DSAutoCapture: getCustomExchange({ Request: { - payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", + payment_method_type: "card", + payment_method_subtype: "credit", customer_acceptance: null, - setup_future_usage: "on_session", + shipping: shippingAddress, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, }, }), Capture: getCustomExchange({ @@ -634,7 +610,6 @@ export const connectorDetails = { payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", customer_acceptance: null, }, }), @@ -659,8 +634,28 @@ export const connectorDetails = { error: { type: "invalid_request", message: - "You cannot cancel this payment because it has status succeeded", - code: "IR_16", + "This Payment could not be PaymentsCancel because it has a status of requires_payment_method. The expected state is requires_capture, partially_captured_and_capturable, partially_authorized_and_requires_capture", + code: "IR_14", + }, + }, + }, + }), + VoidAfterConfirm: getCustomExchange({ + Request: {}, + Response: { + status: 200, + body: { + status: "cancelled", + }, + }, + ResponseCustom: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be PaymentsCancel because it has a status of succeeded. The expected state is requires_capture, partially_captured_and_capturable, partially_authorized_and_requires_capture", + code: "IR_14", }, }, }, @@ -671,7 +666,6 @@ export const connectorDetails = { payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", customer_acceptance: null, }, ResponseCustom: { @@ -970,7 +964,7 @@ export const connectorDetails = { error: { error_type: "invalid_request", message: "Json deserialize error: invalid card number length", - code: "IR_06" + code: "IR_06", }, }, }, @@ -1077,8 +1071,9 @@ export const connectorDetails = { body: { error: { error_type: "invalid_request", - message: "Json deserialize error: unknown variant `United`, 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`, `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`", - code: "IR_06" + message: + "Json deserialize error: unknown variant `United`, 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`, `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`", + code: "IR_06", }, }, }, @@ -1105,8 +1100,9 @@ export const connectorDetails = { body: { error: { error_type: "invalid_request", - message: "Json deserialize error: unknown variant `auto`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled`", - code: "IR_06" + message: + "Json deserialize error: unknown variant `auto`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled`", + code: "IR_06", }, }, }, @@ -1132,8 +1128,9 @@ export const connectorDetails = { body: { error: { error_type: "invalid_request", - message: "Json deserialize error: unknown variant `this_supposed_to_be_a_card`, expected one of `card`, `card_redirect`, `pay_later`, `wallet`, `bank_redirect`, `bank_transfer`, `crypto`, `bank_debit`, `reward`, `real_time_payment`, `upi`, `voucher`, `gift_card`, `open_banking`, `mobile_payment`", - code: "IR_06" + message: + "Json deserialize error: unknown variant `this_supposed_to_be_a_card`, expected one of `card`, `card_redirect`, `pay_later`, `wallet`, `bank_redirect`, `bank_transfer`, `crypto`, `bank_debit`, `reward`, `real_time_payment`, `upi`, `voucher`, `gift_card`, `open_banking`, `mobile_payment`", + code: "IR_06", }, }, }, @@ -1202,7 +1199,8 @@ export const connectorDetails = { body: { error: { type: "invalid_request", - message: "A payment token or payment method data or ctp service details is required", + message: + "A payment token or payment method data or ctp service details is required", code: "IR_06", }, }, diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js index 569b557b690..c21a3c6a650 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js @@ -5,7 +5,7 @@ const connectorDetails = { }; export default function getConnectorDetails(connectorId) { - let x = mergeDetails(connectorId); + const x = mergeDetails(connectorId); return x; } @@ -61,9 +61,9 @@ export const should_continue_further = (res_data) => { } if ( - res_data.body.error !== undefined || - res_data.body.error_code !== undefined || - res_data.body.error_message !== undefined + res_data.Response.body.error !== undefined || + res_data.Response.body.error_code !== undefined || + res_data.Response.body.error_message !== undefined ) { return false; } else { @@ -89,9 +89,12 @@ export function defaultErrorHandler(response, response_data) { if (typeof response.body.error === "object") { for (const key in response_data.body.error) { // Check if the error message is a Json deserialize error - let apiResponseContent = response.body.error[key]; - let expectedContent = response_data.body.error[key]; - if (typeof apiResponseContent === "string" && apiResponseContent.includes("Json deserialize error")) { + const apiResponseContent = response.body.error[key]; + const expectedContent = response_data.body.error[key]; + if ( + typeof apiResponseContent === "string" && + apiResponseContent.includes("Json deserialize error") + ) { expect(apiResponseContent).to.include(expectedContent); } else { expect(apiResponseContent).to.equal(expectedContent); diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/_Reusable.js b/cypress-tests-v2/cypress/e2e/configs/Payment/_Reusable.js index 353d96260b5..d24e96cfdf8 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/_Reusable.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/_Reusable.js @@ -46,9 +46,7 @@ with `getCustomExchange`, if 501 response is expected, there is no need to pass // Const to get default PaymentExchange object const getDefaultExchange = () => ({ - Request: { - currency: "EUR", - }, + Request: {}, Response: { status: 501, body: { @@ -62,9 +60,7 @@ const getDefaultExchange = () => ({ }); const getUnsupportedExchange = () => ({ - Request: { - currency: "EUR", - }, + Request: {}, Response: { status: 400, body: { diff --git a/cypress-tests-v2/cypress/e2e/spec/Payment/0001-[No3DS]Payments.cy.js b/cypress-tests-v2/cypress/e2e/spec/Payment/0001-[No3DS]Payments.cy.js index 21766617c09..06afc506bcb 100644 --- a/cypress-tests-v2/cypress/e2e/spec/Payment/0001-[No3DS]Payments.cy.js +++ b/cypress-tests-v2/cypress/e2e/spec/Payment/0001-[No3DS]Payments.cy.js @@ -40,12 +40,11 @@ describe("[Payment] [No 3DS] [Payment Method: Card]", () => { let req_data = data["Request"]; let res_data = data["Response"]; cy.paymentIntentCreateCall( + globalState, fixtures.createPaymentBody, - req_data, res_data, "no_three_ds", - "automatic", - globalState + "automatic" ); }); @@ -59,7 +58,7 @@ describe("[Payment] [No 3DS] [Payment Method: Card]", () => { ]; let req_data = data["Request"]; let res_data = data["Response"]; - cy.paymentIntentConfirmCall( + cy.paymentConfirmCall( fixtures.confirmBody, req_data, res_data, @@ -97,12 +96,11 @@ describe("[Payment] [No 3DS] [Payment Method: Card]", () => { let req_data = data["Request"]; let res_data = data["Response"]; cy.paymentIntentCreateCall( + globalState, fixtures.createPaymentBody, - req_data, res_data, "no_three_ds", - "automatic", - globalState + "automatic" ); }); @@ -116,7 +114,7 @@ describe("[Payment] [No 3DS] [Payment Method: Card]", () => { ]; let req_data = data["Request"]; let res_data = data["Response"]; - cy.paymentIntentConfirmCall( + cy.paymentConfirmCall( fixtures.confirmBody, req_data, res_data, diff --git a/cypress-tests-v2/cypress/e2e/spec/Payment/0003-VoidPayments.cy.js b/cypress-tests-v2/cypress/e2e/spec/Payment/0003-VoidPayments.cy.js new file mode 100644 index 00000000000..76fb97d9644 --- /dev/null +++ b/cypress-tests-v2/cypress/e2e/spec/Payment/0003-VoidPayments.cy.js @@ -0,0 +1,207 @@ +/* +V2 Void/Cancel Payment Tests +Test scenarios: +1. Void payment in requires_capture state +2. Void payment in requires_payment_method state +3. Void payment in succeeded state (should fail) +*/ + +import * as fixtures from "../../../fixtures/imports"; +import State from "../../../utils/State"; +import getConnectorDetails, { + should_continue_further, +} from "../../configs/Payment/Utils"; + +let globalState; + +describe("[Payment] [Void/Cancel] [Payment Method: Card]", () => { + context("[Payment] [Void] [Requires Capture State]", () => { + let should_continue = true; + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it("Create payment intent", () => { + const data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + const req_data = data["Request"]; + const res_data = data["Response"]; + + cy.paymentIntentCreateCall( + globalState, + req_data, + res_data, + "no_three_ds", + "manual" + ); + + if (should_continue) should_continue = should_continue_further(data); + }); + + it("Confirm payment intent", () => { + const data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSManualCapture"]; + const req_data = data["Request"]; + + cy.paymentConfirmCall(globalState, req_data, data); + + if (should_continue) should_continue = should_continue_further(data); + }); + + it("Void payment intent", () => { + const data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["VoidAfterConfirm"]; + + cy.paymentVoidCall(globalState, fixtures.void_payment_body, data); + + if (should_continue) should_continue = should_continue_further(data); + }); + }); + + context( + "[Payment] [Void] [Requires Payment Method State - Should Fail]", + () => { + let should_continue = true; + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it("Create payment intent", () => { + const data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + const req_data = data["Request"]; + const res_data = data["Response"]; + + cy.paymentIntentCreateCall( + globalState, + req_data, + res_data, + "no_three_ds", + "manual" + ); + + if (should_continue) should_continue = should_continue_further(data); + }); + + it("Void payment intent - should fail", () => { + const data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["Void"]; + + // Use the ResponseCustom which contains the error response + const void_data = { + ...data, + Response: data.ResponseCustom, + }; + + cy.paymentVoidCall( + globalState, + fixtures.void_payment_body, + void_data + ); + + if (should_continue) should_continue = should_continue_further(data); + }); + } + ); + + context("[Payment] [Void] [Succeeded State - Should Fail]", () => { + let should_continue = true; + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it("Create payment intent", () => { + const data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntent"]; + + const req_data = data["Request"]; + const res_data = data["Response"]; + + cy.paymentIntentCreateCall( + globalState, + req_data, + res_data, + "no_three_ds", + "automatic" + ); + + if (should_continue) should_continue = should_continue_further(data); + }); + + it("Confirm payment intent", () => { + const data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["No3DSAutoCapture"]; + const req_data = data["Request"]; + + cy.paymentConfirmCall(globalState, req_data, data); + + if (should_continue) should_continue = should_continue_further(data); + }); + + it("Void payment intent - should fail", () => { + const data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["VoidAfterConfirm"]; + + // Use the ResponseCustom which contains the error response + const void_data = { + ...data, + Response: data.ResponseCustom, + }; + + cy.paymentVoidCall( + globalState, + fixtures.void_payment_body, + void_data + ); + + if (should_continue) should_continue = should_continue_further(data); + }); + }); +}); diff --git a/cypress-tests-v2/cypress/fixtures/imports.js b/cypress-tests-v2/cypress/fixtures/imports.js index 30f0dfb50c2..4b3f8c4b89e 100644 --- a/cypress-tests-v2/cypress/fixtures/imports.js +++ b/cypress-tests-v2/cypress/fixtures/imports.js @@ -4,6 +4,7 @@ import merchant_account_body from "./merchant_account.json"; import merchant_connector_account_body from "./merchant_connector_account.json"; import organization_body from "./organization.json"; import routing_body from "./routing.json"; +import void_payment_body from "./void_payment.json"; export { api_key_body, @@ -12,4 +13,5 @@ export { merchant_connector_account_body, organization_body, routing_body, + void_payment_body, }; diff --git a/cypress-tests-v2/cypress/fixtures/void_payment.json b/cypress-tests-v2/cypress/fixtures/void_payment.json new file mode 100644 index 00000000000..471d90d6c48 --- /dev/null +++ b/cypress-tests-v2/cypress/fixtures/void_payment.json @@ -0,0 +1,3 @@ +{ + "cancellation_reason": "requested_by_customer" +} diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index e77a0f65143..7afa35152c6 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -27,7 +27,10 @@ // cy.task can only be used in support files (spec files or commands file) import { nanoid } from "nanoid"; -import { getValueByKey } from "../e2e/configs/Payment/Utils.js"; +import { + defaultErrorHandler, + getValueByKey, +} from "../e2e/configs/Payment/Utils.js"; import { isoTimeTomorrow, validateEnv } from "../utils/RequestBodyUtils.js"; function logRequestId(xRequestId) { @@ -55,7 +58,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, }, body: organizationCreateBody, failOnStatusCode: false, @@ -91,7 +94,7 @@ Cypress.Commands.add("organizationRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, }, failOnStatusCode: false, }).then((response) => { @@ -135,7 +138,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, }, body: organizationUpdateBody, failOnStatusCode: false, @@ -185,7 +188,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, "X-Organization-Id": organization_id, }, body: merchantAccountCreateBody, @@ -230,7 +233,7 @@ Cypress.Commands.add("merchantAccountRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, }, failOnStatusCode: false, }).then((response) => { @@ -274,7 +277,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, }, body: merchantAccountUpdateBody, failOnStatusCode: false, @@ -324,7 +327,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, "x-merchant-id": merchant_id, ...customHeaders, }, @@ -369,7 +372,7 @@ Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -411,7 +414,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, ...customHeaders, }, body: businessProfileUpdateBody, @@ -503,7 +506,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, ...customHeaders, }, body: mcaCreateBody, @@ -551,7 +554,7 @@ Cypress.Commands.add("mcaRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -611,7 +614,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, ...customHeaders, }, body: mcaUpdateBody, @@ -671,7 +674,7 @@ Cypress.Commands.add("apiKeyCreateCall", (apiKeyCreateBody, globalState) => { url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, ...customHeaders, }, body: apiKeyCreateBody, @@ -718,7 +721,7 @@ Cypress.Commands.add("apiKeyRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -768,7 +771,7 @@ Cypress.Commands.add("apiKeyUpdateCall", (apiKeyUpdateBody, globalState) => { url: url, headers: { "Content-Type": "application/json", - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, ...customHeaders, }, body: apiKeyUpdateBody, @@ -1176,7 +1179,7 @@ Cypress.Commands.add("merchantAccountsListCall", (globalState) => { method: "GET", url: url, headers: { - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, "Content-Type": "application/json", }, failOnStatusCode: false, @@ -1218,7 +1221,7 @@ Cypress.Commands.add("businessProfilesListCall", (globalState) => { method: "GET", url: url, headers: { - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, }, @@ -1261,7 +1264,7 @@ Cypress.Commands.add("mcaListCall", (globalState, service_type) => { method: "GET", url: url, headers: { - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, }, @@ -1323,7 +1326,7 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => { method: "GET", url: url, headers: { - "Authorization": `admin-api-key=${api_key}`, + Authorization: `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, }, @@ -1354,13 +1357,64 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => { // Payment API calls // Update the below commands while following the conventions // Below is an example of how the payment intent create call should look like (update the below command as per the need) + +Cypress.Commands.add( + "paymentVoidCall", + (globalState, voidRequestBody, data) => { + const { Request: reqData = {}, Response: resData } = data || {}; + + // Define the necessary variables and constants at the top + const api_key = globalState.get("apiKey"); + const base_url = globalState.get("baseUrl"); + const profile_id = globalState.get("profileId"); + const payment_id = globalState.get("paymentID"); + const url = `${base_url}/v2/payments/${payment_id}/cancel`; + + // Apply connector-specific request data (including cancellation_reason) + for (const key in reqData) { + voidRequestBody[key] = reqData[key]; + } + + // Pass Custom Headers + const customHeaders = { + "x-profile-id": profile_id, + }; + + cy.request({ + method: "POST", + url: url, + headers: { + Authorization: `api-key=${api_key}`, + "Content-Type": "application/json", + ...customHeaders, + }, + body: voidRequestBody, + failOnStatusCode: false, + }).then((response) => { + // Logging x-request-id is mandatory + logRequestId(response.headers["x-request-id"]); + + cy.wrap(response).then(() => { + expect(response.headers["content-type"]).to.include("application/json"); + if (response.status === 200) { + for (const key in resData.body) { + expect(resData.body[key]).to.equal(response.body[key]); + } + } else { + defaultErrorHandler(response, resData); + } + }); + }); + } +); Cypress.Commands.add( "paymentIntentCreateCall", ( globalState, paymentRequestBody, - paymentResponseBody - /* Add more variables based on the need*/ + paymentResponseBody, + authentication_type, + capture_method ) => { // Define the necessary variables and constants at the top // Also construct the URL here @@ -1369,8 +1423,9 @@ Cypress.Commands.add( const profile_id = globalState.get("profileId"); const url = `${base_url}/v2/payments/create-intent`; - // Update request body if needed - paymentRequestBody = {}; + // Set capture_method and authentication_type as parameters (like V1) + paymentRequestBody.authentication_type = authentication_type; + paymentRequestBody.capture_method = capture_method; // Pass Custom Headers const customHeaders = { @@ -1381,7 +1436,7 @@ Cypress.Commands.add( method: "POST", url: url, headers: { - "api-key": api_key, + Authorization: `api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, }, @@ -1391,28 +1446,113 @@ Cypress.Commands.add( // Logging x-request-id is mandatory logRequestId(response.headers["x-request-id"]); - if (response.status === 200) { - // Update the assertions based on the need - expect(response.body).to.deep.equal(paymentResponseBody); - } else if (response.status === 400) { - // Add 4xx validations here - expect(response.body).to.deep.equal(paymentResponseBody); - } else if (response.status === 500) { - // Add 5xx validations here - expect(response.body).to.deep.equal(paymentResponseBody); - } else { - // If status code is other than the ones mentioned above, default should be thrown - throw new Error( - `Payment intent create call failed with status ${response.status} and message: "${response.body.error.message}"` - ); - } + cy.wrap(response).then(() => { + expect(response.headers["content-type"]).to.include("application/json"); + if (response.status === 200) { + // Validate the payment create response - V2 uses different ID format + expect(response.body).to.have.property("id").and.to.be.a("string").and + .not.be.empty; + expect(response.body).to.have.property("status"); + + // Store the payment ID for future use + globalState.set("paymentID", response.body.id); + + // Log payment creation success + cy.task( + "cli_log", + `Payment created with ID: ${response.body.id}, Status: ${response.body.status}` + ); + + if (paymentResponseBody && paymentResponseBody.body) { + for (const key in paymentResponseBody.body) { + if (paymentResponseBody.body[key] !== null) { + expect(response.body[key]).to.equal( + paymentResponseBody.body[key] + ); + } + } + } + } else { + defaultErrorHandler(response, paymentResponseBody); + } + }); }); } ); -Cypress.Commands.add("paymentIntentConfirmCall", (globalState) => {}); -Cypress.Commands.add("paymentIntentRetrieveCall", (globalState) => {}); +Cypress.Commands.add( + "paymentConfirmCall", + (globalState, paymentConfirmRequestBody, data) => { + const { Request: reqData = {}, Response: resData } = data || {}; -// templates for future use -Cypress.Commands.add("", () => { - cy.request({}).then((response) => {}); -}); + // Define the necessary variables and constants at the top + const api_key = globalState.get("apiKey"); + const base_url = globalState.get("baseUrl"); + const profile_id = globalState.get("profileId"); + const payment_id = globalState.get("paymentID"); + const url = `${base_url}/v2/payments/${payment_id}/confirm-intent`; + + // Apply connector-specific request data + for (const key in reqData) { + paymentConfirmRequestBody[key] = reqData[key]; + } + + // Pass Custom Headers + const customHeaders = { + "x-profile-id": profile_id, + }; + + cy.request({ + method: "POST", + url: url, + headers: { + Authorization: `api-key=${api_key}`, + "Content-Type": "application/json", + ...customHeaders, + }, + body: paymentConfirmRequestBody, + failOnStatusCode: false, + }).then((response) => { + // Logging x-request-id is mandatory + logRequestId(response.headers["x-request-id"]); + + cy.wrap(response).then(() => { + expect(response.headers["content-type"]).to.include("application/json"); + if (response.status === 200) { + // Validate the payment confirm response + expect(response.body).to.have.property("id").and.to.be.a("string").and + .not.be.empty; + expect(response.body).to.have.property("status"); + + globalState.set("paymentID", response.body.id); + + // Validate response body against expected data + if (resData && resData.body) { + for (const key in resData.body) { + // Skip validation if expected value is null or undefined + if (resData.body[key] == null) { + continue; + } + // Only validate if the field exists in the response and has a non-null value + if ( + response.body.hasOwnProperty(key) && + response.body[key] != null + ) { + // Use deep equal for object comparison, regular equal for primitives + if ( + typeof resData.body[key] === "object" && + typeof response.body[key] === "object" + ) { + expect(response.body[key]).to.deep.equal(resData.body[key]); + } else { + expect(response.body[key]).to.equal(resData.body[key]); + } + } + } + } + } else { + defaultErrorHandler(response, resData); + } + }); + }); + } +);
2025-10-01T11:34:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This implementation adds comprehensive V2 API testing for payment void/cancel operations across different payment states. The feature introduces a new Cypress test suite that validates three critical scenarios: successfully voiding a payment in the requires_capture state `after manual capture confirmation`, attempting to void a payment in the `requires_payment_method` state, and attempting to void a completed payment in the `succeeded` state. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes #9638 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1728" height="1117" alt="image" src="https://github.com/user-attachments/assets/8c5d6b12-3ccb-467e-a38f-13e1c9350d3c" /> <img width="1728" height="1061" alt="image" src="https://github.com/user-attachments/assets/4626ee99-8a0b-44c3-a2ed-f7f76c186209" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
90c7cffcd5b555bb5f18e320f723fce265781e9e
juspay/hyperswitch
juspay__hyperswitch-9610
Bug: [FIX]: [PAYOUTS] add should_continue flag for propagating error for each call Paypal requires creation of access token before payment/payouts in its flow. In Access token flow, we do get error response ``` PaypalAccessTokenErrorResponse { error: \"invalid_client\", error_description: \"Client Authentication failed\" } ``` The error response gets updated on router data but we don’t do a early return based on this condition thus this gets overwritten by payout’s response. In this case, even if access token is not generated (null), it still goes to payout create flow and fails at connector service with missing value (5xx) (edited)
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 86d9e2c1e64..437c6c50096 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -1656,29 +1656,35 @@ pub async fn create_payout( ) .await?; - // 3. Fetch connector integration details - let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< - api::PoCreate, - types::PayoutsData, - types::PayoutsResponseData, - > = connector_data.connector.get_connector_integration(); - - // 4. Execute pretasks - complete_payout_quote_steps_if_required(state, connector_data, &mut router_data).await?; + // 3. Execute pretasks + if helpers::should_continue_payout(&router_data) { + complete_payout_quote_steps_if_required(state, connector_data, &mut router_data).await?; + }; - // 5. Call connector service - let router_data_resp = services::execute_connector_processing_step( - state, - connector_integration, - &router_data, - payments::CallConnectorAction::Trigger, - None, - None, - ) - .await - .to_payout_failed_response()?; + // 4. Call connector service + let router_data_resp = match helpers::should_continue_payout(&router_data) { + true => { + let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< + api::PoCreate, + types::PayoutsData, + types::PayoutsResponseData, + > = connector_data.connector.get_connector_integration(); + + services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + None, + ) + .await + .to_payout_failed_response()? + } + false => router_data, + }; - // 6. Process data returned by the connector + // 5. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { @@ -1880,26 +1886,30 @@ pub async fn create_payout_retrieve( ) .await?; - // 3. Fetch connector integration details - let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< - api::PoSync, - types::PayoutsData, - types::PayoutsResponseData, - > = connector_data.connector.get_connector_integration(); - - // 4. Call connector service - let router_data_resp = services::execute_connector_processing_step( - state, - connector_integration, - &router_data, - payments::CallConnectorAction::Trigger, - None, - None, - ) - .await - .to_payout_failed_response()?; + // 3. Call connector service + let router_data_resp = match helpers::should_continue_payout(&router_data) { + true => { + let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< + api::PoSync, + types::PayoutsData, + types::PayoutsResponseData, + > = connector_data.connector.get_connector_integration(); + + services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + None, + ) + .await + .to_payout_failed_response()? + } + false => router_data, + }; - // 5. Process data returned by the connector + // 4. Process data returned by the connector update_retrieve_payout_tracker(state, merchant_context, payout_data, &router_data_resp).await?; Ok(()) @@ -2383,26 +2393,30 @@ pub async fn fulfill_payout( ) .await?; - // 3. Fetch connector integration details - let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< - api::PoFulfill, - types::PayoutsData, - types::PayoutsResponseData, - > = connector_data.connector.get_connector_integration(); - - // 4. Call connector service - let router_data_resp = services::execute_connector_processing_step( - state, - connector_integration, - &router_data, - payments::CallConnectorAction::Trigger, - None, - None, - ) - .await - .to_payout_failed_response()?; + // 3. Call connector service + let router_data_resp = match helpers::should_continue_payout(&router_data) { + true => { + let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< + api::PoFulfill, + types::PayoutsData, + types::PayoutsResponseData, + > = connector_data.connector.get_connector_integration(); + + services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + None, + ) + .await + .to_payout_failed_response()? + } + false => router_data, + }; - // 5. Process data returned by the connector + // 4. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 00bcc7a26f6..a1d6b4747d8 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -38,6 +38,7 @@ use crate::{ routes::{metrics, SessionState}, services, types::{ + self as router_types, api::{self, enums as api_enums}, domain::{self, types::AsyncLift}, storage, @@ -1637,3 +1638,9 @@ pub async fn resolve_billing_address_for_payout( (None, None, None) => Ok((None, None)), } } + +pub fn should_continue_payout<F: Clone + 'static>( + router_data: &router_types::PayoutsRouterData<F>, +) -> bool { + router_data.response.is_ok() +}
2025-09-24T04:52:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Paypal requires creation of access token before payment/payouts in its flow. In Access token flow, we do get error response ``` PaypalAccessTokenErrorResponse { error: \"invalid_client\", error_description: \"Client Authentication failed\" } ``` The error response gets updated on router data but we don’t do a early return based on this condition thus this gets overwritten by payout’s response. In this case, even if access token is not generated (null), it still goes to payout create flow and fails at connector service with missing value (5xx) (edited) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested through Postman: - Create an MCA (Paypal payout) with `incorrect credentials` - Create a Paypal Payout ``` curl --location '{{baseUrl}}/payouts/create' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data-raw '{ "amount": 1, "currency": "EUR", "customer_id": "payout_customer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payout request", "payout_type": "wallet", "payout_method_data": { "wallet": { "paypal": { "email": "[email protected]" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "NY", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "entity_type": "NaturalPerson", "recurring": false, "metadata": { "ref": "123" }, "confirm": true, "auto_fulfill": true }' ``` It should give out an 2xx with failed response: ``` { "payout_id": "payout_OCfkeZ0BRP1TvVBCbqJS", "merchant_id": "merchant_1758740236", "merchant_order_reference_id": null, "amount": 1, "currency": "EUR", "connector": "paypal", "payout_type": "wallet", "payout_method_data": { "wallet": { "email": "sk******@juspay.in", "telephone_number": null, "paypal_id": null } }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "NY", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "auto_fulfill": true, "customer_id": "payout_customer", "customer": { "id": "payout_customer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "client_secret": "payout_payout_OCfkeZ0BRP1TvVBCbqJS_secret_odzX4yMLCWleZmuNb9sh", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "NaturalPerson", "recurring": false, "metadata": { "ref": "123" }, "merchant_connector_id": "mca_jWza4o9JclyqVqh3maid", "status": "failed", "error_message": "invalid_client", "error_code": "invalid_client", "profile_id": "pro_yOBs0ZV2FcCS8k3ZEbCM", "created": "2025-09-24T18:58:12.868Z", "connector_transaction_id": null, "priority": null, "payout_link": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payout_method_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
85da1b2bc80d4befd392cf7a9d2060d1e2f5cbe9
juspay/hyperswitch
juspay__hyperswitch-9612
Bug: Nexixpay MIT fix Nexixpay MITs are failing when created a CIT for already existing customer for which normal payment was made.
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 2cf30de8edf..e1a5f783ffd 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -39,7 +39,7 @@ use crate::{ get_unimplemented_payment_method_error_message, to_connector_meta, to_connector_meta_from_secret, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, - PaymentsSetupMandateRequestData, RouterData as _, + PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RouterData as _, }, }; @@ -1081,6 +1081,19 @@ impl<F> }, psync_flow: NexixpayPaymentIntent::Authorize })); + let mandate_reference = if item.data.request.is_mandate_payment() { + 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, + })) + } else { + Box::new(None) + }; let status = AttemptStatus::from(response_body.operation.operation_result.clone()); match status { AttemptStatus::Failure => { @@ -1100,15 +1113,7 @@ impl<F> 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, - })), + mandate_reference, connector_metadata, network_txn_id: None, connector_response_reference_id: Some( @@ -1257,6 +1262,16 @@ impl<F> meta_data, is_auto_capture, })?); + let mandate_reference = if item.data.request.is_mandate_payment() { + 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, + })) + } else { + Box::new(None) + }; let status = if item.data.request.amount == 0 && item.response.operation.operation_result == NexixpayPaymentStatus::Authorized { @@ -1282,15 +1297,7 @@ impl<F> 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, - })), + mandate_reference, connector_metadata, network_txn_id: None, connector_response_reference_id: Some(item.response.operation.order_id), @@ -1466,6 +1473,16 @@ impl<F> >, ) -> Result<Self, Self::Error> { let status = AttemptStatus::from(item.response.operation_result.clone()); + let mandate_reference = if item.data.request.is_mandate_payment() { + 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, + })) + } else { + Box::new(None) + }; match status { AttemptStatus::Failure => { let response = Err(get_error_response( @@ -1482,15 +1499,7 @@ impl<F> 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, - })), + mandate_reference, connector_metadata: item.data.request.connector_meta.clone(), network_txn_id: None, connector_response_reference_id: Some(item.response.order_id.clone()),
2025-09-29T13:41:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Stop sending back mandate reference from connector response in case of non-CIT payments to avoid making connector mandate details entry in payment_methods table. This should only be done in case of CIT payments to store correct PSP token which will be used in MIT payments. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Step 1:** Do an on_session payment with certain customer and card details with customer acceptance. **Step 2:** Use same customer and card details and do an off_session payment (CIT creation). **Step 3:** Do a MIT payment. In this case MIT should not fail. <details> <summary>1. Do an on_session payment with certain customer and card details with customer acceptance</summary> ### cURL Request ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_n5vnntb0V5gRjNMdwTnPXweumExJV6vYon3lVNzW2BoA3F4S4V0PXDHK3lW7gWHh' \ --data-raw '{ "amount": 545, "currency": "EUR", "profile_id": "pro_QEwjCvFhpcLC2azRNZEf", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111 1111 1111 1111", "card_exp_month": "03", "card_exp_year": "30", "card_cvc": "737" } }, "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "setup_future_usage": "on_session", "customer": { "id": "customerssh", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "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", "country": "BR", "zip": "94122", "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": "BR", "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 }' ``` ### Response ```json { "payment_id": "pay_UJeFlJM9WMIeBvNEVd0O", "merchant_id": "merchant_1759144749", "status": "requires_customer_action", "amount": 545, "net_amount": 545, "shipping_cost": null, "amount_capturable": 545, "amount_received": null, "connector": "nexixpay", "client_secret": "pay_UJeFlJM9WMIeBvNEVd0O_secret_xWU3ewN9pUcuqFAMbm9Q", "created": "2025-09-30T09:53:19.420Z", "currency": "EUR", "customer_id": "customerssh", "customer": { "id": "customerssh", "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": "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": "30", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_EJFI1EooKy0qnkpjqk05", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_UJeFlJM9WMIeBvNEVd0O/merchant_1759144749/pay_UJeFlJM9WMIeBvNEVd0O_1" } } ``` Open and complete 3DS payment ### cURL (Payments Retrieve) ```bash curl --location 'http://localhost:8080/payments/pay_UJeFlJM9WMIeBvNEVd0O?force_sync=true&expand_captures=true&expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_n5vnntb0V5gRjNMdwTnPXweumExJV6vYon3lVNzW2BoA3F4S4V0PXDHK3lW7gWHh' ``` ### Response ```json { "payment_id": "pay_UJeFlJM9WMIeBvNEVd0O", "merchant_id": "merchant_1759144749", "status": "succeeded", "amount": 545, "net_amount": 545, "shipping_cost": null, "amount_capturable": 0, "amount_received": 545, "connector": "nexixpay", "client_secret": "pay_UJeFlJM9WMIeBvNEVd0O_secret_xWU3ewN9pUcuqFAMbm9Q", "created": "2025-09-30T09:53:19.420Z", "currency": "EUR", "customer_id": "customerssh", "customer": { "id": "customerssh", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_UJeFlJM9WMIeBvNEVd0O_1", "status": "charged", "amount": 545, "order_tax_amount": null, "currency": "EUR", "connector": "nexixpay", "error_message": null, "payment_method": "card", "connector_transaction_id": "Sk6LXorxafrWXJ4eyr", "capture_method": "automatic", "authentication_type": "three_ds", "created_at": "2025-09-30T09:53:19.420Z", "modified_at": "2025-09-30T09:57:43.778Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": "token_EJFI1EooKy0qnkpjqk05", "connector_metadata": { "psyncFlow": "Authorize", "cancelOperationId": null, "threeDSAuthResult": { "authenticationValue": "AJkBAiFGcAAAAAIhl4JzdQAAAAA=" }, "captureOperationId": "622504582202352739", "threeDSAuthResponse": "notneeded", "authorizationOperationId": "622504582202352739" }, "payment_experience": null, "payment_method_type": "credit", "reference_id": "Sk6LXorxafrWXJ4eyr", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "payment_method_id": "pm_QfbMOx8yXdpxfniJwh53" } ``` ### Database Query Do a DB query: ```sql SELECT * FROM payment_methods WHERE payment_method_id = 'pm_QfbMOx8yXdpxfniJwh53'; ``` **Expected Result:** `connector_mandate_details` should be null in this case. </details> <details> <summary>2. Use same customer and card details and do an off_session payment (CIT creation)</summary> ### cURL Request ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_n5vnntb0V5gRjNMdwTnPXweumExJV6vYon3lVNzW2BoA3F4S4V0PXDHK3lW7gWHh' \ --data-raw '{ "amount": 545, "currency": "EUR", "profile_id": "pro_QEwjCvFhpcLC2azRNZEf", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111 1111 1111 1111", "card_exp_month": "03", "card_exp_year": "30", "card_cvc": "737" } }, "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "setup_future_usage": "off_session", "customer": { "id": "customerssh", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "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", "country": "BR", "zip": "94122", "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": "BR", "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 }' ``` ### Response (Payments - Retrieve) ```json { "payment_id": "pay_13wFZiDN7ZUJtSx87U8Z", "merchant_id": "merchant_1759144749", "status": "succeeded", "amount": 545, "net_amount": 545, "shipping_cost": null, "amount_capturable": 0, "amount_received": 545, "connector": "nexixpay", "client_secret": "pay_13wFZiDN7ZUJtSx87U8Z_secret_JyWk0LkWu6tOa7mnLXUG", "created": "2025-09-30T10:01:01.076Z", "currency": "EUR", "customer_id": "customerssh", "customer": { "id": "customerssh", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_13wFZiDN7ZUJtSx87U8Z_1", "status": "charged", "amount": 545, "order_tax_amount": null, "currency": "EUR", "connector": "nexixpay", "error_message": null, "payment_method": "card", "connector_transaction_id": "9dHJb42gtTkDntQ7xY", "capture_method": "automatic", "authentication_type": "three_ds", "created_at": "2025-09-30T10:01:01.077Z", "modified_at": "2025-09-30T10:01:29.144Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": "token_Ro6vBjhJSWBxtCDUjDTw", "connector_metadata": { "psyncFlow": "Authorize", "cancelOperationId": null, "threeDSAuthResult": { "authenticationValue": "AAkBBgmCIQAAAAIhl4JzdQAAAAA=" }, "captureOperationId": "501653294486252739", "threeDSAuthResponse": "notneeded", "authorizationOperationId": "501653294486252739" }, "payment_experience": null, "payment_method_type": "credit", "reference_id": "9dHJb42gtTkDntQ7xY", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "payment_method_id": "pm_ZNF2NslDvKAFvlUG5HwO" } ``` </details> <details> <summary>3. Do a MIT payment</summary> ### cURL Request ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_n5vnntb0V5gRjNMdwTnPXweumExJV6vYon3lVNzW2BoA3F4S4V0PXDHK3lW7gWHh' \ --data '{ "amount": 3545, "currency": "EUR", "confirm": true, "customer_id": "customerssh", "recurring_details": { "type": "payment_method_id", "data": "pm_ZNF2NslDvKAFvlUG5HwO" }, "off_session": true }' ``` ### Response ```json { "payment_id": "pay_ZmNL5MZQmRC6YpbLcXWk", "merchant_id": "merchant_1759144749", "status": "succeeded", "amount": 3545, "net_amount": 3545, "shipping_cost": null, "amount_capturable": 0, "amount_received": 3545, "connector": "nexixpay", "client_secret": "pay_ZmNL5MZQmRC6YpbLcXWk_secret_24nJQzb7Fls1clDFoMyv", "created": "2025-09-30T10:02:54.008Z", "currency": "EUR", "customer_id": "customerssh", "customer": { "id": "customerssh", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": null, "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": "30", "card_holder_name": "joseph 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": "9999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customerssh", "created_at": 1759226573, "expires": 1759230173, "secret": "epk_4296651e27474ad2b0a0c3cd27f2748b" }, "manual_retry_allowed": null, "connector_transaction_id": "mhgsAykYdVmEKMSzIL", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "mhgsAykYdVmEKMSzIL", "payment_link": null, "profile_id": "pro_QEwjCvFhpcLC2azRNZEf", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_lJPT4aN2CbXmgSAFDmCT", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-30T10:17:54.008Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": "pm_ZNF2NslDvKAFvlUG5HwO", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-09-30T10:02:56.107Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "yjYPw5r6T7d2VgSbRf", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9cd8f001f7360d9b8877fe94b9c185fc237e525c
juspay/hyperswitch
juspay__hyperswitch-9596
Bug: [BUG] connector_request_reference_id not updated in payment_tokenization confirm_intent flow ### Bug Description In the payment tokenization confirm intent flow, the field `connector_request_reference_id` is not being updated in payment_attempt. Because of this missing update, flows such as PaymentsCancel and PaymentsCapture break, resulting in a 500 Internal Server Error with the message "connector_request_reference_id not found in payment_attempt". ### Expected Behavior The expected behavior is that during confirm intent `connector_request_reference_id` field should be updated in payment attepmt, so that subsequent cancel and capture operations can function correctly without failing. ### Actual Behavior Because of this missing update, flows such as PaymentsCancel and PaymentsCapture break, resulting in a 500 Internal Server Error with the message "connector_request_reference_id not found in payment_attempt". <img width="1721" height="428" alt="Image" src="https://github.com/user-attachments/assets/f2eea707-d3bc-4213-9f78-495cb0249f6f" /> ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Create a Payment Intent ``` { "amount_details": { "order_amount": 10000, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "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" }, "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" }, "email": "[email protected]" } } ``` 2. Confirm the Payment Intent with customer_acceptance ``` { "payment_method_data": { "card": { "card_cvc": "123", "card_exp_month": "10", "card_exp_year": "25", "card_number": "4111111111111111", "card_holder_name": "joseph Doe" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" }, "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" } } } ``` 3. Attempt to Void After the confirm step, call /v2/payments/{payment_id}/cancel. <img width="1728" height="431" alt="Image" src="https://github.com/user-attachments/assets/723db89c-2f25-4e29-8e40-bac011d23500" /> Observed Behavior: The void request fails with a 500 Internal Server Error because the field connector_request_reference_id is not updated in payment_attempt during the confirm intent step. ### 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_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 7f8b9020618..256f3ef2728 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -2017,6 +2017,7 @@ pub enum PaymentAttemptUpdate { merchant_connector_id: id_type::MerchantConnectorAccountId, authentication_type: storage_enums::AuthenticationType, payment_method_id: id_type::GlobalPaymentMethodId, + connector_request_reference_id: Option<String>, }, /// Update the payment attempt on confirming the intent, after calling the connector on success response ConfirmIntentResponse(Box<ConfirmIntentResponseUpdate>), @@ -3041,6 +3042,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal merchant_connector_id, authentication_type, payment_method_id, + connector_request_reference_id, } => Self { status: Some(status), payment_method_id: Some(payment_method_id), @@ -3066,7 +3068,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_advice_code: None, network_decline_code: None, network_error_message: None, - connector_request_reference_id: None, + connector_request_reference_id, connector_response_reference_id: None, }, } 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 ccbe540dfc5..f8f293faf96 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -620,6 +620,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, PaymentsConfirmInt .attach_printable("Merchant connector id is none when constructing response") })?, authentication_type, + connector_request_reference_id, payment_method_id : payment_method.get_id().clone() } }
2025-09-29T09:55:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> In the payment tokenization confirm intent flow, the field `connector_request_reference_id` was not being updated in payment_attempt. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes #9596 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Confirm Intent : ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_019994e36a177e03b4024c1e86907ed0/confirm-intent' \ --header 'x-profile-id: pro_rn7g67NOZXIaqMQMjSWG' \ --header 'x-client-secret: cs_019994e36a2a771290eaaf9c5baba115' \ --header 'Authorization: api-key=dev_C9gNbgcEhMbQloVd4ASlr97dPXRvpcZP5iTrecc88qJA1UqMsJa0VPxqlz8lOcy9' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_aacd87682cc548e6a240c0a5e69c3771' \ --data '{ "payment_method_data": { "card": { "card_cvc": "123", "card_exp_month": "10", "card_exp_year": "25", "card_number": "4111111111111111", "card_holder_name": "joseph Doe" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" }, "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" } } }' ``` Response: ``` { "id": "12345_pay_019994e36a177e03b4024c1e86907ed0", "status": "requires_capture", "amount": { "order_amount": 10000, "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": 10000, "amount_to_capture": null, "amount_capturable": 10000, "amount_captured": 0 }, "customer_id": "12345_cus_019994e3438475c39db3fd368c7f5343", "connector": "authorizedotnet", "created": "2025-09-29T09:52:35.876Z", "modified_at": "2025-09-29T09:52:45.633Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "120071794888", "connector_reference_id": "120071794888", "merchant_connector_id": "mca_wOvtWjK6SlBGig1M2MFQ", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": "12345_pm_019994e387c677919b40d6062bff9935", "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, "merchant_reference_id": null, "raw_connector_response": null, "feature_metadata": null, "metadata": null } ``` <img width="773" height="173" alt="image" src="https://github.com/user-attachments/assets/b07d60f5-ec3e-4419-ae38-4e922a955fe8" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9cd8f001f7360d9b8877fe94b9c185fc237e525c
juspay/hyperswitch
juspay__hyperswitch-9613
Bug: [FEAT]: Add support for visibility and updating additional token details
diff --git a/crates/api_models/src/revenue_recovery_data_backfill.rs b/crates/api_models/src/revenue_recovery_data_backfill.rs index 34c64b75547..8f0276a84c0 100644 --- a/crates/api_models/src/revenue_recovery_data_backfill.rs +++ b/crates/api_models/src/revenue_recovery_data_backfill.rs @@ -3,11 +3,11 @@ use std::{collections::HashMap, fs::File, io::BufReader}; use actix_multipart::form::{tempfile::TempFile, MultipartForm}; use actix_web::{HttpResponse, ResponseError}; use common_enums::{CardNetwork, PaymentMethodType}; -use common_utils::events::ApiEventMetric; +use common_utils::{events::ApiEventMetric, pii::PhoneNumberStrategy}; use csv::Reader; use masking::Secret; use serde::{Deserialize, Serialize}; -use time::Date; +use time::{Date, PrimitiveDateTime}; #[derive(Debug, Deserialize, Serialize)] pub struct RevenueRecoveryBackfillRequest { @@ -82,6 +82,24 @@ impl ApiEventMetric for CsvParsingError { } } +impl ApiEventMetric for RedisDataResponse { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Miscellaneous) + } +} + +impl ApiEventMetric for UpdateTokenStatusRequest { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Miscellaneous) + } +} + +impl ApiEventMetric for UpdateTokenStatusResponse { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Miscellaneous) + } +} + #[derive(Debug, Clone, Serialize)] pub enum BackfillError { InvalidCardType(String), @@ -96,6 +114,72 @@ pub struct BackfillQuery { pub cutoff_time: Option<String>, } +#[derive(Debug, Serialize, Deserialize)] +pub enum RedisKeyType { + Status, // for customer:{id}:status + Tokens, // for customer:{id}:tokens +} + +#[derive(Debug, Deserialize)] +pub struct GetRedisDataQuery { + pub key_type: RedisKeyType, +} + +#[derive(Debug, Serialize)] +pub struct RedisDataResponse { + pub exists: bool, + pub ttl_seconds: i64, + pub data: Option<serde_json::Value>, +} + +#[derive(Debug, Serialize)] +pub enum ScheduledAtUpdate { + SetToNull, + SetToDateTime(PrimitiveDateTime), +} + +impl<'de> Deserialize<'de> for ScheduledAtUpdate { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + let value = serde_json::Value::deserialize(deserializer)?; + + match value { + serde_json::Value::String(s) => { + if s.to_lowercase() == "null" { + Ok(Self::SetToNull) + } else { + // Parse as datetime using iso8601 deserializer + common_utils::custom_serde::iso8601::deserialize( + &mut serde_json::Deserializer::from_str(&format!("\"{}\"", s)), + ) + .map(Self::SetToDateTime) + .map_err(serde::de::Error::custom) + } + } + _ => Err(serde::de::Error::custom( + "Expected null variable or datetime iso8601 ", + )), + } + } +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct UpdateTokenStatusRequest { + pub connector_customer_id: String, + pub payment_processor_token: Secret<String, PhoneNumberStrategy>, + pub scheduled_at: Option<ScheduledAtUpdate>, + pub is_hard_decline: Option<bool>, + pub error_code: Option<String>, +} + +#[derive(Debug, Serialize)] +pub struct UpdateTokenStatusResponse { + pub updated: bool, + pub message: String, +} + impl std::fmt::Display for BackfillError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index b0bf47e955e..54e7eed7f11 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -485,6 +485,14 @@ impl super::RedisConnectionPool { .change_context(errors::RedisError::SetExpiryFailed) } + #[instrument(level = "DEBUG", skip(self))] + pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> { + self.pool + .ttl(key.tenant_aware_key(self)) + .await + .change_context(errors::RedisError::GetFailed) + } + #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_fields<V>( &self, diff --git a/crates/router/src/core/revenue_recovery_data_backfill.rs b/crates/router/src/core/revenue_recovery_data_backfill.rs index 629b9e6a586..d6df7b75b57 100644 --- a/crates/router/src/core/revenue_recovery_data_backfill.rs +++ b/crates/router/src/core/revenue_recovery_data_backfill.rs @@ -1,10 +1,12 @@ use std::collections::HashMap; use api_models::revenue_recovery_data_backfill::{ - BackfillError, ComprehensiveCardData, RevenueRecoveryBackfillRequest, - RevenueRecoveryDataBackfillResponse, UnlockStatusResponse, + BackfillError, ComprehensiveCardData, GetRedisDataQuery, RedisDataResponse, RedisKeyType, + RevenueRecoveryBackfillRequest, RevenueRecoveryDataBackfillResponse, ScheduledAtUpdate, + UnlockStatusResponse, UpdateTokenStatusRequest, UpdateTokenStatusResponse, }; use common_enums::{CardNetwork, PaymentMethodType}; +use error_stack::ResultExt; use hyperswitch_domain_models::api::ApplicationResponse; use masking::ExposeInterface; use router_env::{instrument, logger}; @@ -86,6 +88,150 @@ pub async fn unlock_connector_customer_status( Ok(ApplicationResponse::Json(response)) } +pub async fn get_redis_data( + state: SessionState, + connector_customer_id: &str, + key_type: &RedisKeyType, +) -> RouterResult<ApplicationResponse<RedisDataResponse>> { + match storage::revenue_recovery_redis_operation::RedisTokenManager::get_redis_key_data_raw( + &state, + connector_customer_id, + key_type, + ) + .await + { + Ok((exists, ttl_seconds, data)) => { + let response = RedisDataResponse { + exists, + ttl_seconds, + data, + }; + + logger::info!( + "Retrieved Redis data for connector customer {}, exists={}, ttl={}", + connector_customer_id, + exists, + ttl_seconds + ); + + Ok(ApplicationResponse::Json(response)) + } + Err(error) => Err( + error.change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: format!( + "Redis data not found for connector customer id:- '{}'", + connector_customer_id + ), + }), + ), + } +} + +pub async fn redis_update_additional_details_for_revenue_recovery( + state: SessionState, + request: UpdateTokenStatusRequest, +) -> RouterResult<ApplicationResponse<UpdateTokenStatusResponse>> { + // Get existing token + let existing_token = storage::revenue_recovery_redis_operation:: + RedisTokenManager::get_payment_processor_token_using_token_id( + &state, + &request.connector_customer_id, + &request.payment_processor_token.clone().expose(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve existing token data")?; + + // Check if token exists + let mut token_status = existing_token.ok_or_else(|| { + error_stack::Report::new(errors::ApiErrorResponse::GenericNotFoundError { + message: format!( + "Token '{:?}' not found for connector customer id:- '{}'", + request.payment_processor_token, request.connector_customer_id + ), + }) + })?; + + let mut updated_fields = Vec::new(); + + // Handle scheduled_at update + match request.scheduled_at { + Some(ScheduledAtUpdate::SetToDateTime(dt)) => { + // Field provided with datetime - update schedule_at field with datetime + token_status.scheduled_at = Some(dt); + updated_fields.push(format!("scheduled_at: {}", dt)); + logger::info!( + "Set scheduled_at to '{}' for token '{:?}'", + dt, + request.payment_processor_token + ); + } + Some(ScheduledAtUpdate::SetToNull) => { + // Field provided with "null" variable - set schedule_at field to null + token_status.scheduled_at = None; + updated_fields.push("scheduled_at: set to null".to_string()); + logger::info!( + "Set scheduled_at to null for token '{:?}'", + request.payment_processor_token + ); + } + None => { + // Field not provided - we don't update schedule_at field + logger::debug!("scheduled_at not provided in request - leaving unchanged"); + } + } + + // Update is_hard_decline field + request.is_hard_decline.map(|is_hard_decline| { + token_status.is_hard_decline = Some(is_hard_decline); + updated_fields.push(format!("is_hard_decline: {}", is_hard_decline)); + }); + + // Update error_code field + request.error_code.as_ref().map(|error_code| { + token_status.error_code = Some(error_code.clone()); + updated_fields.push(format!("error_code: {}", error_code)); + }); + + // Update Redis with modified token + let mut tokens_map = HashMap::new(); + tokens_map.insert( + request.payment_processor_token.clone().expose(), + token_status, + ); + + storage::revenue_recovery_redis_operation:: + RedisTokenManager::update_or_add_connector_customer_payment_processor_tokens( + &state, + &request.connector_customer_id, + tokens_map, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update token status in Redis")?; + + let updated_fields_str = if updated_fields.is_empty() { + "no fields were updated".to_string() + } else { + updated_fields.join(", ") + }; + + let response = UpdateTokenStatusResponse { + updated: true, + message: format!( + "Successfully updated token '{:?}' for connector customer '{}'. Updated fields: {}", + request.payment_processor_token, request.connector_customer_id, updated_fields_str + ), + }; + + logger::info!( + "Updated token status for connector customer {}, token: {:?}", + request.connector_customer_id, + request.payment_processor_token + ); + + Ok(ApplicationResponse::Json(response)) +} async fn process_payment_method_record( state: &SessionState, diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index faefaffa547..a41c1df68f6 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -50,6 +50,8 @@ pub mod recon; pub mod refunds; #[cfg(feature = "v2")] pub mod revenue_recovery_data_backfill; +#[cfg(feature = "v2")] +pub mod revenue_recovery_redis; #[cfg(feature = "olap")] pub mod routing; #[cfg(feature = "v1")] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1de0029f767..9647be8caf1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -3018,5 +3018,15 @@ impl RecoveryDataBackfill { super::revenue_recovery_data_backfill::revenue_recovery_data_backfill_status, ), )) + .service(web::resource("/redis-data/{token_id}").route( + web::get().to( + super::revenue_recovery_redis::get_revenue_recovery_redis_data, + ), + )) + .service(web::resource("/update-token").route( + web::put().to( + super::revenue_recovery_data_backfill::update_revenue_recovery_additional_redis_data, + ), + )) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 992edb61c35..922a0de1708 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -50,7 +50,7 @@ pub enum ApiIdentifier { ProfileAcquirer, ThreeDsDecisionRule, GenericTokenization, - RecoveryDataBackfill, + RecoveryRecovery, } impl From<Flow> for ApiIdentifier { @@ -350,7 +350,7 @@ impl From<Flow> for ApiIdentifier { Self::GenericTokenization } - Flow::RecoveryDataBackfill => Self::RecoveryDataBackfill, + Flow::RecoveryDataBackfill | Flow::RevenueRecoveryRedis => Self::RecoveryRecovery, } } } diff --git a/crates/router/src/routes/revenue_recovery_data_backfill.rs b/crates/router/src/routes/revenue_recovery_data_backfill.rs index 4203f52dfff..3a5c378e74c 100644 --- a/crates/router/src/routes/revenue_recovery_data_backfill.rs +++ b/crates/router/src/routes/revenue_recovery_data_backfill.rs @@ -1,6 +1,8 @@ use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; -use api_models::revenue_recovery_data_backfill::{BackfillQuery, RevenueRecoveryDataBackfillForm}; +use api_models::revenue_recovery_data_backfill::{ + BackfillQuery, GetRedisDataQuery, RevenueRecoveryDataBackfillForm, UpdateTokenStatusRequest, +}; use router_env::{instrument, tracing, Flow}; use crate::{ @@ -66,6 +68,30 @@ pub async fn revenue_recovery_data_backfill( .await } +#[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))] +pub async fn update_revenue_recovery_additional_redis_data( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<UpdateTokenStatusRequest>, +) -> HttpResponse { + let flow = Flow::RecoveryDataBackfill; + + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _: (), request, _| { + revenue_recovery_data_backfill::redis_update_additional_details_for_revenue_recovery( + state, request, + ) + }, + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))] pub async fn revenue_recovery_data_backfill_status( state: web::Data<AppState>, diff --git a/crates/router/src/routes/revenue_recovery_redis.rs b/crates/router/src/routes/revenue_recovery_redis.rs new file mode 100644 index 00000000000..fe6cbe5a97b --- /dev/null +++ b/crates/router/src/routes/revenue_recovery_redis.rs @@ -0,0 +1,34 @@ +use actix_web::{web, HttpRequest, HttpResponse}; +use api_models::revenue_recovery_data_backfill::GetRedisDataQuery; +use router_env::{instrument, tracing, Flow}; + +use crate::{ + core::{api_locking, revenue_recovery_data_backfill}, + routes::AppState, + services::{api, authentication as auth}, +}; + +#[instrument(skip_all, fields(flow = ?Flow::RevenueRecoveryRedis))] +pub async fn get_revenue_recovery_redis_data( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, + query: web::Query<GetRedisDataQuery>, +) -> HttpResponse { + let flow = Flow::RevenueRecoveryRedis; + let connector_customer_id = path.into_inner(); + let key_type = &query.key_type; + + Box::pin(api::server_wrap( + flow, + state, + &req, + (), + |state, _: (), _, _| { + revenue_recovery_data_backfill::get_redis_data(state, &connector_customer_id, key_type) + }, + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs index e89db0d1aa8..96b0a438355 100644 --- a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs +++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use api_models; +use api_models::revenue_recovery_data_backfill::{self, RedisKeyType}; use common_enums::enums::CardNetwork; use common_utils::{date_time, errors::CustomResult, id_type}; use error_stack::ResultExt; @@ -755,13 +755,90 @@ impl RedisTokenManager { Ok(token) } + /// Get Redis key data for revenue recovery + #[instrument(skip_all)] + pub async fn get_redis_key_data_raw( + state: &SessionState, + connector_customer_id: &str, + key_type: &RedisKeyType, + ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> { + let redis_conn = + state + .store + .get_redis_conn() + .change_context(errors::StorageError::RedisError( + errors::RedisError::RedisConnectionError.into(), + ))?; + + let redis_key = match key_type { + RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id), + RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id), + }; + + // Get TTL + let ttl = redis_conn + .get_ttl(&redis_key.clone().into()) + .await + .map_err(|error| { + tracing::error!(operation = "get_ttl", err = ?error); + errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into()) + })?; + + // Get data based on key type and determine existence + let (key_exists, data) = match key_type { + RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await { + Ok(status_value) => (true, serde_json::Value::String(status_value)), + Err(error) => { + tracing::error!(operation = "get_status_key", err = ?error); + ( + false, + serde_json::Value::String(format!( + "Error retrieving status key: {}", + error + )), + ) + } + }, + RedisKeyType::Tokens => { + match redis_conn + .get_hash_fields::<HashMap<String, String>>(&redis_key.into()) + .await + { + Ok(hash_fields) => { + let exists = !hash_fields.is_empty(); + let data = if exists { + serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null) + } else { + serde_json::Value::Object(serde_json::Map::new()) + }; + (exists, data) + } + Err(error) => { + tracing::error!(operation = "get_tokens_hash", err = ?error); + (false, serde_json::Value::Null) + } + } + } + }; + + tracing::debug!( + connector_customer_id = connector_customer_id, + key_type = ?key_type, + exists = key_exists, + ttl = ttl, + "Retrieved Redis key data" + ); + + Ok((key_exists, ttl, Some(data))) + } + /// Update Redis token with comprehensive card data #[instrument(skip_all)] pub async fn update_redis_token_with_comprehensive_card_data( state: &SessionState, customer_id: &str, token: &str, - card_data: &api_models::revenue_recovery_data_backfill::ComprehensiveCardData, + card_data: &revenue_recovery_data_backfill::ComprehensiveCardData, cutoff_datetime: Option<PrimitiveDateTime>, ) -> CustomResult<(), errors::StorageError> { // Get existing token data diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 50c47489108..0213c5c9b27 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -658,6 +658,8 @@ pub enum Flow { TokenizationDelete, /// Payment method data backfill flow RecoveryDataBackfill, + /// Revenue recovery Redis operations flow + RevenueRecoveryRedis, /// Gift card balance check flow GiftCardBalanceCheck, }
2025-09-29T13:22:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR introduces two new API:- 1) To get data from Redis for monitoring purpose **v2/recovery/data-backfill/redis-data/:id?key_type=Status** 2) To update additional token data(error code, hard decline flag and schedule at fields) **v2/recovery/data-backfill/update-token** ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> cURL to get redis data (token type:- Tokens) ``` curl --location 'http://localhost:8080/v2/recovery/data-backfill/redis-data/10010?key_type=Tokens' \ --header 'Authorization: admin-api-key=test_admin' ``` Test case 1 (token is present) Response:- ``` { "exists": true, "ttl_seconds": 3887994, "data": { "2401559361951038": "{\"payment_processor_token_details\":{\"payment_processor_token\":\"2401559361951038\",\"expiry_month\":\"02\",\"expiry_year\":\"27\",\"card_issuer\":\"Plus Credit Union\",\"last_four_digits\":null,\"card_network\":null,\"card_type\":\"card\"},\"inserted_by_attempt_id\":\"12345_att_0199517c62647b9090c328ed1b28ebf6\",\"error_code\":\"12\",\"daily_retry_history\":{},\"scheduled_at\":null,\"is_hard_decline\":false}" } } ``` Test case 2 (token is not present) ``` { "error": { "type": "invalid_request", "message": "Redis data not found for connector customer id:- '100101'", "code": "IR_37" } } Router log:- <img width="1353" height="758" alt="Screenshot 2025-09-29 at 19 32 47" src="https://github.com/user-attachments/assets/89198cc1-70ce-4ac4-9b20-4d53e7260754" /> ``` cURL to get redis data (token type:- Status) ``` curl --location 'http://localhost:8080/v2/recovery/data-backfill/redis-data/100101?key_type=Status' \ --header 'Authorization: admin-api-key=test_admin' ``` Test case 3 (status is not present) ``` { "error": { "type": "invalid_request", "message": "Redis data not found for connector customer id:- '100101'", "code": "IR_37" } } ``` cURL to update redis data ``` curl --location --request PUT 'http://localhost:8080/v2/recovery/data-backfill/update-token' \ --header 'Content-Type: application/json' \ --header 'Authorization: admin-api-key=test_admin' \ --data '{ "connector_customer_id": "57984238498234763874917211", "payment_processor_token": "2541911049890008", "scheduled_at": "2025-09-29T08:45:53.692126Z", "is_hard_decline": false, "error_code": "-1" } ' ``` Test case 4 (token is present) ``` { "updated": true, "message": "Successfully updated token '0008' for connector customer '10010'. Updated fields: scheduled_at: 2025-09-29T08:45:53.692126Z, is_hard_decline: false, error_code: -1" } ``` Test case 5 (token is not present) ``` { "error": { "type": "invalid_request", "message": "Token '0008' not found for connector customer id:- '100101'", "code": "IR_37" } } ``` <img width="1359" height="689" alt="Screenshot 2025-09-29 at 19 34 29" src="https://github.com/user-attachments/assets/675442da-0ac1-44fd-b3ab-a4ce921370fe" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9cd8f001f7360d9b8877fe94b9c185fc237e525c
juspay/hyperswitch
juspay__hyperswitch-9572
Bug: [FEATURE] Add Peachpayments Cypress ### Feature Description Add Peachpayments Cypress ### Possible Implementation Add Peachpayments Cypress ### 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/peachpayments.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments.rs index abc8caf1efc..dd5c4869cf9 100644 --- a/crates/hyperswitch_connectors/src/connectors/peachpayments.rs +++ b/crates/hyperswitch_connectors/src/connectors/peachpayments.rs @@ -171,6 +171,16 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Peachpayments { + fn build_request( + &self, + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented( + "Setup Mandate flow for Peachpayments".to_string(), + ) + .into()) + } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs index 9b1776bf056..5ae02cc24cc 100644 --- a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs @@ -20,7 +20,7 @@ use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use crate::{ types::ResponseRouterData, - utils::{self, CardData}, + utils::{self, CardData, RouterData as OtherRouterData}, }; //TODO: Fill the struct with respective fields @@ -311,6 +311,14 @@ impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>> fn try_from( item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { + if item.router_data.is_three_ds() { + return Err(errors::ConnectorError::NotSupported { + message: "3DS flow".to_string(), + connector: "Peachpayments", + } + .into()); + } + match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let amount_in_cents = item.amount;
2025-09-26T09:14:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9572) ## Description <!-- Describe your changes in detail --> Added Peachpayments Cypress Test. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Cypress Test Screenshot: **Peachpayments** - <img width="325" height="839" alt="Screenshot 2025-09-26 at 2 42 26 PM" src="https://github.com/user-attachments/assets/af0e67f4-1811-453a-b47d-442a4b8665c6" /> **Refund flow of Adyen(prod connector)** - <img width="888" height="1077" alt="Screenshot 2025-09-26 at 4 13 20 PM" src="https://github.com/user-attachments/assets/ba7ce251-bd47-4c31-b123-aaf729af345a" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
1ff66a720b29a169870b2141e6ffd585b4d5b640
juspay/hyperswitch
juspay__hyperswitch-9570
Bug: [REFACTOR] (GOOGLEPAY) Introduce `cardsFundingSource` in google pay payment method data What's Changing? GPay API response will include a new field, `cardFundingSource`, within the [`CardInfo`](https://developers.google.com/pay/api/web/reference/response-objects#CardInfo) response object. This field will help you identify whether a card used in a transaction is a `"CREDIT"`, `"DEBIT"`, or `"PREPAID"` card. In some cases, this may not be known and an `"UNKNOWN"` value will be returned. Important: for the time being, `cardFundingSource` is only returned in `TEST` environment. Google will release to `PRODUCTION` in 2025 Q4.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 840ab7537f0..56416e21427 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -9,7 +9,7 @@ pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; -use common_enums::ProductType; +use common_enums::{GooglePayCardFundingSource, ProductType}; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, @@ -4261,6 +4261,8 @@ pub struct GooglePayPaymentMethodInfo { pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, + /// Card funding source for the selected payment method + pub card_funding_source: Option<GooglePayCardFundingSource>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 529bb649cc9..e6e71abff74 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -9560,3 +9560,13 @@ pub enum ExternalVaultEnabled { #[default] Skip, } + +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "UPPERCASE")] +pub enum GooglePayCardFundingSource { + Credit, + Debit, + Prepaid, + #[serde(other)] + Unknown, +} diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index e9d766f912b..6cc381cb8f2 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -1,4 +1,4 @@ -use common_enums::{enums, CaptureMethod, FutureUsage, PaymentChannel}; +use common_enums::{enums, CaptureMethod, FutureUsage, GooglePayCardFundingSource, PaymentChannel}; use common_types::{ payments::{ ApplePayPaymentData, ApplePayPredecryptData, GPayPredecryptData, GpayTokenizationData, @@ -1033,6 +1033,7 @@ struct GooglePayInfoCamelCase { card_network: Secret<String>, card_details: Secret<String>, assurance_details: Option<GooglePayAssuranceDetailsCamelCase>, + card_funding_source: Option<GooglePayCardFundingSource>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] @@ -1161,6 +1162,7 @@ where .card_holder_authenticated, account_verified: details.account_verified, }), + card_funding_source: gpay_data.info.card_funding_source.clone(), }, tokenization_data: GooglePayTokenizationDataCamelCase { token_type: token_type.into(), diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 85051693105..d08c9cd47b7 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -51,7 +51,10 @@ use hyperswitch_domain_models::{ address::{Address, AddressDetails, PhoneDetails}, mandates, network_tokenization::NetworkTokenNumber, - payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData}, + payment_method_data::{ + self, Card, CardDetailsForNetworkTransactionId, GooglePayPaymentMethodInfo, + PaymentMethodData, + }, router_data::{ ErrorResponse, L2L3Data, PaymentMethodToken, RecurringMandatePaymentData, RouterData as ConnectorRouterData, @@ -238,13 +241,6 @@ pub struct GooglePayWalletData { pub tokenization_data: common_types::payments::GpayTokenizationData, } -#[derive(Clone, Debug, serde::Serialize)] -#[serde(rename_all = "camelCase")] -pub struct GooglePayPaymentMethodInfo { - pub card_network: String, - pub card_details: String, -} - #[derive(Debug, Serialize)] pub struct CardMandateInfo { pub card_exp_month: Secret<String>, @@ -277,6 +273,8 @@ impl TryFrom<payment_method_data::GooglePayWalletData> for GooglePayWalletData { info: GooglePayPaymentMethodInfo { card_network: data.info.card_network, card_details: data.info.card_details, + assurance_details: data.info.assurance_details, + card_funding_source: data.info.card_funding_source, }, tokenization_data, }) diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 6bc9062eea2..7046bb18c2f 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -6,7 +6,7 @@ use api_models::{ payment_methods::{self}, payments::{additional_info as payment_additional_types, ExtendedCardInfo}, }; -use common_enums::enums as api_enums; +use common_enums::{enums as api_enums, GooglePayCardFundingSource}; use common_utils::{ ext_traits::{OptionExt, StringExt}, id_type, @@ -468,8 +468,10 @@ pub struct GooglePayPaymentMethodInfo { pub card_network: String, /// The details of the card pub card_details: String, - //assurance_details of the card + /// assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, + /// Card funding source for the selected payment method + pub card_funding_source: Option<GooglePayCardFundingSource>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] @@ -1265,6 +1267,7 @@ impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData { account_verified: info.account_verified, } }), + card_funding_source: value.info.card_funding_source, }, tokenization_data: value.tokenization_data, } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index e52daa7fedb..2759bfc6e18 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -382,6 +382,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::OrganizationType, api_models::enums::PaymentLinkShowSdkTerms, api_models::enums::ExternalVaultEnabled, + api_models::enums::GooglePayCardFundingSource, api_models::enums::VaultSdk, api_models::admin::ExternalVaultConnectorDetails, api_models::admin::MerchantConnectorCreate, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 6ea50cb85fa..f4c1944931d 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -334,6 +334,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::PaymentLinkSdkLabelType, api_models::enums::PaymentLinkShowSdkTerms, api_models::enums::OrganizationType, + api_models::enums::GooglePayCardFundingSource, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, api_models::admin::CardTestingGuardConfig, diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs index 585a5a10f10..17278bf5e16 100644 --- a/crates/router/tests/connectors/payu.rs +++ b/crates/router/tests/connectors/payu.rs @@ -1,3 +1,4 @@ +use common_enums::GooglePayCardFundingSource; use masking::PeekInterface; use router::types::{self, domain, storage::enums, AccessToken, ConnectorAuthType}; @@ -97,6 +98,7 @@ async fn should_authorize_gpay_payment() { card_network: "VISA".to_string(), card_details: "1234".to_string(), assurance_details: None, + card_funding_source: Some(GooglePayCardFundingSource::Unknown), }, tokenization_data: common_types::payments::GpayTokenizationData::Encrypted( common_types::payments::GpayEcryptedTokenizationData { diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs index 2c792337b16..022d0862cba 100644 --- a/crates/router/tests/connectors/worldpay.rs +++ b/crates/router/tests/connectors/worldpay.rs @@ -1,3 +1,4 @@ +use common_enums::GooglePayCardFundingSource; use futures::future::OptionFuture; use router::types::{self, domain, storage::enums}; use serde_json::json; @@ -70,6 +71,7 @@ async fn should_authorize_gpay_payment() { card_network: "VISA".to_string(), card_details: "1234".to_string(), assurance_details: None, + card_funding_source: Some(GooglePayCardFundingSource::Unknown), }, tokenization_data: common_types::payments::GpayTokenizationData::Encrypted( common_types::payments::GpayEcryptedTokenizationData {
2025-09-25T18:48:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> google recently [introduced](https://developers.google.com/pay/api/web/reference/response-objects#CardInfo) new field called `cardFundingSource`. It is an upcoming gpay api change it takes an enum: - `UNKNOWN` - `CREDIT` - `DEBIT` - `PREPAID` google has mentioned it on their api reference that this info will be `none` on production until q4 of 2025. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> this new information will enable us to implement more sophisticated business logic such as routing, analytics, fraud management etc, tailored to different card types. closes https://github.com/juspay/hyperswitch/issues/9570 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ```bash curl --location 'http://localhost:8080/payments/pay_P9LfwQUR2raIVIvvY1pb/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_uDP0kqyLTXnlN5jYassJphQYXWAJEywH4BSkKQXtJoOYLCs71FGNCifuORqq9w2q' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "description": "Visa •••• 1111", "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{\"signature\":\"MEUCIAT1vH7oE0bc1FR..." }, "type": "CARD", "info": { "card_network": "VISA", "card_details": "1111" } } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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" } } }' ``` ```json { "payment_id": "pay_P9LfwQUR2raIVIvvY1pb", "merchant_id": "postman_merchant_GHAction_1758879946", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "cybersource", "client_secret": "pay_P9LfwQUR2raIVIvvY1pb_secret_NWAWTxJGdQ0z1OAj5wAZ", "created": "2025-09-26T09:45:52.604Z", "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": { "google_pay": { "last4": "1111", "card_network": "VISA", "type": "CARD" } }, "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", "origin_zip": 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": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": 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": "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": "google_pay", "connector_label": "cybersource_US_default_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "7588799552276876103812", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_P9LfwQUR2raIVIvvY1pb_1", "payment_link": null, "profile_id": "pro_QHOqYvAjzpmM3wQpjd2E", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_N8JtdITxcIuQ0D1tM1Uh", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-26T10:00:52.604Z", "fingerprint": null, "browser_info": { "os_type": null, "referer": null, "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "os_version": null, "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, "device_model": null, "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, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": "016153570198200", "payment_method_status": null, "updated": "2025-09-26T09:45:56.234Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` nuvei: ```bash { "amount": 1, "currency": "EUR", "confirm": true, "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "wallet", "payment_method_type": "google_pay", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "UA", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" }, "email": "[email protected]" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "[email protected]", "payment_method_data": { "wallet": { "google_pay": { "description": "SG Visa Success: Visa •••• 1390", "info": { "assurance_details": { "account_verified": true, "card_holder_authenticated": false }, "card_details": "1390", "card_funding_source": "CREDIT", "card_network": "VISA" }, "tokenization_data": { "token": "{...}", "type": "PAYMENT_GATEWAY" }, "type": "CARD" } } } } ``` ```json { "payment_id": "pay_BHX5HsGxx8GWTqhtxv55", "merchant_id": "merchant_1758885759", "status": "succeeded", "amount": 1, "net_amount": 1, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1, "connector": "nuvei", "client_secret": "pay_BHX5HsGxx8GWTqhtxv55_secret_9ZgxOEN1NokJgukDDUKe", "created": "2025-09-26T11:24:42.509Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": { "google_pay": { "last4": "1390", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "UA", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://www.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": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1758885882, "expires": 1758889482, "secret": "epk_31a09b5d224f4aea8bf6a114c6b7acd9" }, "manual_retry_allowed": null, "connector_transaction_id": "7110000000017459005", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "9201058111", "payment_link": null, "profile_id": "pro_IOIVxznj4AqQbMy44z1p", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MDGr4n22wQXL1OQXay79", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-26T11:39:42.509Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": "483297487231504", "payment_method_status": null, "updated": "2025-09-26T11:24:44.551Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` <img width="1188" height="405" alt="image" src="https://github.com/user-attachments/assets/854b7c02-1125-4d4b-9d08-1b46153d8ab8" /> after unmasking, this data is being sent to the connector: <img width="683" height="64" alt="image" src="https://github.com/user-attachments/assets/f3744dda-75b0-4aa5-a66a-b5185965c4ca" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- @coderabbitai ignore -->
efab34f0ef0bd032b049778f18f3cb688faa7fa7
juspay/hyperswitch
juspay__hyperswitch-9587
Bug: FEATURE: [LOONIO] Add template code Add template code for Loonio
diff --git a/config/config.example.toml b/config/config.example.toml index 56da591f1fc..7d01564db87 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -253,6 +253,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url= "https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" +loonio.base_url = "https://loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 02ee0124bae..1741835712e 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -91,6 +91,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url="https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" +loonio.base_url = "https://loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 998986b3829..9f74603c866 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -95,6 +95,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://www.katapult.com/api/v3" jpmorgan.secondary_base_url="https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.klarna.com/" +loonio.base_url = "https://loonio.ca/" mifinity.base_url = "https://secure.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 3f16af80c6f..09877fd802d 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -95,6 +95,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url="https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" +loonio.base_url = "https://loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" diff --git a/config/development.toml b/config/development.toml index c15532805db..387d0f0ba6f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -291,6 +291,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url = "https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" +loonio.base_url = "https://loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index b5101c53ad0..f29d2093b7c 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -179,6 +179,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url="https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" +loonio.base_url = "https://loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index aed9dbf70de..c01ac16c0e1 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -296,6 +296,7 @@ pub struct ConnectorConfig { pub inespay: Option<ConnectorTomlConfig>, pub jpmorgan: Option<ConnectorTomlConfig>, pub klarna: Option<ConnectorTomlConfig>, + pub loonio: Option<ConnectorTomlConfig>, pub mifinity: Option<ConnectorTomlConfig>, pub mollie: Option<ConnectorTomlConfig>, pub moneris: Option<ConnectorTomlConfig>, diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 4b4bbc6ec83..0f98861cc04 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7186,4 +7186,7 @@ api_key = "API Key" [tesouro] [tesouro.connector_auth.BodyKey] api_key="Client ID" -key1="Client Secret" \ No newline at end of file +key1="Client Secret" +[loonio] +[loonio.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 86eea4d3534..aea8277906e 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5923,4 +5923,7 @@ api_key = "API Key" [tesouro] [tesouro.connector_auth.BodyKey] api_key="Client ID" -key1="Client Secret" \ No newline at end of file +key1="Client Secret" +[loonio] +[loonio.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 08ae831a52e..f7c7ed3e997 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7165,4 +7165,7 @@ api_key = "API Key" [tesouro] [tesouro.connector_auth.BodyKey] api_key="Client ID" -key1="Client Secret" \ No newline at end of file +key1="Client Secret" +[loonio] +[loonio.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 70abd02eaaa..63257b72a90 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -63,6 +63,7 @@ pub mod jpmorgan; pub mod juspaythreedsserver; pub mod katapult; pub mod klarna; +pub mod loonio; pub mod mifinity; pub mod mollie; pub mod moneris; @@ -150,12 +151,12 @@ pub use self::{ gpayments::Gpayments, helcim::Helcim, hipay::Hipay, hyperswitch_vault::HyperswitchVault, hyperwallet::Hyperwallet, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, katapult::Katapult, - klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, mpgs::Mpgs, - multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, - nmi::Nmi, nomupay::Nomupay, noon::Noon, nordea::Nordea, novalnet::Novalnet, nuvei::Nuvei, - opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payload::Payload, - payme::Payme, payone::Payone, paypal::Paypal, paysafe::Paysafe, paystack::Paystack, - paytm::Paytm, payu::Payu, peachpayments::Peachpayments, phonepe::Phonepe, + klarna::Klarna, loonio::Loonio, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, + mpgs::Mpgs, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, + nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, nordea::Nordea, novalnet::Novalnet, + nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, + payload::Payload, payme::Payme, payone::Payone, paypal::Paypal, paysafe::Paysafe, + paystack::Paystack, paytm::Paytm, payu::Payu, peachpayments::Peachpayments, phonepe::Phonepe, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, santander::Santander, shift4::Shift4, sift::Sift, signifyd::Signifyd, silverflow::Silverflow, diff --git a/crates/hyperswitch_connectors/src/connectors/loonio.rs b/crates/hyperswitch_connectors/src/connectors/loonio.rs new file mode 100644 index 00000000000..ad57fad435e --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/loonio.rs @@ -0,0 +1,621 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::enums; +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::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 loonio; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Loonio { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Loonio { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Loonio {} +impl api::PaymentSession for Loonio {} +impl api::ConnectorAccessToken for Loonio {} +impl api::MandateSetup for Loonio {} +impl api::PaymentAuthorize for Loonio {} +impl api::PaymentSync for Loonio {} +impl api::PaymentCapture for Loonio {} +impl api::PaymentVoid for Loonio {} +impl api::Refund for Loonio {} +impl api::RefundExecute for Loonio {} +impl api::RefundSync for Loonio {} +impl api::PaymentToken for Loonio {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Loonio +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Loonio +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 Loonio { + fn id(&self) -> &'static str { + "loonio" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.loonio.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = loonio::LoonioAuthType::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: loonio::LoonioErrorResponse = res + .response + .parse_struct("LoonioErrorResponse") + .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, + connector_metadata: None, + }) + } +} + +impl ConnectorValidation for Loonio { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Loonio { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Loonio {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Loonio {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Loonio { + 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 = loonio::LoonioRouterData::from((amount, req)); + let connector_req = loonio::LoonioPaymentsRequest::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: loonio::LoonioPaymentsResponse = res + .response + .parse_struct("Loonio 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 Loonio { + 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: loonio::LoonioPaymentsResponse = res + .response + .parse_struct("loonio 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 Loonio { + 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: loonio::LoonioPaymentsResponse = res + .response + .parse_struct("Loonio 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 Loonio {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Loonio { + 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 = loonio::LoonioRouterData::from((refund_amount, req)); + let connector_req = loonio::LoonioRefundRequest::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: loonio::RefundResponse = + res.response + .parse_struct("loonio 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 Loonio { + 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: loonio::RefundResponse = res + .response + .parse_struct("loonio 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 Loonio { + 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)) + } +} + +static LOONIO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static LOONIO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Loonio", + description: "Loonio connector", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, +}; + +static LOONIO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Loonio { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&LOONIO_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*LOONIO_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&LOONIO_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs new file mode 100644 index 00000000000..0bdaf494cea --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs @@ -0,0 +1,219 @@ +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}; + +//TODO: Fill the struct with respective fields +pub struct LoonioRouterData<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 LoonioRouterData<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 LoonioPaymentsRequest { + amount: StringMinorUnit, + card: LoonioCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct LoonioCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&LoonioRouterData<&PaymentsAuthorizeRouterData>> for LoonioPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &LoonioRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct LoonioAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for LoonioAuthType { + 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, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum LoonioPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<LoonioPaymentStatus> for common_enums::AttemptStatus { + fn from(item: LoonioPaymentStatus) -> Self { + match item { + LoonioPaymentStatus::Succeeded => Self::Charged, + LoonioPaymentStatus::Failed => Self::Failure, + LoonioPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct LoonioPaymentsResponse { + status: LoonioPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, LoonioPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, LoonioPaymentsResponse, 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 LoonioRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&LoonioRouterData<&RefundsRouterData<F>>> for LoonioRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &LoonioRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 LoonioErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index f742437f400..7aaf51f554f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -231,6 +231,7 @@ default_imp_for_authorize_session_token!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -377,6 +378,7 @@ default_imp_for_calculate_tax!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -517,6 +519,7 @@ default_imp_for_session_update!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -664,6 +667,7 @@ default_imp_for_post_session_tokens!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -809,6 +813,7 @@ default_imp_for_create_order!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Rapyd, connectors::Recurly, connectors::Redsys, @@ -956,6 +961,7 @@ default_imp_for_update_metadata!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Paypal, connectors::Paysafe, connectors::Rapyd, @@ -1103,6 +1109,7 @@ default_imp_for_cancel_post_capture!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Paypal, connectors::Paysafe, connectors::Rapyd, @@ -1249,6 +1256,7 @@ default_imp_for_complete_authorize!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Moneris, connectors::Mpgs, @@ -1383,6 +1391,7 @@ default_imp_for_incremental_authorization!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -1522,6 +1531,7 @@ default_imp_for_create_customer!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -1664,6 +1674,7 @@ default_imp_for_connector_redirect_response!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Moneris, connectors::Mpgs, @@ -1796,6 +1807,7 @@ default_imp_for_pre_authenticate_steps!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -1942,6 +1954,7 @@ default_imp_for_authenticate_steps!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -2088,6 +2101,7 @@ default_imp_for_post_authenticate_steps!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -2231,6 +2245,7 @@ default_imp_for_pre_processing_steps!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nomupay, connectors::Noon, @@ -2367,6 +2382,7 @@ default_imp_for_post_processing_steps!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -2515,6 +2531,7 @@ default_imp_for_approve!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nomupay, connectors::Noon, @@ -2664,6 +2681,7 @@ default_imp_for_reject!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -2814,6 +2832,7 @@ default_imp_for_webhook_source_verification!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -2960,6 +2979,7 @@ default_imp_for_accept_dispute!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -3106,6 +3126,7 @@ default_imp_for_submit_evidence!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -3250,6 +3271,7 @@ default_imp_for_defend_dispute!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Helcim, connectors::Netcetera, connectors::Nmi, @@ -3398,6 +3420,7 @@ default_imp_for_fetch_disputes!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Loonio, connectors::Katapult, connectors::Helcim, connectors::Netcetera, @@ -3546,6 +3569,7 @@ default_imp_for_dispute_sync!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Loonio, connectors::Katapult, connectors::Helcim, connectors::Netcetera, @@ -3703,6 +3727,7 @@ default_imp_for_file_upload!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -3840,6 +3865,7 @@ default_imp_for_payouts!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -3983,6 +4009,7 @@ default_imp_for_payouts_create!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, @@ -4130,6 +4157,7 @@ default_imp_for_payouts_retrieve!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, @@ -4275,6 +4303,7 @@ default_imp_for_payouts_eligibility!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, @@ -4421,6 +4450,7 @@ default_imp_for_payouts_fulfill!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Noon, connectors::Nordea, @@ -4564,6 +4594,7 @@ default_imp_for_payouts_cancel!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, @@ -4711,6 +4742,7 @@ default_imp_for_payouts_quote!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, @@ -4859,6 +4891,7 @@ default_imp_for_payouts_recipient!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, @@ -5007,6 +5040,7 @@ default_imp_for_payouts_recipient_account!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, @@ -5156,6 +5190,7 @@ default_imp_for_frm_sale!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nomupay, connectors::Nmi, @@ -5305,6 +5340,7 @@ default_imp_for_frm_checkout!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -5454,6 +5490,7 @@ default_imp_for_frm_transaction!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -5603,6 +5640,7 @@ default_imp_for_frm_fulfillment!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -5752,6 +5790,7 @@ default_imp_for_frm_record_return!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -5896,6 +5935,7 @@ default_imp_for_revoking_mandates!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -6042,6 +6082,7 @@ default_imp_for_uas_pre_authentication!( connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -6188,6 +6229,7 @@ default_imp_for_uas_post_authentication!( connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -6335,6 +6377,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -6474,6 +6517,7 @@ default_imp_for_connector_request_id!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -6616,6 +6660,7 @@ default_imp_for_fraud_check!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -6786,6 +6831,7 @@ default_imp_for_connector_authentication!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -6930,6 +6976,7 @@ default_imp_for_uas_authentication!( connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -7070,6 +7117,7 @@ default_imp_for_revenue_recovery!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -7241,6 +7289,7 @@ default_imp_for_subscriptions!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -7391,6 +7440,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Netcetera, connectors::Nmi, @@ -7539,6 +7589,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, @@ -7687,6 +7738,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Nmi, connectors::Noon, @@ -7829,6 +7881,7 @@ default_imp_for_external_vault!( connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, @@ -7976,6 +8029,7 @@ default_imp_for_external_vault_insert!( connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, @@ -8121,6 +8175,7 @@ default_imp_for_gift_card_balance_check!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -8270,6 +8325,7 @@ default_imp_for_external_vault_retrieve!( connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, @@ -8417,6 +8473,7 @@ default_imp_for_external_vault_delete!( connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, @@ -8565,6 +8622,7 @@ default_imp_for_external_vault_create!( connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, @@ -8714,6 +8772,7 @@ default_imp_for_connector_authentication_token!( connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mpgs, connectors::Netcetera, connectors::Nomupay, @@ -8860,6 +8919,7 @@ default_imp_for_external_vault_proxy_payments_create!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 42236aa86af..260f5984a89 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -331,6 +331,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -480,6 +481,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -621,6 +623,7 @@ default_imp_for_new_connector_integration_connector_authentication_token!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -761,6 +764,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -910,6 +914,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -1059,6 +1064,7 @@ default_imp_for_new_connector_integration_fetch_disputes!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -1209,6 +1215,7 @@ default_imp_for_new_connector_integration_dispute_sync!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -1359,6 +1366,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -1506,6 +1514,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Loonio, connectors::Katapult, connectors::Nomupay, connectors::Noon, @@ -1666,6 +1675,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -1817,6 +1827,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -1968,6 +1979,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -2119,6 +2131,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -2270,6 +2283,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -2421,6 +2435,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -2572,6 +2587,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -2723,6 +2739,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -2874,6 +2891,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -3023,6 +3041,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -3174,6 +3193,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -3325,6 +3345,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -3476,6 +3497,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -3627,6 +3649,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -3778,6 +3801,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -3927,6 +3951,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, @@ -4005,6 +4030,7 @@ macro_rules! default_imp_for_new_connector_integration_frm { #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm!( + connectors::Loonio, connectors::Gigadat, connectors::Affirm, connectors::Paytm, @@ -4153,6 +4179,7 @@ macro_rules! default_imp_for_new_connector_integration_connector_authentication } default_imp_for_new_connector_integration_connector_authentication!( + connectors::Loonio, connectors::Gigadat, connectors::Affirm, connectors::Paytm, @@ -4290,6 +4317,7 @@ macro_rules! default_imp_for_new_connector_integration_revenue_recovery { } default_imp_for_new_connector_integration_revenue_recovery!( + connectors::Loonio, connectors::Gigadat, connectors::Affirm, connectors::Paytm, @@ -4500,6 +4528,7 @@ default_imp_for_new_connector_integration_external_vault!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, @@ -4648,6 +4677,7 @@ default_imp_for_new_connector_integration_external_vault_proxy!( connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, + connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rs index a1514c01bc4..5847ba826e2 100644 --- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs +++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs @@ -79,6 +79,7 @@ pub struct Connectors { pub cardinal: NoParams, pub katapult: ConnectorParams, pub klarna: ConnectorParams, + pub loonio: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 78ed84edf3f..b4eab9ea6e2 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -26,24 +26,25 @@ pub use hyperswitch_connectors::connectors::{ hyperswitch_vault::HyperswitchVault, hyperwallet, hyperwallet::Hyperwallet, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, katapult, - katapult::Katapult, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, mollie, - mollie::Mollie, moneris, moneris::Moneris, mpgs, mpgs::Mpgs, multisafepay, - multisafepay::Multisafepay, netcetera, netcetera::Netcetera, nexinets, nexinets::Nexinets, - nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, - nordea, nordea::Nordea, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, - opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payload, - payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paysafe, - paysafe::Paysafe, paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, - peachpayments, peachpayments::Peachpayments, phonepe, phonepe::Phonepe, placetopay, - placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, - prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, - recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, santander, - santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, - silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, - stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, tesouro, - tesouro::Tesouro, threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, - tokenex, tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, - trustpayments, trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, + katapult::Katapult, klarna, klarna::Klarna, loonio, loonio::Loonio, mifinity, + mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, mpgs, mpgs::Mpgs, + multisafepay, multisafepay::Multisafepay, netcetera, netcetera::Netcetera, nexinets, + nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, nomupay::Nomupay, + noon, noon::Noon, nordea, nordea::Nordea, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, + opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, + payeezy::Payeezy, payload, payload::Payload, payme, payme::Payme, payone, payone::Payone, + paypal, paypal::Paypal, paysafe, paysafe::Paysafe, paystack, paystack::Paystack, paytm, + paytm::Paytm, payu, payu::Payu, peachpayments, peachpayments::Peachpayments, phonepe, + phonepe::Phonepe, placetopay, placetopay::Placetopay, plaid, plaid::Plaid, powertranz, + powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, + razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, riskified, + riskified::Riskified, santander, santander::Santander, shift4, shift4::Shift4, sift, + sift::Sift, signifyd, signifyd::Signifyd, silverflow, silverflow::Silverflow, square, + square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, + stripebilling::Stripebilling, taxjar, taxjar::Taxjar, tesouro, tesouro::Tesouro, + threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, + tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, + trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, diff --git a/crates/router/tests/connectors/loonio.rs b/crates/router/tests/connectors/loonio.rs new file mode 100644 index 00000000000..c9756e22807 --- /dev/null +++ b/crates/router/tests/connectors/loonio.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 LoonioTest; +impl ConnectorActions for LoonioTest {} +impl utils::Connector for LoonioTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Loonio; + utils::construct_connector_data_old( + Box::new(Loonio::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .loonio + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "loonio".to_string() + } +} + +static CONNECTOR: LoonioTest = LoonioTest {}; + +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 9738f6a2b72..a43b1ef45f2 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -65,6 +65,7 @@ mod itaubank; mod jpmorgan; mod juspaythreedsserver; mod katapult; +mod loonio; mod mifinity; mod mollie; mod moneris; diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index fbcded72d56..1f4dbbef0f9 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -75,6 +75,7 @@ pub struct ConnectorAuthentication { pub jpmorgan: Option<BodyKey>, pub juspaythreedsserver: Option<HeaderKey>, pub katapult: Option<HeaderKey>, + pub loonio: Option<HeaderKey>, pub mifinity: Option<HeaderKey>, pub mollie: Option<BodyKey>, pub moneris: Option<SignatureKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 695a9593e26..0ad216f4486 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -146,6 +146,7 @@ juspaythreedsserver.base_url = "http://localhost:8000" katapult.base_url = "https://sandbox.katapult.com/api/v3" jpmorgan.secondary_base_url = "https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" +loonio.base_url = "https://loonio.ca/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 4e16b0b7357..38269ef8f5d 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 affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay finix fiserv fiservemea fiuu flexiti forte getnet gigadat globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar tesouro threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay finix fiserv fiservemea fiuu flexiti forte getnet gigadat globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna loonio mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar tesouro threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
2025-09-28T19:27:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add template code for Loonio connector ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? No test required as it is template code ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e45bad38d602634c1bf9019978545f28ba19db23
juspay/hyperswitch
juspay__hyperswitch-9589
Bug: Create a payments API client to connect subscription service with payments
diff --git a/config/config.example.toml b/config/config.example.toml index 1b767adb4eb..d588c22a638 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1279,4 +1279,7 @@ connector_list = "worldpayvantiv" # Authentication to communicate between internal services using common_api_key, merchant id and profile id [internal_merchant_id_profile_id_auth] enabled = false # Enable or disable internal api key, merchant id and profile id based authentication -internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication + +[internal_services] # Internal services base urls and configs +payments_base_url = "http://localhost:8080" diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index d48ab2d148d..b8523401448 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -428,3 +428,6 @@ encryption_key = "" # Key to encrypt and decrypt chat [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response + +[internal_services] # Internal services base urls and configs +payments_base_url = "http://localhost:8080" \ No newline at end of file diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 2128079b3d3..bde1e29ba78 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -920,8 +920,3 @@ connector_list = "worldpayvantiv" [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call - -# Authentication to communicate between internal services using common_api_key, merchant id and profile id -[internal_merchant_id_profile_id_auth] -enabled = false # Enable or disable internal api key, merchant id and profile id based authentication -internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/config/deployments/production.toml b/config/deployments/production.toml index c7c85bc1f85..e078e4c50cf 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -926,8 +926,3 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call - -# Authentication to communicate between internal services using common_api_key, merchant id and profile id -[internal_merchant_id_profile_id_auth] -enabled = false # Enable or disable internal api key, merchant id and profile id based authentication -internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 916636bcc45..4c777e8a62f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -935,8 +935,3 @@ connector_list = "worldpayvantiv" [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call - -# Authentication to communicate between internal services using common_api_key, merchant id and profile id -[internal_merchant_id_profile_id_auth] -enabled = false # Enable or disable internal api key, merchant id and profile id based authentication -internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/config/development.toml b/config/development.toml index a82fe46afd9..6d468c4656d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1399,4 +1399,7 @@ connector_list = "worldpayvantiv" [internal_merchant_id_profile_id_auth] enabled = false -internal_api_key = "test_internal_api_key" \ No newline at end of file +internal_api_key = "test_internal_api_key" + +[internal_services] +payments_base_url = "http://localhost:8080" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index e4f7197c04d..86e82aaf487 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1291,4 +1291,7 @@ connector_list = "worldpayvantiv" # Authentication to communicate between internal services using common_api_key, merchant id and profile id [internal_merchant_id_profile_id_auth] enabled = false # Enable or disable internal api key, merchant id and profile id based authentication -internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication + +[internal_services] # Internal services base urls and configs +payments_base_url = "http://localhost:8080" diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs index 4ed14a9c64e..c0403848b9d 100644 --- a/crates/api_models/src/subscription.rs +++ b/crates/api_models/src/subscription.rs @@ -8,17 +8,18 @@ use crate::{ payments::{Address, PaymentMethodDataRequest}, }; -// use crate::{ -// customers::{CustomerRequest, CustomerResponse}, -// payments::CustomerDetailsResponse, -// }; - /// Request payload for creating a subscription. /// /// This struct captures details required to create a subscription, /// including plan, profile, merchant connector, and optional customer info. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateSubscriptionRequest { + /// Amount to be charged for the invoice. + pub amount: MinorUnit, + + /// Currency for the amount. + pub currency: api_enums::Currency, + /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, @@ -30,13 +31,22 @@ pub struct CreateSubscriptionRequest { /// customer ID associated with this subscription. pub customer_id: common_utils::id_type::CustomerId, + + /// payment details for the subscription. + pub payment_details: CreateSubscriptionPaymentDetails, + + /// billing address for the subscription. + pub billing: Option<Address>, + + /// shipping address for the subscription. + pub shipping: Option<Address>, } /// Response payload returned after successfully creating a subscription. /// /// Includes details such as subscription ID, status, plan, merchant, and customer info. #[derive(Debug, Clone, serde::Serialize, ToSchema)] -pub struct CreateSubscriptionResponse { +pub struct SubscriptionResponse { /// Unique identifier for the subscription. pub id: common_utils::id_type::SubscriptionId, @@ -78,6 +88,7 @@ pub struct CreateSubscriptionResponse { /// - `Cancelled`: Subscription has been cancelled. /// - `Failed`: Subscription has failed. #[derive(Debug, Clone, serde::Serialize, strum::EnumString, strum::Display, ToSchema)] +#[serde(rename_all = "snake_case")] pub enum SubscriptionStatus { /// Subscription is active. Active, @@ -101,7 +112,7 @@ pub enum SubscriptionStatus { Failed, } -impl CreateSubscriptionResponse { +impl SubscriptionResponse { /// Creates a new [`CreateSubscriptionResponse`] with the given identifiers. /// /// By default, `client_secret`, `coupon_code`, and `customer` fields are `None`. @@ -130,15 +141,77 @@ impl CreateSubscriptionResponse { } } -impl ApiEventMetric for CreateSubscriptionResponse {} +impl ApiEventMetric for SubscriptionResponse {} impl ApiEventMetric for CreateSubscriptionRequest {} +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct ConfirmSubscriptionPaymentDetails { + pub payment_method: api_enums::PaymentMethod, + pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub payment_method_data: PaymentMethodDataRequest, + pub customer_acceptance: Option<CustomerAcceptance>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct CreateSubscriptionPaymentDetails { + pub return_url: common_utils::types::Url, + pub setup_future_usage: Option<api_enums::FutureUsage>, + pub capture_method: Option<api_enums::CaptureMethod>, + pub authentication_type: Option<api_enums::AuthenticationType>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentDetails { + pub payment_method: Option<api_enums::PaymentMethod>, + pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub payment_method_data: Option<PaymentMethodDataRequest>, + pub setup_future_usage: Option<api_enums::FutureUsage>, + pub customer_acceptance: Option<CustomerAcceptance>, + pub return_url: Option<common_utils::types::Url>, + pub capture_method: Option<api_enums::CaptureMethod>, + pub authentication_type: Option<api_enums::AuthenticationType>, +} + +// Creating new type for PaymentRequest API call as usage of api_models::PaymentsRequest will result in invalid payment request during serialization +// Eg: Amount will be serialized as { amount: {Value: 100 }} +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct CreatePaymentsRequestData { + pub amount: MinorUnit, + pub currency: api_enums::Currency, + pub customer_id: Option<common_utils::id_type::CustomerId>, + pub billing: Option<Address>, + pub shipping: Option<Address>, + pub setup_future_usage: Option<api_enums::FutureUsage>, + pub return_url: Option<common_utils::types::Url>, + pub capture_method: Option<api_enums::CaptureMethod>, + pub authentication_type: Option<api_enums::AuthenticationType>, +} + +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct ConfirmPaymentsRequestData { + pub billing: Option<Address>, + pub shipping: Option<Address>, pub payment_method: api_enums::PaymentMethod, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, + pub customer_acceptance: Option<CustomerAcceptance>, +} + +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct CreateAndConfirmPaymentsRequestData { + pub amount: MinorUnit, + pub currency: api_enums::Currency, + pub customer_id: Option<common_utils::id_type::CustomerId>, + pub confirm: bool, + pub billing: Option<Address>, + pub shipping: Option<Address>, pub setup_future_usage: Option<api_enums::FutureUsage>, + pub return_url: Option<common_utils::types::Url>, + pub capture_method: Option<api_enums::CaptureMethod>, + pub authentication_type: Option<api_enums::AuthenticationType>, + pub payment_method: Option<api_enums::PaymentMethod>, + pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub payment_method_data: Option<PaymentMethodDataRequest>, pub customer_acceptance: Option<CustomerAcceptance>, } @@ -149,18 +222,16 @@ pub struct PaymentResponseData { pub amount: MinorUnit, pub currency: api_enums::Currency, pub connector: Option<String>, + pub payment_method_id: Option<Secret<String>>, + pub payment_experience: Option<api_enums::PaymentExperience>, + pub error_code: Option<String>, + pub error_message: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionRequest { /// Client secret for SDK based interaction. pub client_secret: Option<String>, - /// Amount to be charged for the invoice. - pub amount: MinorUnit, - - /// Currency for the amount. - pub currency: api_enums::Currency, - /// Identifier for the associated plan_id. pub plan_id: Option<String>, @@ -174,10 +245,13 @@ pub struct ConfirmSubscriptionRequest { pub customer_id: common_utils::id_type::CustomerId, /// Billing address for the subscription. - pub billing_address: Option<Address>, + pub billing: Option<Address>, + + /// Shipping address for the subscription. + pub shipping: Option<Address>, /// Payment details for the invoice. - pub payment_details: PaymentDetails, + pub payment_details: ConfirmSubscriptionPaymentDetails, } impl ConfirmSubscriptionRequest { @@ -190,9 +264,9 @@ impl ConfirmSubscriptionRequest { } pub fn get_billing_address(&self) -> Result<Address, error_stack::Report<ValidationError>> { - self.billing_address.clone().ok_or(error_stack::report!( + self.billing.clone().ok_or(error_stack::report!( ValidationError::MissingRequiredField { - field_name: "billing_address".to_string() + field_name: "billing".to_string() } )) } @@ -200,6 +274,41 @@ impl ConfirmSubscriptionRequest { impl ApiEventMetric for ConfirmSubscriptionRequest {} +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct CreateAndConfirmSubscriptionRequest { + /// Amount to be charged for the invoice. + pub amount: Option<MinorUnit>, + + /// Currency for the amount. + pub currency: Option<api_enums::Currency>, + + /// Identifier for the associated plan_id. + pub plan_id: Option<String>, + + /// Identifier for the associated item_price_id for the subscription. + pub item_price_id: Option<String>, + + /// Idenctifier for the coupon code for the subscription. + pub coupon_code: Option<String>, + + /// Identifier for customer. + pub customer_id: common_utils::id_type::CustomerId, + + /// Billing address for the subscription. + pub billing: Option<Address>, + + /// Shipping address for the subscription. + pub shipping: Option<Address>, + + /// Payment details for the invoice. + pub payment_details: PaymentDetails, + + /// Merchant specific Unique identifier. + pub merchant_reference_id: Option<String>, +} + +impl ApiEventMetric for CreateAndConfirmSubscriptionRequest {} + #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ConfirmSubscriptionResponse { /// Unique identifier for the subscription. @@ -231,6 +340,9 @@ pub struct ConfirmSubscriptionResponse { /// Invoice Details for the subscription. pub invoice: Option<Invoice>, + + /// Billing Processor subscription ID. + pub billing_processor_subscription_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 51dc6469424..532123c3501 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -894,7 +894,8 @@ impl TryFrom<Connector> for RoutableConnectors { } // Enum representing different status an invoice can have. -#[derive(Debug, Clone, PartialEq, Eq, strum::Display, strum::EnumString)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, strum::Display, strum::EnumString)] +#[strum(serialize_all = "snake_case")] pub enum InvoiceStatus { InvoiceCreated, PaymentPending, @@ -904,4 +905,5 @@ pub enum InvoiceStatus { PaymentCanceled, InvoicePaid, ManualReview, + Voided, } diff --git a/crates/common_utils/src/id_type/subscription.rs b/crates/common_utils/src/id_type/subscription.rs index 20f0c483fa1..abccf711787 100644 --- a/crates/common_utils/src/id_type/subscription.rs +++ b/crates/common_utils/src/id_type/subscription.rs @@ -9,7 +9,7 @@ crate::impl_id_type_methods!(SubscriptionId, "subscription_id"); crate::impl_debug_id_type!(SubscriptionId); crate::impl_try_from_cow_str_id_type!(SubscriptionId, "subscription_id"); -crate::impl_generate_id_id_type!(SubscriptionId, "subscription"); +crate::impl_generate_id_id_type!(SubscriptionId, "sub"); crate::impl_serializable_secret_id_type!(SubscriptionId); crate::impl_queryable_id_type!(SubscriptionId); crate::impl_to_sql_from_sql_id_type!(SubscriptionId); diff --git a/crates/diesel_models/src/query/invoice.rs b/crates/diesel_models/src/query/invoice.rs index 10df8620461..0166469d340 100644 --- a/crates/diesel_models/src/query/invoice.rs +++ b/crates/diesel_models/src/query/invoice.rs @@ -38,4 +38,32 @@ impl Invoice { >(conn, dsl::id.eq(id.to_owned()), invoice_update) .await } + + pub async fn list_invoices_by_subscription_id( + conn: &PgPooledConn, + subscription_id: String, + limit: Option<i64>, + offset: Option<i64>, + order_by_ascending_order: bool, + ) -> StorageResult<Vec<Self>> { + if order_by_ascending_order { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::subscription_id.eq(subscription_id.to_owned()), + limit, + offset, + Some(dsl::created_at.asc()), + ) + .await + } else { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::subscription_id.eq(subscription_id.to_owned()), + limit, + offset, + Some(dsl::created_at.desc()), + ) + .await + } + } } diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rs index 96a41f10ca0..98589804a35 100644 --- a/crates/diesel_models/src/query/utils.rs +++ b/crates/diesel_models/src/query/utils.rs @@ -103,6 +103,7 @@ impl_get_primary_key!( schema::events::table, schema::merchant_account::table, schema::process_tracker::table, + schema::invoice::table, // v2 tables schema_v2::dashboard_metadata::table, schema_v2::merchant_connector_account::table, diff --git a/crates/diesel_models/src/subscription.rs b/crates/diesel_models/src/subscription.rs index f49fef4a7be..7124c2eebd6 100644 --- a/crates/diesel_models/src/subscription.rs +++ b/crates/diesel_models/src/subscription.rs @@ -1,6 +1,6 @@ use common_utils::{generate_id_with_default_len, pii::SecretSerdeValue}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::schema::subscription; @@ -48,6 +48,7 @@ pub struct Subscription { #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, Deserialize)] #[diesel(table_name = subscription)] pub struct SubscriptionUpdate { + pub connector_subscription_id: Option<String>, pub payment_method_id: Option<String>, pub status: Option<String>, pub modified_at: time::PrimitiveDateTime, @@ -97,10 +98,15 @@ impl SubscriptionNew { } impl SubscriptionUpdate { - pub fn new(payment_method_id: Option<String>, status: Option<String>) -> Self { + pub fn new( + payment_method_id: Option<Secret<String>>, + status: Option<String>, + connector_subscription_id: Option<String>, + ) -> Self { Self { - payment_method_id, + payment_method_id: payment_method_id.map(|pmid| pmid.peek().clone()), status, + connector_subscription_id, modified_at: common_utils::date_time::now(), } } diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 3bf78b0e68b..64d9431c195 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -1,7 +1,7 @@ #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use std::str::FromStr; -use common_enums::enums; +use common_enums::{connector_enums, enums}; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, @@ -29,8 +29,8 @@ use hyperswitch_domain_models::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ self, GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, - GetSubscriptionPlansResponse, SubscriptionCreateResponse, SubscriptionLineItem, - SubscriptionStatus, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, SubscriptionInvoiceData, + SubscriptionLineItem, SubscriptionStatus, }, ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData, }, @@ -120,6 +120,7 @@ impl TryFrom<&ChargebeeRouterData<&hyperswitch_domain_models::types::Subscriptio #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ChargebeeSubscriptionCreateResponse { pub subscription: ChargebeeSubscriptionDetails, + pub invoice: Option<ChargebeeInvoiceData>, } #[derive(Debug, Deserialize, Serialize, Clone)] @@ -192,6 +193,7 @@ impl total_amount: subscription.total_dues.unwrap_or(MinorUnit::new(0)), next_billing_at: subscription.next_billing_at, created_at: subscription.created_at, + invoice_details: item.response.invoice.map(SubscriptionInvoiceData::from), }), ..item.data }) @@ -461,17 +463,18 @@ pub enum ChargebeeEventType { InvoiceDeleted, } -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug)] pub struct ChargebeeInvoiceData { // invoice id pub id: String, pub total: MinorUnit, pub currency_code: enums::Currency, + pub status: Option<ChargebeeInvoiceStatus>, pub billing_address: Option<ChargebeeInvoiceBillingAddress>, pub linked_payments: Option<Vec<ChargebeeInvoicePayments>>, } -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug)] pub struct ChargebeeInvoicePayments { pub txn_status: Option<String>, } @@ -539,7 +542,7 @@ pub struct ChargebeeCustomer { pub payment_method: ChargebeePaymentMethod, } -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug)] pub struct ChargebeeInvoiceBillingAddress { pub line1: Option<Secret<String>>, pub line2: Option<Secret<String>>, @@ -788,7 +791,6 @@ impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceD } } -#[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl From<ChargebeeInvoiceData> for api_models::payments::Address { fn from(item: ChargebeeInvoiceData) -> Self { Self { @@ -801,7 +803,6 @@ impl From<ChargebeeInvoiceData> for api_models::payments::Address { } } -#[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl From<ChargebeeInvoiceBillingAddress> for api_models::payments::AddressDetails { fn from(item: ChargebeeInvoiceBillingAddress) -> Self { Self { @@ -1337,3 +1338,40 @@ pub struct LineItem { pub discount_amount: MinorUnit, pub item_level_discount_amount: MinorUnit, } + +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "snake_case")] +pub enum ChargebeeInvoiceStatus { + Paid, + Posted, + PaymentDue, + NotPaid, + Voided, + #[serde(other)] + Pending, +} + +impl From<ChargebeeInvoiceData> for SubscriptionInvoiceData { + fn from(item: ChargebeeInvoiceData) -> Self { + Self { + billing_address: Some(api_models::payments::Address::from(item.clone())), + id: item.id, + total: item.total, + currency_code: item.currency_code, + status: item.status.map(connector_enums::InvoiceStatus::from), + } + } +} + +impl From<ChargebeeInvoiceStatus> for connector_enums::InvoiceStatus { + fn from(status: ChargebeeInvoiceStatus) -> Self { + match status { + ChargebeeInvoiceStatus::Paid => Self::InvoicePaid, + ChargebeeInvoiceStatus::Posted => Self::PaymentPendingTimeout, + ChargebeeInvoiceStatus::PaymentDue => Self::PaymentPending, + ChargebeeInvoiceStatus::NotPaid => Self::PaymentFailed, + ChargebeeInvoiceStatus::Voided => Self::Voided, + ChargebeeInvoiceStatus::Pending => Self::InvoiceCreated, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs index 73b80b82075..e60b7783cb5 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs @@ -11,6 +11,16 @@ pub struct SubscriptionCreateResponse { pub total_amount: MinorUnit, pub next_billing_at: Option<PrimitiveDateTime>, pub created_at: Option<PrimitiveDateTime>, + pub invoice_details: Option<SubscriptionInvoiceData>, +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct SubscriptionInvoiceData { + pub id: String, + pub total: MinorUnit, + pub currency_code: Currency, + pub status: Option<common_enums::connector_enums::InvoiceStatus>, + pub billing_address: Option<api_models::payments::Address>, } #[derive(Debug, Clone, PartialEq, Eq, Copy)] diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 67b6854922a..7aef8d74464 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -580,5 +580,6 @@ pub(crate) async fn fetch_raw_secrets( infra_values: conf.infra_values, enhancement: conf.enhancement, proxy_status_mapping: conf.proxy_status_mapping, + internal_services: conf.internal_services, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 6a7bf225473..2dd028cf72e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -169,6 +169,7 @@ pub struct Settings<S: SecretState> { #[serde(default)] pub enhancement: Option<HashMap<String, String>>, pub proxy_status_mapping: ProxyStatusMapping, + pub internal_services: InternalServicesConfig, } #[derive(Debug, Deserialize, Clone, Default)] @@ -972,6 +973,12 @@ pub struct NetworkTokenizationSupportedConnectors { pub connector_list: HashSet<enums::Connector>, } +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] +pub struct InternalServicesConfig { + pub payments_base_url: String, +} + impl Settings<SecuredSecret> { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 6b98eabf8bb..71e32c43bf6 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -1,148 +1,167 @@ -use std::str::FromStr; - -use api_models::{ - enums as api_enums, - subscription::{self as subscription_types, CreateSubscriptionResponse, SubscriptionStatus}, +use api_models::subscription::{ + self as subscription_types, SubscriptionResponse, SubscriptionStatus, }; -use common_utils::{ext_traits::ValueExt, id_type::GenerateId, pii}; -use diesel_models::subscription::SubscriptionNew; +use common_enums::connector_enums; +use common_utils::id_type::GenerateId; use error_stack::ResultExt; -use hyperswitch_domain_models::{ - api::ApplicationResponse, - merchant_context::MerchantContext, - router_data_v2::flow_common_types::{SubscriptionCreateData, SubscriptionCustomerData}, - router_request_types::{subscriptions as subscription_request_types, ConnectorCustomerData}, - router_response_types::{ - subscriptions as subscription_response_types, ConnectorCustomerResponseData, - PaymentsResponseData, - }, -}; -use masking::Secret; +use hyperswitch_domain_models::{api::ApplicationResponse, merchant_context::MerchantContext}; use super::errors::{self, RouterResponse}; use crate::{ - core::payments as payments_core, routes::SessionState, services, types::api as api_types, + core::subscription::{ + billing_processor_handler::BillingHandler, invoice_handler::InvoiceHandler, + subscription_handler::SubscriptionHandler, + }, + routes::SessionState, }; +pub mod billing_processor_handler; +pub mod invoice_handler; +pub mod payments_api_client; +pub mod subscription_handler; + pub const SUBSCRIPTION_CONNECTOR_ID: &str = "DefaultSubscriptionConnectorId"; pub const SUBSCRIPTION_PAYMENT_ID: &str = "DefaultSubscriptionPaymentId"; pub async fn create_subscription( state: SessionState, merchant_context: MerchantContext, - profile_id: String, + profile_id: common_utils::id_type::ProfileId, request: subscription_types::CreateSubscriptionRequest, -) -> RouterResponse<CreateSubscriptionResponse> { - let store = state.store.clone(); - let db = store.as_ref(); - let id = common_utils::id_type::SubscriptionId::generate(); - let profile_id = common_utils::id_type::ProfileId::from_str(&profile_id).change_context( - errors::ApiErrorResponse::InvalidDataValue { - field_name: "X-Profile-Id", - }, - )?; - - let mut subscription = SubscriptionNew::new( - id, - SubscriptionStatus::Created.to_string(), - None, - None, - None, - None, - None, - merchant_context.get_merchant_account().get_id().clone(), - request.customer_id.clone(), - None, - profile_id, - request.merchant_reference_id, - ); +) -> RouterResponse<SubscriptionResponse> { + let subscription_id = common_utils::id_type::SubscriptionId::generate(); - subscription.generate_and_set_client_secret(); - let subscription_response = db - .insert_subscription_entry(subscription) + let profile = + SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) + .await + .attach_printable("subscriptions: failed to find business profile")?; + let customer = + SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id) + .await + .attach_printable("subscriptions: failed to find customer")?; + let billing_handler = + BillingHandler::create(&state, &merchant_context, customer, profile.clone()).await?; + + let subscription_handler = SubscriptionHandler::new(&state, &merchant_context, profile); + let mut subscription = subscription_handler + .create_subscription_entry( + subscription_id, + &request.customer_id, + billing_handler.connector_data.connector_name, + billing_handler.merchant_connector_id.clone(), + request.merchant_reference_id.clone(), + ) + .await + .attach_printable("subscriptions: failed to create subscription entry")?; + let invoice_handler = subscription.get_invoice_handler(); + let payment = invoice_handler + .create_payment_with_confirm_false(subscription.handler.state, &request) + .await + .attach_printable("subscriptions: failed to create payment")?; + invoice_handler + .create_invoice_entry( + &state, + billing_handler.merchant_connector_id, + Some(payment.payment_id.clone()), + request.amount, + request.currency, + connector_enums::InvoiceStatus::InvoiceCreated, + billing_handler.connector_data.connector_name, + None, + ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("subscriptions: unable to insert subscription entry to database")?; + .attach_printable("subscriptions: failed to create invoice")?; - let response = CreateSubscriptionResponse::new( - subscription_response.id.clone(), - subscription_response.merchant_reference_id, - SubscriptionStatus::from_str(&subscription_response.status) - .unwrap_or(SubscriptionStatus::Created), - None, - subscription_response.profile_id, - subscription_response.merchant_id, - subscription_response.client_secret.map(Secret::new), - request.customer_id, - ); + subscription + .update_subscription(diesel_models::subscription::SubscriptionUpdate::new( + payment.payment_method_id.clone(), + None, + None, + )) + .await + .attach_printable("subscriptions: failed to update subscription")?; - Ok(ApplicationResponse::Json(response)) + Ok(ApplicationResponse::Json( + subscription.to_subscription_response(), + )) } -pub async fn confirm_subscription( +/// Creates and confirms a subscription in one operation. +/// This method combines the creation and confirmation flow to reduce API calls +pub async fn create_and_confirm_subscription( state: SessionState, merchant_context: MerchantContext, - profile_id: String, - request: subscription_types::ConfirmSubscriptionRequest, - subscription_id: common_utils::id_type::SubscriptionId, + profile_id: common_utils::id_type::ProfileId, + request: subscription_types::CreateAndConfirmSubscriptionRequest, ) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { - let profile_id = common_utils::id_type::ProfileId::from_str(&profile_id).change_context( - errors::ApiErrorResponse::InvalidDataValue { - field_name: "X-Profile-Id", - }, - )?; - - let key_manager_state = &(&state).into(); - let merchant_key_store = merchant_context.get_merchant_key_store(); + let subscription_id = common_utils::id_type::SubscriptionId::generate(); - let profile = state - .store - .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, &profile_id) - .await - .change_context(errors::ApiErrorResponse::ProfileNotFound { - id: profile_id.get_string_repr().to_string(), - })?; - - let customer = state - .store - .find_customer_by_customer_id_merchant_id( - key_manager_state, + let profile = + SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) + .await + .attach_printable("subscriptions: failed to find business profile")?; + let customer = + SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id) + .await + .attach_printable("subscriptions: failed to find customer")?; + + let billing_handler = + BillingHandler::create(&state, &merchant_context, customer, profile.clone()).await?; + let subscription_handler = SubscriptionHandler::new(&state, &merchant_context, profile.clone()); + let mut subs_handler = subscription_handler + .create_subscription_entry( + subscription_id.clone(), &request.customer_id, - merchant_context.get_merchant_account().get_id(), - merchant_key_store, - merchant_context.get_merchant_account().storage_scheme, + billing_handler.connector_data.connector_name, + billing_handler.merchant_connector_id.clone(), + request.merchant_reference_id.clone(), ) .await - .change_context(errors::ApiErrorResponse::CustomerNotFound) - .attach_printable("subscriptions: unable to fetch customer from database")?; - - let handler = SubscriptionHandler::new(state, merchant_context, request, profile); - - let mut subscription_entry = handler - .find_subscription(subscription_id.get_string_repr().to_string()) - .await?; - - let billing_handler = subscription_entry.get_billing_handler(customer).await?; - let invoice_handler = subscription_entry.get_invoice_handler().await?; + .attach_printable("subscriptions: failed to create subscription entry")?; + let invoice_handler = subs_handler.get_invoice_handler(); let _customer_create_response = billing_handler - .create_customer_on_connector(&handler.state) + .create_customer_on_connector( + &state, + request.customer_id.clone(), + request.billing.clone(), + request + .payment_details + .payment_method_data + .clone() + .and_then(|data| data.payment_method_data), + ) .await?; let subscription_create_response = billing_handler - .create_subscription_on_connector(&handler.state) + .create_subscription_on_connector( + &state, + subs_handler.subscription.clone(), + request.item_price_id.clone(), + request.billing.clone(), + ) .await?; - // let payment_response = invoice_handler.create_cit_payment().await?; + let invoice_details = subscription_create_response.invoice_details; + let (amount, currency) = InvoiceHandler::get_amount_and_currency( + (request.amount, request.currency), + invoice_details.clone(), + ); + + let payment_response = invoice_handler + .create_and_confirm_payment(&state, &request, amount, currency) + .await?; let invoice_entry = invoice_handler .create_invoice_entry( - &handler.state, - subscription_entry.profile.get_billing_processor_id()?, - None, - billing_handler.request.amount, - billing_handler.request.currency.to_string(), - common_enums::connector_enums::InvoiceStatus::InvoiceCreated, + &state, + profile.get_billing_processor_id()?, + Some(payment_response.payment_id.clone()), + amount, + currency, + invoice_details + .and_then(|invoice| invoice.status) + .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), billing_handler.connector_data.connector_name, None, ) @@ -152,470 +171,144 @@ pub async fn confirm_subscription( // .create_invoice_record_back_job(&payment_response) // .await?; - subscription_entry - .update_subscription_status( - SubscriptionStatus::from(subscription_create_response.status).to_string(), - ) + subs_handler + .update_subscription(diesel_models::subscription::SubscriptionUpdate::new( + payment_response.payment_method_id.clone(), + Some(SubscriptionStatus::from(subscription_create_response.status).to_string()), + Some( + subscription_create_response + .subscription_id + .get_string_repr() + .to_string(), + ), + )) .await?; - let response = subscription_entry - .generate_response(&invoice_entry, subscription_create_response.status)?; + let response = subs_handler.generate_response( + &invoice_entry, + &payment_response, + subscription_create_response.status, + )?; Ok(ApplicationResponse::Json(response)) } -pub struct SubscriptionHandler { +pub async fn confirm_subscription( state: SessionState, merchant_context: MerchantContext, + profile_id: common_utils::id_type::ProfileId, request: subscription_types::ConfirmSubscriptionRequest, - profile: hyperswitch_domain_models::business_profile::Profile, -} - -impl SubscriptionHandler { - pub fn new( - state: SessionState, - merchant_context: MerchantContext, - request: subscription_types::ConfirmSubscriptionRequest, - profile: hyperswitch_domain_models::business_profile::Profile, - ) -> Self { - Self { - state, - merchant_context, - request, - profile, - } - } - pub async fn find_subscription( - &self, - subscription_id: String, - ) -> errors::RouterResult<SubscriptionWithHandler<'_>> { - let subscription = self - .state - .store - .find_by_merchant_id_subscription_id( - self.merchant_context.get_merchant_account().get_id(), - subscription_id.clone(), - ) - .await - .change_context(errors::ApiErrorResponse::GenericNotFoundError { - message: format!("subscription not found for id: {subscription_id}"), - })?; - - Ok(SubscriptionWithHandler { - handler: self, - subscription, - profile: self.profile.clone(), - }) - } -} -pub struct SubscriptionWithHandler<'a> { - handler: &'a SubscriptionHandler, - subscription: diesel_models::subscription::Subscription, - profile: hyperswitch_domain_models::business_profile::Profile, -} - -impl SubscriptionWithHandler<'_> { - fn generate_response( - &self, - invoice: &diesel_models::invoice::Invoice, - // _payment_response: &subscription_types::PaymentResponseData, - status: subscription_response_types::SubscriptionStatus, - ) -> errors::RouterResult<subscription_types::ConfirmSubscriptionResponse> { - Ok(subscription_types::ConfirmSubscriptionResponse { - id: self.subscription.id.clone(), - merchant_reference_id: self.subscription.merchant_reference_id.clone(), - status: SubscriptionStatus::from(status), - plan_id: None, - profile_id: self.subscription.profile_id.to_owned(), - payment: None, - customer_id: Some(self.subscription.customer_id.clone()), - price_id: None, - coupon: None, - invoice: Some(subscription_types::Invoice { - id: invoice.id.clone(), - subscription_id: invoice.subscription_id.clone(), - merchant_id: invoice.merchant_id.clone(), - profile_id: invoice.profile_id.clone(), - merchant_connector_id: invoice.merchant_connector_id.clone(), - payment_intent_id: invoice.payment_intent_id.clone(), - payment_method_id: invoice.payment_method_id.clone(), - customer_id: invoice.customer_id.clone(), - amount: invoice.amount, - currency: api_enums::Currency::from_str(invoice.currency.as_str()) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "currency", - }) - .attach_printable(format!( - "unable to parse currency name {currency:?}", - currency = invoice.currency - ))?, - status: invoice.status.clone(), - }), - }) - } - - async fn update_subscription_status(&mut self, status: String) -> errors::RouterResult<()> { - let db = self.handler.state.store.as_ref(); - let updated_subscription = db - .update_subscription_entry( - self.handler - .merchant_context - .get_merchant_account() - .get_id(), - self.subscription.id.get_string_repr().to_string(), - diesel_models::subscription::SubscriptionUpdate::new(None, Some(status)), - ) + subscription_id: common_utils::id_type::SubscriptionId, +) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { + // Find the subscription from database + let profile = + SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await - .change_context(errors::ApiErrorResponse::SubscriptionError { - operation: "Subscription Update".to_string(), - }) - .attach_printable("subscriptions: unable to update subscription entry in database")?; - - self.subscription = updated_subscription; - - Ok(()) - } - - pub async fn get_billing_handler( - &self, - customer: hyperswitch_domain_models::customer::Customer, - ) -> errors::RouterResult<BillingHandler> { - let mca_id = self.profile.get_billing_processor_id()?; - - let billing_processor_mca = self - .handler - .state - .store - .find_by_merchant_connector_account_merchant_id_merchant_connector_id( - &(&self.handler.state).into(), - self.handler - .merchant_context - .get_merchant_account() - .get_id(), - &mca_id, - self.handler.merchant_context.get_merchant_key_store(), - ) + .attach_printable("subscriptions: failed to find business profile")?; + let customer = + SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id) .await - .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { - id: mca_id.get_string_repr().to_string(), - })?; - - let connector_name = billing_processor_mca.connector_name.clone(); - - let auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType = - payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new( - billing_processor_mca.clone(), - )) - .get_connector_account_details() - .parse_value("ConnectorAuthType") - .change_context(errors::ApiErrorResponse::InvalidDataFormat { - field_name: "connector_account_details".to_string(), - expected_format: "auth_type and api_key".to_string(), - })?; + .attach_printable("subscriptions: failed to find customer")?; - let connector_data = api_types::ConnectorData::get_connector_by_name( - &self.handler.state.conf.connectors, - &connector_name, - api_types::GetToken::Connector, - Some(billing_processor_mca.get_id()), + let handler = SubscriptionHandler::new(&state, &merchant_context, profile.clone()); + let mut subscription_entry = handler.find_subscription(subscription_id).await?; + let invoice_handler = subscription_entry.get_invoice_handler(); + let invoice = invoice_handler + .get_latest_invoice(&state) + .await + .attach_printable("subscriptions: failed to get latest invoice")?; + let payment_response = invoice_handler + .confirm_payment( + &state, + invoice + .payment_intent_id + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "payment_intent_id", + })?, + &request, ) - .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) - .attach_printable( - "invalid connector name received in billing merchant connector account", - )?; - - let connector_enum = - common_enums::connector_enums::Connector::from_str(connector_name.as_str()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable(format!("unable to parse connector name {connector_name:?}"))?; - - let connector_params = - hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params( - &self.handler.state.conf.connectors, - connector_enum, - ) - .change_context(errors::ApiErrorResponse::ConfigNotFound) - .attach_printable(format!( - "cannot find connector params for this connector {connector_name} in this flow", - ))?; - - Ok(BillingHandler { - subscription: self.subscription.clone(), - auth_type, - connector_data, - connector_params, - request: self.handler.request.clone(), - connector_metadata: billing_processor_mca.metadata.clone(), - customer, - }) - } - - pub async fn get_invoice_handler(&self) -> errors::RouterResult<InvoiceHandler> { - Ok(InvoiceHandler { - subscription: self.subscription.clone(), - }) - } -} - -pub struct BillingHandler { - subscription: diesel_models::subscription::Subscription, - auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType, - connector_data: api_types::ConnectorData, - connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams, - connector_metadata: Option<pii::SecretSerdeValue>, - customer: hyperswitch_domain_models::customer::Customer, - request: subscription_types::ConfirmSubscriptionRequest, -} - -pub struct InvoiceHandler { - subscription: diesel_models::subscription::Subscription, -} - -#[allow(clippy::todo)] -impl InvoiceHandler { - #[allow(clippy::too_many_arguments)] - pub async fn create_invoice_entry( - self, - state: &SessionState, - merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, - payment_intent_id: Option<common_utils::id_type::PaymentId>, - amount: common_utils::types::MinorUnit, - currency: String, - status: common_enums::connector_enums::InvoiceStatus, - provider_name: common_enums::connector_enums::Connector, - metadata: Option<pii::SecretSerdeValue>, - ) -> errors::RouterResult<diesel_models::invoice::Invoice> { - let invoice_new = diesel_models::invoice::InvoiceNew::new( - self.subscription.id.to_owned(), - self.subscription.merchant_id.to_owned(), - self.subscription.profile_id.to_owned(), - merchant_connector_id, - payment_intent_id, - self.subscription.payment_method_id.clone(), - self.subscription.customer_id.to_owned(), - amount, - currency, - status, - provider_name, - metadata, - ); - - let invoice = state - .store - .insert_invoice_entry(invoice_new) - .await - .change_context(errors::ApiErrorResponse::SubscriptionError { - operation: "Subscription Confirm".to_string(), - }) - .attach_printable("invoices: unable to insert invoice entry to database")?; - - Ok(invoice) - } - - pub async fn create_cit_payment( - &self, - ) -> errors::RouterResult<subscription_types::PaymentResponseData> { - // Create a CIT payment for the invoice - todo!("Create a CIT payment for the invoice") - } + .await?; - pub async fn create_invoice_record_back_job( - &self, - // _invoice: &subscription_types::Invoice, - _payment_response: &subscription_types::PaymentResponseData, - ) -> errors::RouterResult<()> { - // Create an invoice job entry based on payment status - todo!("Create an invoice job entry based on payment status") - } -} + let billing_handler = + BillingHandler::create(&state, &merchant_context, customer, profile).await?; + let invoice_handler = subscription_entry.get_invoice_handler(); + let subscription = subscription_entry.subscription.clone(); -#[allow(clippy::todo)] -impl BillingHandler { - pub async fn create_customer_on_connector( - &self, - state: &SessionState, - ) -> errors::RouterResult<ConnectorCustomerResponseData> { - let customer_req = ConnectorCustomerData { - email: self.customer.email.clone().map(pii::Email::from), - payment_method_data: self - .request + let _customer_create_response = billing_handler + .create_customer_on_connector( + &state, + subscription.customer_id.clone(), + request.billing.clone(), + request .payment_details .payment_method_data - .payment_method_data - .clone() - .map(|pmd| pmd.into()), - description: None, - phone: None, - name: None, - preprocessing_id: None, - split_payments: None, - setup_future_usage: None, - customer_acceptance: None, - customer_id: Some(self.subscription.customer_id.to_owned()), - billing_address: self - .request - .billing_address - .as_ref() - .and_then(|add| add.address.clone()) - .and_then(|addr| addr.into()), - }; - let router_data = self.build_router_data( - state, - customer_req, - SubscriptionCustomerData { - connector_meta_data: self.connector_metadata.clone(), - }, - )?; - let connector_integration = self.connector_data.connector.get_connector_integration(); - - let response = Box::pin(self.call_connector( - state, - router_data, - "create customer on connector", - connector_integration, - )) + .payment_method_data, + ) .await?; - match response { - Ok(response_data) => match response_data { - PaymentsResponseData::ConnectorCustomerResponse(customer_response) => { - Ok(customer_response) - } - _ => Err(errors::ApiErrorResponse::SubscriptionError { - operation: "Subscription Customer Create".to_string(), - } - .into()), - }, - Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { - code: err.code, - message: err.message, - connector: self.connector_data.connector_name.to_string(), - status_code: err.status_code, - reason: err.reason, - } - .into()), - } - } - pub async fn create_subscription_on_connector( - &self, - state: &SessionState, - ) -> errors::RouterResult<subscription_response_types::SubscriptionCreateResponse> { - let subscription_item = subscription_request_types::SubscriptionItem { - item_price_id: self.request.get_item_price_id().change_context( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "item_price_id", - }, - )?, - quantity: Some(1), - }; - let subscription_req = subscription_request_types::SubscriptionCreateRequest { - subscription_id: self.subscription.id.to_owned(), - customer_id: self.subscription.customer_id.to_owned(), - subscription_items: vec![subscription_item], - billing_address: self.request.get_billing_address().change_context( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "billing_address", - }, - )?, - auto_collection: subscription_request_types::SubscriptionAutoCollection::Off, - connector_params: self.connector_params.clone(), - }; + let subscription_create_response = billing_handler + .create_subscription_on_connector( + &state, + subscription, + request.item_price_id, + request.billing, + ) + .await?; - let router_data = self.build_router_data( - state, - subscription_req, - SubscriptionCreateData { - connector_meta_data: self.connector_metadata.clone(), - }, - )?; - let connector_integration = self.connector_data.connector.get_connector_integration(); + let invoice_details = subscription_create_response.invoice_details; + let invoice_entry = invoice_handler + .update_invoice( + &state, + invoice.id, + payment_response.payment_method_id.clone(), + invoice_details + .clone() + .and_then(|invoice| invoice.status) + .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), + ) + .await?; - let response = self - .call_connector( - state, - router_data, - "create subscription on connector", - connector_integration, - ) - .await?; + subscription_entry + .update_subscription(diesel_models::subscription::SubscriptionUpdate::new( + payment_response.payment_method_id.clone(), + Some(SubscriptionStatus::from(subscription_create_response.status).to_string()), + Some( + subscription_create_response + .subscription_id + .get_string_repr() + .to_string(), + ), + )) + .await?; - match response { - Ok(response_data) => Ok(response_data), - Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { - code: err.code, - message: err.message, - connector: self.connector_data.connector_name.to_string(), - status_code: err.status_code, - reason: err.reason, - } - .into()), - } - } + let response = subscription_entry.generate_response( + &invoice_entry, + &payment_response, + subscription_create_response.status, + )?; - async fn call_connector<F, ResourceCommonData, Req, Resp>( - &self, - state: &SessionState, - router_data: hyperswitch_domain_models::router_data_v2::RouterDataV2< - F, - ResourceCommonData, - Req, - Resp, - >, - operation_name: &str, - connector_integration: hyperswitch_interfaces::connector_integration_interface::BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, - ) -> errors::RouterResult<Result<Resp, hyperswitch_domain_models::router_data::ErrorResponse>> - where - F: Clone + std::fmt::Debug + 'static, - Req: Clone + std::fmt::Debug + 'static, - Resp: Clone + std::fmt::Debug + 'static, - ResourceCommonData: - hyperswitch_interfaces::connector_integration_interface::RouterDataConversion< - F, - Req, - Resp, - > + Clone - + 'static, - { - let old_router_data = ResourceCommonData::to_old_router_data(router_data).change_context( - errors::ApiErrorResponse::SubscriptionError { - operation: { operation_name.to_string() }, - }, - )?; + Ok(ApplicationResponse::Json(response)) +} - let router_resp = services::execute_connector_processing_step( - state, - connector_integration, - &old_router_data, - payments_core::CallConnectorAction::Trigger, - None, - None, - ) +pub async fn get_subscription( + state: SessionState, + merchant_context: MerchantContext, + profile_id: common_utils::id_type::ProfileId, + subscription_id: common_utils::id_type::SubscriptionId, +) -> RouterResponse<SubscriptionResponse> { + let profile = + SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) + .await + .attach_printable( + "subscriptions: failed to find business profile in get_subscription", + )?; + let handler = SubscriptionHandler::new(&state, &merchant_context, profile); + let subscription = handler + .find_subscription(subscription_id) .await - .change_context(errors::ApiErrorResponse::SubscriptionError { - operation: operation_name.to_string(), - }) - .attach_printable(format!( - "Failed while in subscription operation: {operation_name}" - ))?; - - Ok(router_resp.response) - } + .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?; - fn build_router_data<F, ResourceCommonData, Req, Resp>( - &self, - state: &SessionState, - req: Req, - resource_common_data: ResourceCommonData, - ) -> errors::RouterResult< - hyperswitch_domain_models::router_data_v2::RouterDataV2<F, ResourceCommonData, Req, Resp>, - > { - Ok(hyperswitch_domain_models::router_data_v2::RouterDataV2 { - flow: std::marker::PhantomData, - connector_auth_type: self.auth_type.clone(), - resource_common_data, - tenant_id: state.tenant.tenant_id.clone(), - request: req, - response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), - }) - } + Ok(ApplicationResponse::Json( + subscription.to_subscription_response(), + )) } diff --git a/crates/router/src/core/subscription/billing_processor_handler.rs b/crates/router/src/core/subscription/billing_processor_handler.rs new file mode 100644 index 00000000000..7e0e303f042 --- /dev/null +++ b/crates/router/src/core/subscription/billing_processor_handler.rs @@ -0,0 +1,283 @@ +use std::str::FromStr; + +use common_enums::connector_enums; +use common_utils::{ext_traits::ValueExt, pii}; +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + merchant_context::MerchantContext, + router_data_v2::flow_common_types::{SubscriptionCreateData, SubscriptionCustomerData}, + router_request_types::{subscriptions as subscription_request_types, ConnectorCustomerData}, + router_response_types::{ + subscriptions as subscription_response_types, ConnectorCustomerResponseData, + PaymentsResponseData, + }, +}; + +use super::errors; +use crate::{ + core::payments as payments_core, routes::SessionState, services, types::api as api_types, +}; + +pub struct BillingHandler { + pub auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType, + pub connector_data: api_types::ConnectorData, + pub connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams, + pub connector_metadata: Option<pii::SecretSerdeValue>, + pub customer: hyperswitch_domain_models::customer::Customer, + pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, +} + +#[allow(clippy::todo)] +impl BillingHandler { + pub async fn create( + state: &SessionState, + merchant_context: &MerchantContext, + customer: hyperswitch_domain_models::customer::Customer, + profile: hyperswitch_domain_models::business_profile::Profile, + ) -> errors::RouterResult<Self> { + let merchant_connector_id = profile.get_billing_processor_id()?; + + let billing_processor_mca = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &(state).into(), + merchant_context.get_merchant_account().get_id(), + &merchant_connector_id, + merchant_context.get_merchant_key_store(), + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_connector_id.get_string_repr().to_string(), + })?; + + let connector_name = billing_processor_mca.connector_name.clone(); + + let auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType = + payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new( + billing_processor_mca.clone(), + )) + .get_connector_account_details() + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_account_details".to_string(), + expected_format: "auth_type and api_key".to_string(), + })?; + + let connector_data = api_types::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_name, + api_types::GetToken::Connector, + Some(billing_processor_mca.get_id()), + ) + .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) + .attach_printable( + "invalid connector name received in billing merchant connector account", + )?; + + let connector_enum = connector_enums::Connector::from_str(connector_name.as_str()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable(format!("unable to parse connector name {connector_name:?}"))?; + + let connector_params = + hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params( + &state.conf.connectors, + connector_enum, + ) + .change_context(errors::ApiErrorResponse::ConfigNotFound) + .attach_printable(format!( + "cannot find connector params for this connector {connector_name} in this flow", + ))?; + + Ok(Self { + auth_type, + connector_data, + connector_params, + connector_metadata: billing_processor_mca.metadata.clone(), + customer, + merchant_connector_id, + }) + } + pub async fn create_customer_on_connector( + &self, + state: &SessionState, + customer_id: common_utils::id_type::CustomerId, + billing_address: Option<api_models::payments::Address>, + payment_method_data: Option<api_models::payments::PaymentMethodData>, + ) -> errors::RouterResult<ConnectorCustomerResponseData> { + let customer_req = ConnectorCustomerData { + email: self.customer.email.clone().map(pii::Email::from), + payment_method_data: payment_method_data.clone().map(|pmd| pmd.into()), + description: None, + phone: None, + name: None, + preprocessing_id: None, + split_payments: None, + setup_future_usage: None, + customer_acceptance: None, + customer_id: Some(customer_id.clone()), + billing_address: billing_address + .as_ref() + .and_then(|add| add.address.clone()) + .and_then(|addr| addr.into()), + }; + let router_data = self.build_router_data( + state, + customer_req, + SubscriptionCustomerData { + connector_meta_data: self.connector_metadata.clone(), + }, + )?; + let connector_integration = self.connector_data.connector.get_connector_integration(); + + let response = Box::pin(self.call_connector( + state, + router_data, + "create customer on connector", + connector_integration, + )) + .await?; + + match response { + Ok(response_data) => match response_data { + PaymentsResponseData::ConnectorCustomerResponse(customer_response) => { + Ok(customer_response) + } + _ => Err(errors::ApiErrorResponse::SubscriptionError { + operation: "Subscription Customer Create".to_string(), + } + .into()), + }, + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: self.connector_data.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + } + .into()), + } + } + pub async fn create_subscription_on_connector( + &self, + state: &SessionState, + subscription: diesel_models::subscription::Subscription, + item_price_id: Option<String>, + billing_address: Option<api_models::payments::Address>, + ) -> errors::RouterResult<subscription_response_types::SubscriptionCreateResponse> { + let subscription_item = subscription_request_types::SubscriptionItem { + item_price_id: item_price_id.ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "item_price_id", + })?, + quantity: Some(1), + }; + let subscription_req = subscription_request_types::SubscriptionCreateRequest { + subscription_id: subscription.id.to_owned(), + customer_id: subscription.customer_id.to_owned(), + subscription_items: vec![subscription_item], + billing_address: billing_address.ok_or( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "billing", + }, + )?, + auto_collection: subscription_request_types::SubscriptionAutoCollection::Off, + connector_params: self.connector_params.clone(), + }; + + let router_data = self.build_router_data( + state, + subscription_req, + SubscriptionCreateData { + connector_meta_data: self.connector_metadata.clone(), + }, + )?; + let connector_integration = self.connector_data.connector.get_connector_integration(); + + let response = self + .call_connector( + state, + router_data, + "create subscription on connector", + connector_integration, + ) + .await?; + + match response { + Ok(response_data) => Ok(response_data), + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: self.connector_data.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + } + .into()), + } + } + + async fn call_connector<F, ResourceCommonData, Req, Resp>( + &self, + state: &SessionState, + router_data: hyperswitch_domain_models::router_data_v2::RouterDataV2< + F, + ResourceCommonData, + Req, + Resp, + >, + operation_name: &str, + connector_integration: hyperswitch_interfaces::connector_integration_interface::BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, + ) -> errors::RouterResult<Result<Resp, hyperswitch_domain_models::router_data::ErrorResponse>> + where + F: Clone + std::fmt::Debug + 'static, + Req: Clone + std::fmt::Debug + 'static, + Resp: Clone + std::fmt::Debug + 'static, + ResourceCommonData: + hyperswitch_interfaces::connector_integration_interface::RouterDataConversion< + F, + Req, + Resp, + > + Clone + + 'static, + { + let old_router_data = ResourceCommonData::to_old_router_data(router_data).change_context( + errors::ApiErrorResponse::SubscriptionError { + operation: { operation_name.to_string() }, + }, + )?; + + let router_resp = services::execute_connector_processing_step( + state, + connector_integration, + &old_router_data, + payments_core::CallConnectorAction::Trigger, + None, + None, + ) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: operation_name.to_string(), + }) + .attach_printable(format!( + "Failed while in subscription operation: {operation_name}" + ))?; + + Ok(router_resp.response) + } + + fn build_router_data<F, ResourceCommonData, Req, Resp>( + &self, + state: &SessionState, + req: Req, + resource_common_data: ResourceCommonData, + ) -> errors::RouterResult< + hyperswitch_domain_models::router_data_v2::RouterDataV2<F, ResourceCommonData, Req, Resp>, + > { + Ok(hyperswitch_domain_models::router_data_v2::RouterDataV2 { + flow: std::marker::PhantomData, + connector_auth_type: self.auth_type.clone(), + resource_common_data, + tenant_id: state.tenant.tenant_id.clone(), + request: req, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), + }) + } +} diff --git a/crates/router/src/core/subscription/invoice_handler.rs b/crates/router/src/core/subscription/invoice_handler.rs new file mode 100644 index 00000000000..eae1b9d05c7 --- /dev/null +++ b/crates/router/src/core/subscription/invoice_handler.rs @@ -0,0 +1,215 @@ +use api_models::{ + enums as api_enums, + subscription::{self as subscription_types}, +}; +use common_enums::connector_enums; +use common_utils::{pii, types::MinorUnit}; +use error_stack::ResultExt; +use hyperswitch_domain_models::router_response_types::subscriptions as subscription_response_types; +use masking::{PeekInterface, Secret}; + +use super::errors; +use crate::{core::subscription::payments_api_client, routes::SessionState}; + +pub struct InvoiceHandler { + pub subscription: diesel_models::subscription::Subscription, + pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, + pub profile: hyperswitch_domain_models::business_profile::Profile, +} + +#[allow(clippy::todo)] +impl InvoiceHandler { + #[allow(clippy::too_many_arguments)] + pub async fn create_invoice_entry( + self, + state: &SessionState, + merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + payment_intent_id: Option<common_utils::id_type::PaymentId>, + amount: MinorUnit, + currency: common_enums::Currency, + status: connector_enums::InvoiceStatus, + provider_name: connector_enums::Connector, + metadata: Option<pii::SecretSerdeValue>, + ) -> errors::RouterResult<diesel_models::invoice::Invoice> { + let invoice_new = diesel_models::invoice::InvoiceNew::new( + self.subscription.id.to_owned(), + self.subscription.merchant_id.to_owned(), + self.subscription.profile_id.to_owned(), + merchant_connector_id, + payment_intent_id, + self.subscription.payment_method_id.clone(), + self.subscription.customer_id.to_owned(), + amount, + currency.to_string(), + status, + provider_name, + metadata, + ); + + let invoice = state + .store + .insert_invoice_entry(invoice_new) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: "Create Invoice".to_string(), + }) + .attach_printable("invoices: unable to insert invoice entry to database")?; + + Ok(invoice) + } + + pub async fn update_invoice( + &self, + state: &SessionState, + invoice_id: common_utils::id_type::InvoiceId, + payment_method_id: Option<Secret<String>>, + status: connector_enums::InvoiceStatus, + ) -> errors::RouterResult<diesel_models::invoice::Invoice> { + let update_invoice = diesel_models::invoice::InvoiceUpdate::new( + payment_method_id.as_ref().map(|id| id.peek()).cloned(), + Some(status), + ); + state + .store + .update_invoice_entry(invoice_id.get_string_repr().to_string(), update_invoice) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: "Invoice Update".to_string(), + }) + .attach_printable("invoices: unable to update invoice entry in database") + } + + pub fn get_amount_and_currency( + request: (Option<MinorUnit>, Option<api_enums::Currency>), + invoice_details: Option<subscription_response_types::SubscriptionInvoiceData>, + ) -> (MinorUnit, api_enums::Currency) { + // Use request amount and currency if provided, else fallback to invoice details from connector response + request.0.zip(request.1).unwrap_or( + invoice_details + .clone() + .map(|invoice| (invoice.total, invoice.currency_code)) + .unwrap_or((MinorUnit::new(0), api_enums::Currency::default())), + ) // Default to 0 and a default currency if not provided + } + + pub async fn create_payment_with_confirm_false( + &self, + state: &SessionState, + request: &subscription_types::CreateSubscriptionRequest, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let payment_details = &request.payment_details; + let payment_request = subscription_types::CreatePaymentsRequestData { + amount: request.amount, + currency: request.currency, + customer_id: Some(self.subscription.customer_id.clone()), + billing: request.billing.clone(), + shipping: request.shipping.clone(), + setup_future_usage: payment_details.setup_future_usage, + return_url: Some(payment_details.return_url.clone()), + capture_method: payment_details.capture_method, + authentication_type: payment_details.authentication_type, + }; + payments_api_client::PaymentsApiClient::create_cit_payment( + state, + payment_request, + self.merchant_account.get_id().get_string_repr(), + self.profile.get_id().get_string_repr(), + ) + .await + } + + pub async fn get_payment_details( + &self, + state: &SessionState, + payment_id: common_utils::id_type::PaymentId, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + payments_api_client::PaymentsApiClient::sync_payment( + state, + payment_id.get_string_repr().to_string(), + self.merchant_account.get_id().get_string_repr(), + self.profile.get_id().get_string_repr(), + ) + .await + } + + pub async fn create_and_confirm_payment( + &self, + state: &SessionState, + request: &subscription_types::CreateAndConfirmSubscriptionRequest, + amount: MinorUnit, + currency: common_enums::Currency, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let payment_details = &request.payment_details; + let payment_request = subscription_types::CreateAndConfirmPaymentsRequestData { + amount, + currency, + confirm: true, + customer_id: Some(self.subscription.customer_id.clone()), + billing: request.billing.clone(), + shipping: request.shipping.clone(), + setup_future_usage: payment_details.setup_future_usage, + return_url: payment_details.return_url.clone(), + capture_method: payment_details.capture_method, + authentication_type: payment_details.authentication_type, + payment_method: payment_details.payment_method, + payment_method_type: payment_details.payment_method_type, + payment_method_data: payment_details.payment_method_data.clone(), + customer_acceptance: payment_details.customer_acceptance.clone(), + }; + payments_api_client::PaymentsApiClient::create_and_confirm_payment( + state, + payment_request, + self.merchant_account.get_id().get_string_repr(), + self.profile.get_id().get_string_repr(), + ) + .await + } + + pub async fn confirm_payment( + &self, + state: &SessionState, + payment_id: common_utils::id_type::PaymentId, + request: &subscription_types::ConfirmSubscriptionRequest, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let payment_details = &request.payment_details; + let cit_payment_request = subscription_types::ConfirmPaymentsRequestData { + billing: request.billing.clone(), + shipping: request.shipping.clone(), + payment_method: payment_details.payment_method, + payment_method_type: payment_details.payment_method_type, + payment_method_data: payment_details.payment_method_data.clone(), + customer_acceptance: payment_details.customer_acceptance.clone(), + }; + payments_api_client::PaymentsApiClient::confirm_payment( + state, + cit_payment_request, + payment_id.get_string_repr().to_string(), + self.merchant_account.get_id().get_string_repr(), + self.profile.get_id().get_string_repr(), + ) + .await + } + + pub async fn get_latest_invoice( + &self, + state: &SessionState, + ) -> errors::RouterResult<diesel_models::invoice::Invoice> { + state + .store + .get_latest_invoice_for_subscription(self.subscription.id.get_string_repr().to_string()) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: "Get Latest Invoice".to_string(), + }) + .attach_printable("invoices: unable to get latest invoice from database") + } + + pub async fn create_invoice_record_back_job( + &self, + // _invoice: &subscription_types::Invoice, + _payment_response: &subscription_types::PaymentResponseData, + ) -> errors::RouterResult<()> { + // Create an invoice job entry based on payment status + todo!("Create an invoice job entry based on payment status") + } +} diff --git a/crates/router/src/core/subscription/payments_api_client.rs b/crates/router/src/core/subscription/payments_api_client.rs new file mode 100644 index 00000000000..e483469be96 --- /dev/null +++ b/crates/router/src/core/subscription/payments_api_client.rs @@ -0,0 +1,195 @@ +use api_models::subscription as subscription_types; +use common_utils::{ext_traits::BytesExt, request as services}; +use error_stack::ResultExt; + +use crate::{core::errors, headers, routes::SessionState, services::api}; + +pub struct PaymentsApiClient; + +#[derive(Debug, serde::Deserialize)] +pub struct ErrorResponse { + error: ErrorResponseDetails, +} + +#[derive(Debug, serde::Deserialize)] +pub struct ErrorResponseDetails { + #[serde(rename = "type")] + error_type: Option<String>, + code: String, + message: String, +} + +impl PaymentsApiClient { + fn get_internal_auth_headers( + state: &SessionState, + merchant_id: &str, + profile_id: &str, + ) -> Vec<(String, masking::Maskable<String>)> { + vec![ + ( + headers::X_INTERNAL_API_KEY.to_string(), + masking::Maskable::Masked( + state + .conf + .internal_merchant_id_profile_id_auth + .internal_api_key + .clone(), + ), + ), + ( + headers::X_MERCHANT_ID.to_string(), + masking::Maskable::Normal(merchant_id.to_string()), + ), + ( + headers::X_PROFILE_ID.to_string(), + masking::Maskable::Normal(profile_id.to_string()), + ), + ] + } + + /// Generic method to handle payment API calls with different HTTP methods and URL patterns + async fn make_payment_api_call( + state: &SessionState, + method: services::Method, + url: String, + request_body: Option<common_utils::request::RequestContent>, + operation_name: &str, + merchant_id: &str, + profile_id: &str, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let subscription_error = errors::ApiErrorResponse::SubscriptionError { + operation: operation_name.to_string(), + }; + let headers = Self::get_internal_auth_headers(state, merchant_id, profile_id); + + let mut request_builder = services::RequestBuilder::new() + .method(method) + .url(&url) + .headers(headers); + + // Add request body only if provided (for POST requests) + if let Some(body) = request_body { + request_builder = request_builder.set_body(body); + } + + let request = request_builder.build(); + let response = api::call_connector_api(state, request, "Subscription Payments") + .await + .change_context(subscription_error.clone())?; + + match response { + Ok(res) => { + let api_response: subscription_types::PaymentResponseData = res + .response + .parse_struct(std::any::type_name::<subscription_types::PaymentResponseData>()) + .change_context(subscription_error)?; + Ok(api_response) + } + Err(err) => { + let error_response: ErrorResponse = err + .response + .parse_struct(std::any::type_name::<ErrorResponse>()) + .change_context(subscription_error)?; + Err(errors::ApiErrorResponse::ExternalConnectorError { + code: error_response.error.code, + message: error_response.error.message, + connector: "payments_microservice".to_string(), + status_code: err.status_code, + reason: error_response.error.error_type, + } + .into()) + } + } + } + + pub async fn create_cit_payment( + state: &SessionState, + request: subscription_types::CreatePaymentsRequestData, + merchant_id: &str, + profile_id: &str, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let base_url = &state.conf.internal_services.payments_base_url; + let url = format!("{}/payments", base_url); + + Self::make_payment_api_call( + state, + services::Method::Post, + url, + Some(common_utils::request::RequestContent::Json(Box::new( + request, + ))), + "Create Payment", + merchant_id, + profile_id, + ) + .await + } + + pub async fn create_and_confirm_payment( + state: &SessionState, + request: subscription_types::CreateAndConfirmPaymentsRequestData, + merchant_id: &str, + profile_id: &str, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let base_url = &state.conf.internal_services.payments_base_url; + let url = format!("{}/payments", base_url); + + Self::make_payment_api_call( + state, + services::Method::Post, + url, + Some(common_utils::request::RequestContent::Json(Box::new( + request, + ))), + "Create And Confirm Payment", + merchant_id, + profile_id, + ) + .await + } + + pub async fn confirm_payment( + state: &SessionState, + request: subscription_types::ConfirmPaymentsRequestData, + payment_id: String, + merchant_id: &str, + profile_id: &str, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let base_url = &state.conf.internal_services.payments_base_url; + let url = format!("{}/payments/{}/confirm", base_url, payment_id); + + Self::make_payment_api_call( + state, + services::Method::Post, + url, + Some(common_utils::request::RequestContent::Json(Box::new( + request, + ))), + "Confirm Payment", + merchant_id, + profile_id, + ) + .await + } + + pub async fn sync_payment( + state: &SessionState, + payment_id: String, + merchant_id: &str, + profile_id: &str, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + let base_url = &state.conf.internal_services.payments_base_url; + let url = format!("{}/payments/{}", base_url, payment_id); + + Self::make_payment_api_call( + state, + services::Method::Get, + url, + None, + "Sync Payment", + merchant_id, + profile_id, + ) + .await + } +} diff --git a/crates/router/src/core/subscription/subscription_handler.rs b/crates/router/src/core/subscription/subscription_handler.rs new file mode 100644 index 00000000000..25259a47696 --- /dev/null +++ b/crates/router/src/core/subscription/subscription_handler.rs @@ -0,0 +1,247 @@ +use std::str::FromStr; + +use api_models::{ + enums as api_enums, + subscription::{self as subscription_types, SubscriptionResponse, SubscriptionStatus}, +}; +use common_enums::connector_enums; +use diesel_models::subscription::SubscriptionNew; +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + merchant_context::MerchantContext, + router_response_types::subscriptions as subscription_response_types, +}; +use masking::Secret; + +use super::errors; +use crate::{core::subscription::invoice_handler::InvoiceHandler, routes::SessionState}; + +pub struct SubscriptionHandler<'a> { + pub state: &'a SessionState, + pub merchant_context: &'a MerchantContext, + pub profile: hyperswitch_domain_models::business_profile::Profile, +} + +impl<'a> SubscriptionHandler<'a> { + pub fn new( + state: &'a SessionState, + merchant_context: &'a MerchantContext, + profile: hyperswitch_domain_models::business_profile::Profile, + ) -> Self { + Self { + state, + merchant_context, + profile, + } + } + + /// Helper function to create a subscription entry in the database. + pub async fn create_subscription_entry( + &self, + subscription_id: common_utils::id_type::SubscriptionId, + customer_id: &common_utils::id_type::CustomerId, + billing_processor: connector_enums::Connector, + merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + merchant_reference_id: Option<String>, + ) -> errors::RouterResult<SubscriptionWithHandler<'_>> { + let store = self.state.store.clone(); + let db = store.as_ref(); + + let mut subscription = SubscriptionNew::new( + subscription_id, + SubscriptionStatus::Created.to_string(), + Some(billing_processor.to_string()), + None, + Some(merchant_connector_id), + None, + None, + self.merchant_context + .get_merchant_account() + .get_id() + .clone(), + customer_id.clone(), + None, + self.profile.get_id().clone(), + merchant_reference_id, + ); + + subscription.generate_and_set_client_secret(); + + let new_subscription = db + .insert_subscription_entry(subscription) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("subscriptions: unable to insert subscription entry to database")?; + + Ok(SubscriptionWithHandler { + handler: self, + subscription: new_subscription, + profile: self.profile.clone(), + merchant_account: self.merchant_context.get_merchant_account().clone(), + }) + } + + /// Helper function to find and validate customer. + pub async fn find_customer( + state: &SessionState, + merchant_context: &MerchantContext, + customer_id: &common_utils::id_type::CustomerId, + ) -> errors::RouterResult<hyperswitch_domain_models::customer::Customer> { + let key_manager_state = &(state).into(); + let merchant_key_store = merchant_context.get_merchant_key_store(); + let merchant_id = merchant_context.get_merchant_account().get_id(); + + state + .store + .find_customer_by_customer_id_merchant_id( + key_manager_state, + customer_id, + merchant_id, + merchant_key_store, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::CustomerNotFound) + .attach_printable("subscriptions: unable to fetch customer from database") + } + + /// Helper function to find business profile. + pub async fn find_business_profile( + state: &SessionState, + merchant_context: &MerchantContext, + profile_id: &common_utils::id_type::ProfileId, + ) -> errors::RouterResult<hyperswitch_domain_models::business_profile::Profile> { + let key_manager_state = &(state).into(); + let merchant_key_store = merchant_context.get_merchant_key_store(); + + state + .store + .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id) + .await + .change_context(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_string(), + }) + } + + pub async fn find_subscription( + &self, + subscription_id: common_utils::id_type::SubscriptionId, + ) -> errors::RouterResult<SubscriptionWithHandler<'_>> { + let subscription = self + .state + .store + .find_by_merchant_id_subscription_id( + self.merchant_context.get_merchant_account().get_id(), + subscription_id.get_string_repr().to_string().clone(), + ) + .await + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: format!( + "subscription not found for id: {}", + subscription_id.get_string_repr() + ), + })?; + + Ok(SubscriptionWithHandler { + handler: self, + subscription, + profile: self.profile.clone(), + merchant_account: self.merchant_context.get_merchant_account().clone(), + }) + } +} +pub struct SubscriptionWithHandler<'a> { + pub handler: &'a SubscriptionHandler<'a>, + pub subscription: diesel_models::subscription::Subscription, + pub profile: hyperswitch_domain_models::business_profile::Profile, + pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, +} + +impl SubscriptionWithHandler<'_> { + pub fn generate_response( + &self, + invoice: &diesel_models::invoice::Invoice, + payment_response: &subscription_types::PaymentResponseData, + status: subscription_response_types::SubscriptionStatus, + ) -> errors::RouterResult<subscription_types::ConfirmSubscriptionResponse> { + Ok(subscription_types::ConfirmSubscriptionResponse { + id: self.subscription.id.clone(), + merchant_reference_id: self.subscription.merchant_reference_id.clone(), + status: SubscriptionStatus::from(status), + plan_id: None, + profile_id: self.subscription.profile_id.to_owned(), + payment: Some(payment_response.clone()), + customer_id: Some(self.subscription.customer_id.clone()), + price_id: None, + coupon: None, + billing_processor_subscription_id: self.subscription.connector_subscription_id.clone(), + invoice: Some(subscription_types::Invoice { + id: invoice.id.clone(), + subscription_id: invoice.subscription_id.clone(), + merchant_id: invoice.merchant_id.clone(), + profile_id: invoice.profile_id.clone(), + merchant_connector_id: invoice.merchant_connector_id.clone(), + payment_intent_id: invoice.payment_intent_id.clone(), + payment_method_id: invoice.payment_method_id.clone(), + customer_id: invoice.customer_id.clone(), + amount: invoice.amount, + currency: api_enums::Currency::from_str(invoice.currency.as_str()) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "currency", + }) + .attach_printable(format!( + "unable to parse currency name {currency:?}", + currency = invoice.currency + ))?, + status: invoice.status.clone(), + }), + }) + } + + pub fn to_subscription_response(&self) -> SubscriptionResponse { + SubscriptionResponse::new( + self.subscription.id.clone(), + self.subscription.merchant_reference_id.clone(), + SubscriptionStatus::from_str(&self.subscription.status) + .unwrap_or(SubscriptionStatus::Created), + None, + self.subscription.profile_id.to_owned(), + self.subscription.merchant_id.to_owned(), + self.subscription.client_secret.clone().map(Secret::new), + self.subscription.customer_id.clone(), + ) + } + + pub async fn update_subscription( + &mut self, + subscription_update: diesel_models::subscription::SubscriptionUpdate, + ) -> errors::RouterResult<()> { + let db = self.handler.state.store.as_ref(); + let updated_subscription = db + .update_subscription_entry( + self.handler + .merchant_context + .get_merchant_account() + .get_id(), + self.subscription.id.get_string_repr().to_string(), + subscription_update, + ) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: "Subscription Update".to_string(), + }) + .attach_printable("subscriptions: unable to update subscription entry in database")?; + + self.subscription = updated_subscription; + + Ok(()) + } + + pub fn get_invoice_handler(&self) -> InvoiceHandler { + InvoiceHandler { + subscription: self.subscription.clone(), + merchant_account: self.merchant_account.clone(), + profile: self.profile.clone(), + } + } +} diff --git a/crates/router/src/db/invoice.rs b/crates/router/src/db/invoice.rs index 850f1c52730..b12a806840f 100644 --- a/crates/router/src/db/invoice.rs +++ b/crates/router/src/db/invoice.rs @@ -27,6 +27,11 @@ pub trait InvoiceInterface { invoice_id: String, data: storage::invoice::InvoiceUpdate, ) -> CustomResult<storage::Invoice, errors::StorageError>; + + async fn get_latest_invoice_for_subscription( + &self, + subscription_id: String, + ) -> CustomResult<storage::Invoice, errors::StorageError>; } #[async_trait::async_trait] @@ -65,6 +70,28 @@ impl InvoiceInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) } + + #[instrument(skip_all)] + async fn get_latest_invoice_for_subscription( + &self, + subscription_id: String, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Invoice::list_invoices_by_subscription_id( + &conn, + subscription_id.clone(), + Some(1), + None, + false, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + .map(|e| e.last().cloned())? + .ok_or(report!(errors::StorageError::ValueNotFound(format!( + "Invoice not found for subscription_id: {}", + subscription_id + )))) + } } #[async_trait::async_trait] @@ -91,6 +118,13 @@ impl InvoiceInterface for MockDb { ) -> CustomResult<storage::Invoice, errors::StorageError> { Err(errors::StorageError::MockDbError)? } + + async fn get_latest_invoice_for_subscription( + &self, + _subscription_id: String, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } } #[async_trait::async_trait] @@ -123,4 +157,13 @@ impl InvoiceInterface for KafkaStore { .update_invoice_entry(invoice_id, data) .await } + + async fn get_latest_invoice_for_subscription( + &self, + subscription_id: String, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + self.diesel_store + .get_latest_invoice_for_subscription(subscription_id) + .await + } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 044aaa1b4bb..60724830e0c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1177,6 +1177,11 @@ impl Subscription { let route = web::scope("/subscriptions").app_data(web::Data::new(state.clone())); route + .service( + web::resource("").route(web::post().to(|state, req, payload| { + subscription::create_and_confirm_subscription(state, req, payload) + })), + ) .service(web::resource("/create").route( web::post().to(|state, req, payload| { subscription::create_subscription(state, req, payload) @@ -1189,6 +1194,10 @@ impl Subscription { }, )), ) + .service( + web::resource("/{subscription_id}") + .route(web::get().to(subscription::get_subscription)), + ) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 67ea61919d5..f6ba2af979a 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -88,7 +88,10 @@ impl From<Flow> for ApiIdentifier { | Flow::DecisionEngineDecideGatewayCall | Flow::DecisionEngineGatewayFeedbackCall => Self::Routing, - Flow::CreateSubscription | Flow::ConfirmSubscription => Self::Subscription, + Flow::CreateSubscription + | Flow::ConfirmSubscription + | Flow::CreateAndConfirmSubscription + | Flow::GetSubscription => Self::Subscription, Flow::RetrieveForexFlow => Self::Forex, Flow::AddToBlocklist => Self::Blocklist, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 3bf2f472837..770d0b2f9bd 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -925,11 +925,15 @@ pub async fn payments_confirm( is_platform_allowed: true, }; - let (auth_type, auth_flow) = - match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { - Ok(auth) => auth, - Err(e) => return api::log_and_return_error_response(e), - }; + let (auth_type, auth_flow) = match auth::check_internal_api_key_auth( + req.headers(), + &payload, + api_auth, + state.conf.internal_merchant_id_profile_id_auth.clone(), + ) { + Ok(auth) => auth, + Err(e) => return api::log_and_return_error_response(e), + }; let locking_action = payload.get_locking_input(flow.clone()); diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs index aacf03392be..a762da71972 100644 --- a/crates/router/src/routes/subscription.rs +++ b/crates/router/src/routes/subscription.rs @@ -3,6 +3,8 @@ //! Functions that are used to perform the api level configuration and retrieval //! of various types under Subscriptions. +use std::str::FromStr; + use actix_web::{web, HttpRequest, HttpResponse, Responder}; use api_models::subscription as subscription_types; use hyperswitch_domain_models::errors; @@ -19,7 +21,34 @@ use crate::{ types::domain, }; -#[cfg(all(feature = "oltp", feature = "v1"))] +fn extract_profile_id(req: &HttpRequest) -> Result<common_utils::id_type::ProfileId, HttpResponse> { + let header_value = req.headers().get(X_PROFILE_ID).ok_or_else(|| { + HttpResponse::BadRequest().json( + errors::api_error_response::ApiErrorResponse::MissingRequiredField { + field_name: X_PROFILE_ID, + }, + ) + })?; + + let profile_str = header_value.to_str().unwrap_or_default(); + + if profile_str.is_empty() { + return Err(HttpResponse::BadRequest().json( + errors::api_error_response::ApiErrorResponse::MissingRequiredField { + field_name: X_PROFILE_ID, + }, + )); + } + + common_utils::id_type::ProfileId::from_str(profile_str).map_err(|_| { + HttpResponse::BadRequest().json( + errors::api_error_response::ApiErrorResponse::InvalidDataValue { + field_name: X_PROFILE_ID, + }, + ) + }) +} + #[instrument(skip_all)] pub async fn create_subscription( state: web::Data<AppState>, @@ -27,15 +56,9 @@ pub async fn create_subscription( json_payload: web::Json<subscription_types::CreateSubscriptionRequest>, ) -> impl Responder { let flow = Flow::CreateSubscription; - let profile_id = match req.headers().get(X_PROFILE_ID) { - Some(val) => val.to_str().unwrap_or_default().to_string(), - None => { - return HttpResponse::BadRequest().json( - errors::api_error_response::ApiErrorResponse::MissingRequiredField { - field_name: "x-profile-id", - }, - ); - } + let profile_id = match extract_profile_id(&req) { + Ok(id) => id, + Err(response) => return response, }; Box::pin(oss_api::server_wrap( flow, @@ -68,7 +91,6 @@ pub async fn create_subscription( .await } -#[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn confirm_subscription( state: web::Data<AppState>, @@ -78,15 +100,9 @@ pub async fn confirm_subscription( ) -> impl Responder { let flow = Flow::ConfirmSubscription; let subscription_id = subscription_id.into_inner(); - let profile_id = match req.headers().get(X_PROFILE_ID) { - Some(val) => val.to_str().unwrap_or_default().to_string(), - None => { - return HttpResponse::BadRequest().json( - errors::api_error_response::ApiErrorResponse::MissingRequiredField { - field_name: "x-profile-id", - }, - ); - } + let profile_id = match extract_profile_id(&req) { + Ok(id) => id, + Err(response) => return response, }; Box::pin(oss_api::server_wrap( flow, @@ -119,3 +135,83 @@ pub async fn confirm_subscription( )) .await } + +/// Add support for get subscription by id +#[instrument(skip_all)] +pub async fn get_subscription( + state: web::Data<AppState>, + req: HttpRequest, + subscription_id: web::Path<common_utils::id_type::SubscriptionId>, +) -> impl Responder { + let flow = Flow::GetSubscription; + let subscription_id = subscription_id.into_inner(); + let profile_id = match extract_profile_id(&req) { + Ok(id) => id, + Err(response) => return response, + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + (), + |state, auth: auth::AuthenticationData, _, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + subscription::get_subscription( + state, + merchant_context, + profile_id.clone(), + subscription_id.clone(), + ) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + &auth::JWTAuth { + permission: Permission::ProfileSubscriptionRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[instrument(skip_all)] +pub async fn create_and_confirm_subscription( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<subscription_types::CreateAndConfirmSubscriptionRequest>, +) -> impl Responder { + let flow = Flow::CreateAndConfirmSubscription; + let profile_id = match extract_profile_id(&req) { + Ok(id) => id, + Err(response) => return response, + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, payload, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + subscription::create_and_confirm_subscription( + state, + merchant_context, + profile_id.clone(), + payload.clone(), + ) + }, + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index cc9632bf8f2..46eef6fab6b 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -267,6 +267,10 @@ pub enum Flow { CreateSubscription, /// Subscription confirm flow, ConfirmSubscription, + /// Subscription create and confirm flow, + CreateAndConfirmSubscription, + /// Get Subscription flow + GetSubscription, /// Create dynamic routing CreateDynamicRoutingConfig, /// Toggle dynamic routing diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 536d23b8578..1f83b94199f 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -864,4 +864,7 @@ max_retry_count_for_thirty_day = 20 # Authentication to communicate between internal services using common_api_key, merchant id and profile id [internal_merchant_id_profile_id_auth] enabled = false # Enable or disable internal api key, merchant id and profile id based authentication -internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication + +[internal_services] # Internal services base urls and configs +payments_base_url = "http://localhost:8080"
2025-09-29T06:11:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Adding support to call payments microservice for subscription related usecases ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> As part of the subscriptions, we need to make several payments API call, adding a API client to facilitate such calls by reusing the call_connector API we already have. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` Enable internal API key Auth by changing config/development.toml [internal_merchant_id_profile_id_auth] enabled = true internal_api_key = "test_internal_api_key" ``` 1. Create Merchant, API key, Payment connector, Billing Connector 2. Update profile to set the billing processor Request ``` curl --location 'http://localhost:8080/account/merchant_1759125756/business_profile/pro_71jcERFiZERp44d8fuSJ' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_0RJW0cwZDeGfSkod0eJWOkfZHK0PCoZtDYJJ1FxeHqhHky1VNPU6nkgFQiTFSDvA' \ --data '{ "billing_processor_id": "mca_NLnCEvS2DfuHWHFVa09o" }' ``` Response ``` {"merchant_id":"merchant_1759125756","profile_id":"pro_71jcERFiZERp44d8fuSJ","profile_name":"US_default","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"ZFjTKSE1EYiXaPcRhacrwlNh4wieUorlmP7r2uSHI8fyHigGmNCKY2hqVtzAq51m","redirect_to_merchant_with_http_post":false,"webhook_details":{"webhook_version":"1.0.1","webhook_username":"ekart_retail","webhook_password":"password_ekart@123","webhook_url":null,"payment_created_enabled":true,"payment_succeeded_enabled":true,"payment_failed_enabled":true,"payment_statuses_enabled":null,"refund_statuses_enabled":null,"payout_statuses_enabled":null},"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":null,"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":false,"payout_link_config":null,"outgoing_webhook_custom_http_headers":null,"tax_connector_id":null,"is_tax_connector_enabled":false,"is_network_tokenization_enabled":false,"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,"is_debit_routing_enabled":false,"merchant_business_country":null,"is_pre_network_tokenization_enabled":false,"acquirer_configs":null,"is_iframe_redirection_enabled":null,"merchant_category_code":null,"merchant_country_code":null,"dispute_polling_interval":null,"is_manual_retry_enabled":null,"always_enable_overcapture":null,"is_external_vault_enabled":"skip","external_vault_connector_details":null,"billing_processor_id":"mca_NLnCEvS2DfuHWHFVa09o"} ``` 3. Create Customer Request ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_0RJW0cwZDeGfSkod0eJWOkfZHK0PCoZtDYJJ1FxeHqhHky1VNPU6nkgFQiTFSDvA' \ --data-raw '{ "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` { "customer_id": "cus_OYy3hzTTt04Enegu3Go3", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": null, "created_at": "2025-09-29T14:45:14.430Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null, "tax_registration_id": null } ``` 4. Create Subscription Request ``` curl --location 'http://localhost:8080/subscriptions/create' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_MiKOgwbj84jJ095MoWdj' \ --header 'api-key: dev_I62cGvBVijteiN61aMcAOeYvXpO8s36gT8BFvPznYYDXF4GFtVtjzgiel9oIpvUK' \ --data '{ "customer_id": "cus_uBtUJLSVSICr8ctmoL8i", "amount": 14100, "currency": "USD", "payment_details": { "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com" } }' ``` Response ``` { "id": "sub_dNLiu9sB55eCnByGNPdd", "merchant_reference_id": null, "status": "created", "plan_id": null, "profile_id": "pro_MiKOgwbj84jJ095MoWdj", "client_secret": "sub_dNLiu9sB55eCnByGNPdd_secret_4QTnPXm7c3B4zMF07WXt", "merchant_id": "merchant_1759157014", "coupon_code": null, "customer_id": "cus_aNko2i9A9Mg7EwXMJKzz" } ``` 5. Confirm Subscription Request ``` curl --location 'http://localhost:8080/subscriptions/sub_CkPzNaFAyxzX2WwdKFCr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_MiKOgwbj84jJ095MoWdj' \ --header 'api-key: dev_I62cGvBVijteiN61aMcAOeYvXpO8s36gT8BFvPznYYDXF4GFtVtjzgiel9oIpvUK' \ --data '{ "item_price_id": "cbdemo_enterprise-suite-monthly", "customer_id": "cus_uBtUJLSVSICr8ctmoL8i", "description": "Hello this is description", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "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" } } } }' ``` Response ``` { "id": "sub_dNLiu9sB55eCnByGNPdd", "merchant_reference_id": null, "status": "active", "plan_id": null, "price_id": null, "coupon": null, "profile_id": "pro_MiKOgwbj84jJ095MoWdj", "payment": { "payment_id": "sub_pay_WiJK7OF07DGdlJGjp1BC", "status": "succeeded", "amount": 14100, "currency": "USD", "connector": "stripe", "payment_method_id": "pm_aMEJiPUp3y0kMPUzzUcU", "payment_experience": null, "error_code": null, "error_message": null }, "customer_id": "cus_aNko2i9A9Mg7EwXMJKzz", "invoice": { "id": "invoice_9VSdsGCGJGxyXQiTaeaX", "subscription_id": "sub_dNLiu9sB55eCnByGNPdd", "merchant_id": "merchant_1759157014", "profile_id": "pro_MiKOgwbj84jJ095MoWdj", "merchant_connector_id": "mca_oMyzcBFcpfISftwDDVuG", "payment_intent_id": "sub_pay_WiJK7OF07DGdlJGjp1BC", "payment_method_id": "pm_aMEJiPUp3y0kMPUzzUcU", "customer_id": "cus_aNko2i9A9Mg7EwXMJKzz", "amount": 14100, "currency": "USD", "status": "payment_pending" }, "billing_processor_subscription_id": "sub_dNLiu9sB55eCnByGNPdd" } ``` 6. Create Customer and Create subscription again, do subscription confirm with Invalid postal code Request ``` curl --location 'http://localhost:8080/subscriptions/sub_PRAyYMVAalH7kPjfMpZP/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_MiKOgwbj84jJ095MoWdj' \ --header 'api-key: dev_I62cGvBVijteiN61aMcAOeYvXpO8s36gT8BFvPznYYDXF4GFtVtjzgiel9oIpvUK' \ --data '{ "item_price_id": "cbdemo_enterprise-suite-monthly", "customer_id": "cus_efEv4nqfrYEo8wSKZ10C", "description": "Hello this is description", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "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" } } } }' ``` Response ``` { "error": { "type": "connector", "message": "param_wrong_value: param_wrong_value", "code": "CE_00", "connector": "chargebee", "reason": "billing_address[zip] : invalid zip/postal code" } } ``` 7. Subscription create and confirm Request ``` curl --location 'http://localhost:8080/subscriptions' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_MiKOgwbj84jJ095MoWdj' \ --header 'api-key: dev_I62cGvBVijteiN61aMcAOeYvXpO8s36gT8BFvPznYYDXF4GFtVtjzgiel9oIpvUK' \ --data '{ "item_price_id": "cbdemo_enterprise-suite-monthly", "customer_id": "cus_efEv4nqfrYEo8wSKZ10C", "description": "Hello this is description", "merchant_reference_id": "mer_ref_1759334677", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com", "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" } } } }' ``` Response ``` { "id": "sub_CkPzNaFAyxzX2WwdKFCr", "merchant_reference_id": "mer_ref_1759334529", "status": "active", "plan_id": null, "price_id": null, "coupon": null, "profile_id": "pro_MiKOgwbj84jJ095MoWdj", "payment": { "payment_id": "sub_pay_KXEtoTxvu0EsadB5wxNn", "status": "succeeded", "amount": 14100, "currency": "INR", "connector": "stripe", "payment_method_id": "pm_bDPHgNaP7UZGjtZ7QPrS", "payment_experience": null, "error_code": null, "error_message": null }, "customer_id": "cus_uBtUJLSVSICr8ctmoL8i", "invoice": { "id": "invoice_Ht72m0Enqy4YOGRKAtbZ", "subscription_id": "sub_CkPzNaFAyxzX2WwdKFCr", "merchant_id": "merchant_1759157014", "profile_id": "pro_MiKOgwbj84jJ095MoWdj", "merchant_connector_id": "mca_oMyzcBFcpfISftwDDVuG", "payment_intent_id": "sub_pay_KXEtoTxvu0EsadB5wxNn", "payment_method_id": null, "customer_id": "cus_uBtUJLSVSICr8ctmoL8i", "amount": 14100, "currency": "INR", "status": "payment_pending" }, "billing_processor_subscription_id": "sub_CkPzNaFAyxzX2WwdKFCr" } ``` 8. Get subscription ``` curl --location 'http://localhost:8080/subscriptions/sub_PRAyYMVAalH7kPjfMpZP' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_MiKOgwbj84jJ095MoWdj' \ --header 'api-key: dev_I62cGvBVijteiN61aMcAOeYvXpO8s36gT8BFvPznYYDXF4GFtVtjzgiel9oIpvUK' ``` Response ``` { "id": "sub_CkPzNaFAyxzX2WwdKFCr", "merchant_reference_id": "mer_ref_1759334529", "status": "active", "plan_id": null, "profile_id": "pro_MiKOgwbj84jJ095MoWdj", "client_secret": "sub_CkPzNaFAyxzX2WwdKFCr_secret_F8z6T70udfgFVYpd4FsX", "merchant_id": "merchant_1759157014", "coupon_code": null, "customer_id": "cus_uBtUJLSVSICr8ctmoL8i" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
af159867ae3594e1b66f5b20d1e61132ec1d2bf4
juspay/hyperswitch
juspay__hyperswitch-9567
Bug: [FEATURE]: [GIGADAT] Implement Interac payouts Implement Interac payouts
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index edc6bf78759..de46df2373e 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -48,6 +48,7 @@ pub enum PayoutConnectors { Adyenplatform, Cybersource, Ebanx, + Gigadat, Nomupay, Nuvei, Payone, @@ -75,6 +76,7 @@ impl From<PayoutConnectors> for RoutableConnectors { PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, + PayoutConnectors::Gigadat => Self::Gigadat, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, @@ -93,6 +95,7 @@ impl From<PayoutConnectors> for Connector { PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, + PayoutConnectors::Gigadat => Self::Gigadat, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 55e13f5b094..5f38ee86f99 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1597,6 +1597,12 @@ pub struct BrowserInformation { /// The device model of the client pub device_model: Option<String>, + + /// Accept-language of the browser + pub accept_language: Option<String>, + + /// Identifier of the source that initiated the request. + pub referer: Option<String>, } impl RequestSurchargeDetails { diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index a6fdaa2b6e5..d61fc5bbc09 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -1,6 +1,8 @@ use std::collections::HashMap; use cards::CardNumber; +#[cfg(feature = "v2")] +use common_utils::types::BrowserInformation; use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, payout_method_utils, @@ -9,6 +11,8 @@ use common_utils::{ types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; +#[cfg(feature = "v1")] +use payments::BrowserInformation; use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -191,6 +195,10 @@ pub struct PayoutCreateRequest { /// Identifier for payout method pub payout_method_id: Option<String>, + + /// Additional details required by 3DS 2.0 + #[schema(value_type = Option<BrowserInformation>)] + pub browser_info: Option<BrowserInformation>, } impl PayoutCreateRequest { diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index a0d7e903068..e69ba486c32 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -285,6 +285,8 @@ pub struct ConnectorConfig { pub forte: Option<ConnectorTomlConfig>, pub getnet: Option<ConnectorTomlConfig>, pub gigadat: Option<ConnectorTomlConfig>, + #[cfg(feature = "payouts")] + pub gigadat_payout: Option<ConnectorTomlConfig>, pub globalpay: Option<ConnectorTomlConfig>, pub globepay: Option<ConnectorTomlConfig>, pub gocardless: Option<ConnectorTomlConfig>, @@ -399,6 +401,7 @@ impl ConnectorConfig { PayoutConnectors::Adyenplatform => Ok(connector_data.adyenplatform_payout), PayoutConnectors::Cybersource => Ok(connector_data.cybersource_payout), PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout), + PayoutConnectors::Gigadat => Ok(connector_data.gigadat_payout), PayoutConnectors::Nomupay => Ok(connector_data.nomupay_payout), PayoutConnectors::Nuvei => Ok(connector_data.nuvei_payout), PayoutConnectors::Payone => Ok(connector_data.payone_payout), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 11f17b69880..1a1b9b1efbb 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7221,6 +7221,20 @@ placeholder = "Enter site where transaction is initiated" required = true type = "Text" +[gigadat_payout] +[gigadat_payout.connector_auth.SignatureKey] +api_key = "Access Token" +api_secret = "Security Token" +key1 = "Campaign ID" +[[gigadat_payout.bank_redirect]] +payment_method_type = "interac" +[gigadat_payout.metadata.site] +name = "site" +label = "Site where transaction is initiated" +placeholder = "Enter site where transaction is initiated" +required = true +type = "Text" + [finix] [finix.connector_auth.HeaderKey] api_key = "API Key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index cc39c1fbc48..a65dcde1e2e 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5959,6 +5959,20 @@ placeholder = "Enter site where transaction is initiated" required = true type = "Text" +[gigadat_payout] +[gigadat_payout.connector_auth.SignatureKey] +api_key = "Access Token" +api_secret = "Security Token" +key1 = "Campaign ID" +[[gigadat_payout.bank_redirect]] +payment_method_type = "interac" +[gigadat_payout.metadata.site] +name = "site" +label = "Site where transaction is initiated" +placeholder = "Enter site where transaction is initiated" +required = true +type = "Text" + [finix] [finix.connector_auth.HeaderKey] api_key = "API Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 0bc4aa79ed7..124286a88a3 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7200,6 +7200,19 @@ placeholder = "Enter site where transaction is initiated" required = true type = "Text" +[gigadat_payout] +[gigadat_payout.connector_auth.SignatureKey] +api_key = "Access Token" +api_secret = "Security Token" +key1 = "Campaign ID" +[[gigadat_payout.bank_redirect]] +payment_method_type = "interac" +[gigadat_payout.metadata.site] +name = "site" +label = "Site where transaction is initiated" +placeholder = "Enter site where transaction is initiated" +required = true +type = "Text" [finix] [finix.connector_auth.HeaderKey] diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat.rs b/crates/hyperswitch_connectors/src/connectors/gigadat.rs index 973e1ae6f30..33910dce4b3 100644 --- a/crates/hyperswitch_connectors/src/connectors/gigadat.rs +++ b/crates/hyperswitch_connectors/src/connectors/gigadat.rs @@ -32,6 +32,13 @@ use hyperswitch_domain_models::{ RefundsRouterData, }, }; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::{PoCreate, PoFulfill, PoQuote}, + types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::types::{PayoutCreateType, PayoutFulfillType, PayoutQuoteType}; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, @@ -45,6 +52,8 @@ use hyperswitch_interfaces::{ }; use lazy_static::lazy_static; use masking::{Mask, PeekInterface}; +#[cfg(feature = "payouts")] +use router_env::{instrument, tracing}; use transformers as gigadat; use uuid::Uuid; @@ -75,6 +84,12 @@ impl api::Refund for Gigadat {} impl api::RefundExecute for Gigadat {} impl api::RefundSync for Gigadat {} impl api::PaymentToken for Gigadat {} +#[cfg(feature = "payouts")] +impl api::PayoutQuote for Gigadat {} +#[cfg(feature = "payouts")] +impl api::PayoutCreate for Gigadat {} +#[cfg(feature = "payouts")] +impl api::PayoutFulfill for Gigadat {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Gigadat @@ -578,6 +593,245 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gigadat { //Gigadat does not support Refund Sync } +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for Gigadat { + fn get_headers( + &self, + req: &PayoutsRouterData<PoQuote>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + req: &PayoutsRouterData<PoQuote>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(format!( + "{}api/payment-token/{}", + self.base_url(connectors), + auth.campaign_id.peek() + )) + } + + fn get_request_body( + &self, + req: &PayoutsRouterData<PoQuote>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.destination_currency, + )?; + + let connector_router_data = gigadat::GigadatRouterData::from((amount, req)); + let connector_req = gigadat::GigadatPayoutQuoteRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoQuote>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutQuoteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PayoutQuoteType::get_headers(self, req, connectors)?) + .set_body(PayoutQuoteType::get_request_body(self, req, connectors)?) + .build(); + + Ok(Some(request)) + } + + #[instrument(skip_all)] + fn handle_response( + &self, + data: &PayoutsRouterData<PoQuote>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PayoutsRouterData<PoQuote>, errors::ConnectorError> { + let response: gigadat::GigadatPayoutResponse = res + .response + .parse_struct("GigadatPayoutResponse") + .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] +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Gigadat { + fn get_headers( + &self, + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let transfer_id = req.request.connector_payout_id.to_owned().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "transfer_id", + }, + )?; + Ok(format!( + "{}webflow?transaction={}", + self.base_url(connectors), + transfer_id, + )) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutCreateType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PayoutCreateType::get_headers(self, req, connectors)?) + .build(); + + Ok(Some(request)) + } + + #[instrument(skip_all)] + fn handle_response( + &self, + data: &PayoutsRouterData<PoCreate>, + _event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PayoutsRouterData<PoCreate>, errors::ConnectorError> { + router_env::logger::debug!("Expected zero bytes response, skipped parsing of the response"); + + let status = if res.status_code == 200 { + enums::PayoutStatus::RequiresFulfillment + } else { + enums::PayoutStatus::Failed + }; + Ok(PayoutsRouterData { + response: Ok(PayoutsResponseData { + status: Some(status), + connector_payout_id: None, + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + error_code: None, + error_message: None, + }), + ..data.clone() + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Gigadat { + fn get_headers( + &self, + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let transfer_id = req.request.connector_payout_id.to_owned().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "transfer_id", + }, + )?; + Ok(format!( + "{}webflow?transaction={}", + self.base_url(connectors), + transfer_id, + )) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Get) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .build(); + + Ok(Some(request)) + } + + #[instrument(skip_all)] + fn handle_response( + &self, + data: &PayoutsRouterData<PoFulfill>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> { + let response: gigadat::GigadatPayoutResponse = res + .response + .parse_struct("GigadatPayoutResponse") + .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 Gigadat { fn get_webhook_object_reference_id( diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs index 060628f7a4b..a4bfc9c01a8 100644 --- a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs @@ -14,10 +14,17 @@ use hyperswitch_domain_models::{ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::PoQuote, router_response_types::PayoutsResponseData, + types::PayoutsRouterData, +}; use hyperswitch_interfaces::errors; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; +#[cfg(feature = "payouts")] +use crate::{types::PayoutsResponseRouterData, utils::PayoutsData as _}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self, BrowserInformationData, PaymentsAuthorizeRequestData, RouterData as _}, @@ -56,7 +63,7 @@ impl TryFrom<&Option<pii::SecretSerdeValue>> for GigadatConnectorMetadataObject } // CPI (Combined Pay-in) Request Structure for Gigadat -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct GigadatCpiRequest { pub user_id: id_type::CustomerId, @@ -73,10 +80,11 @@ pub struct GigadatCpiRequest { pub mobile: Secret<String>, } -#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum GidadatTransactionType { Cpi, + Eto, } impl TryFrom<&GigadatRouterData<&PaymentsAuthorizeRouterData>> for GigadatCpiRequest { @@ -153,19 +161,19 @@ impl TryFrom<&ConnectorAuthType> for GigadatAuthType { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct GigadatPaymentResponse { pub token: Secret<String>, pub data: GigadatPaymentData, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GigadatPaymentData { pub transaction_id: String, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GigadatPaymentStatus { StatusInited, @@ -194,7 +202,7 @@ impl From<GigadatPaymentStatus> for enums::AttemptStatus { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct GigadatTransactionStatusResponse { pub status: GigadatPaymentStatus, } @@ -310,18 +318,107 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRout } } -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GigadatPayoutQuoteRequest { + pub amount: FloatMajorUnit, + pub campaign: Secret<String>, + pub currency: Currency, + pub email: Email, + pub mobile: Secret<String>, + pub name: Secret<String>, + pub site: String, + pub transaction_id: String, + #[serde(rename = "type")] + pub transaction_type: GidadatTransactionType, + pub user_id: id_type::CustomerId, + pub user_ip: Secret<String, IpAddress>, +} + +// Payouts fulfill request transform +#[cfg(feature = "payouts")] +impl TryFrom<&GigadatRouterData<&PayoutsRouterData<PoQuote>>> for GigadatPayoutQuoteRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &GigadatRouterData<&PayoutsRouterData<PoQuote>>, + ) -> Result<Self, Self::Error> { + let metadata: GigadatConnectorMetadataObject = + utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "merchant_connector_account.metadata", + })?; + + let router_data = item.router_data; + let name = router_data.get_billing_full_name()?; + let email = router_data.get_billing_email()?; + let mobile = router_data.get_billing_phone_number()?; + let currency = item.router_data.request.destination_currency; + + let user_ip = router_data.request.get_browser_info()?.get_ip_address()?; + let auth_type = GigadatAuthType::try_from(&item.router_data.connector_auth_type)?; + + Ok(Self { + user_id: router_data.get_customer_id()?, + site: metadata.site, + user_ip, + currency, + amount: item.amount, + transaction_id: router_data.connector_request_reference_id.clone(), + transaction_type: GidadatTransactionType::Eto, + name, + email, + mobile, + campaign: auth_type.campaign_id, + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GigadatPayoutResponse { + pub token: Secret<String>, + pub data: GigadatPayoutData, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GigadatPayoutData { + pub transaction_id: String, + #[serde(rename = "type")] + pub transaction_type: String, +} + +#[cfg(feature = "payouts")] +impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutResponse>> for PayoutsRouterData<F> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: PayoutsResponseRouterData<F, GigadatPayoutResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(PayoutsResponseData { + status: None, + connector_payout_id: Some(item.response.data.transaction_id), + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + error_code: None, + error_message: None, + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize, Deserialize)] pub struct GigadatErrorResponse { pub err: String, } -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Default, Debug, Serialize, Deserialize)] pub struct GigadatRefundErrorResponse { pub error: Vec<Error>, pub message: String, } -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Default, Debug, Serialize, Deserialize)] pub struct Error { pub code: Option<String>, pub detail: String, diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 31b474cd3c3..b3eb01ba92a 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -3992,7 +3992,6 @@ default_imp_for_payouts_create!( connectors::Flexiti, connectors::Forte, connectors::Getnet, - connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4433,7 +4432,6 @@ default_imp_for_payouts_fulfill!( connectors::Flexiti, connectors::Forte, connectors::Getnet, - connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4724,7 +4722,6 @@ default_imp_for_payouts_quote!( connectors::Flexiti, connectors::Forte, connectors::Getnet, - connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 182c6067201..fd3e68f8019 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -6399,6 +6399,7 @@ pub trait PayoutsData { fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>; fn get_payout_type(&self) -> Result<enums::PayoutType, Error>; fn get_webhook_url(&self) -> Result<String, Error>; + fn get_browser_info(&self) -> Result<BrowserInformation, Error>; } #[cfg(feature = "payouts")] @@ -6430,6 +6431,11 @@ impl PayoutsData for hyperswitch_domain_models::router_request_types::PayoutsDat .to_owned() .ok_or_else(missing_field_err("webhook_url")) } + fn get_browser_info(&self) -> Result<BrowserInformation, Error> { + self.browser_info + .clone() + .ok_or_else(missing_field_err("browser_info")) + } } pub trait RevokeMandateRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error>; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index e035af3b074..415b97d1af0 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -939,6 +939,29 @@ impl From<common_utils::types::BrowserInformation> for BrowserInformation { } } +#[cfg(feature = "v1")] +impl From<api_models::payments::BrowserInformation> for BrowserInformation { + fn from(value: api_models::payments::BrowserInformation) -> Self { + Self { + color_depth: value.color_depth, + java_enabled: value.java_enabled, + java_script_enabled: value.java_script_enabled, + language: value.language, + screen_height: value.screen_height, + screen_width: value.screen_width, + time_zone: value.time_zone, + ip_address: value.ip_address, + accept_header: value.accept_header, + user_agent: value.user_agent, + os_type: value.os_type, + os_version: value.os_version, + device_model: value.device_model, + accept_language: value.accept_language, + referer: value.referer, + } + } +} + #[derive(Debug, Clone, Default, Serialize)] pub enum ResponseId { ConnectorTransactionId(String), @@ -1316,6 +1339,7 @@ pub struct PayoutsData { pub priority: Option<storage_enums::PayoutSendPriority>, pub connector_transfer_method_id: Option<String>, pub webhook_url: Option<String>, + pub browser_info: Option<BrowserInformation>, } #[derive(Debug, Default, Clone)] diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index c132ec8d128..90ba7f161be 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -79,6 +79,7 @@ pub struct PayoutData { pub current_locale: String, pub payment_method: Option<PaymentMethod>, pub connector_transfer_method_id: Option<String>, + pub browser_info: Option<domain_models::router_request_types::BrowserInformation>, } // ********************************************** CORE FLOWS ********************************************** @@ -533,12 +534,12 @@ pub async fn payouts_retrieve_core( ) .await?; - complete_payout_retrieve( + Box::pin(complete_payout_retrieve( &state, &merchant_context, connector_call_type, &mut payout_data, - ) + )) .await?; } @@ -2874,6 +2875,7 @@ pub async fn payout_create_db_entries( current_locale: locale.to_string(), payment_method, connector_transfer_method_id: None, + browser_info: req.browser_info.clone().map(Into::into), }) } @@ -2906,6 +2908,12 @@ pub async fn make_payout_data( payouts::PayoutRequest::PayoutRetrieveRequest(r) => r.payout_id.clone(), }; + let browser_info = match req { + payouts::PayoutRequest::PayoutActionRequest(_) => None, + payouts::PayoutRequest::PayoutCreateRequest(r) => r.browser_info.clone().map(Into::into), + payouts::PayoutRequest::PayoutRetrieveRequest(_) => None, + }; + let payouts = db .find_payout_by_merchant_id_payout_id( merchant_id, @@ -3100,6 +3108,7 @@ pub async fn make_payout_data( current_locale: locale.to_string(), payment_method, connector_transfer_method_id: None, + browser_info, }) } diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 30bc466063b..367973ddbd5 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -152,6 +152,8 @@ pub async fn construct_payout_router_data<'a, F>( let connector_transfer_method_id = payout_helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?; + let browser_info = payout_data.browser_info.to_owned(); + let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), @@ -197,6 +199,7 @@ pub async fn construct_payout_router_data<'a, F>( }), connector_transfer_method_id, webhook_url: Some(webhook_url), + browser_info, }, response: Ok(types::PayoutsResponseData::default()), access_token: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 7537b9117bb..8d7493d0c4f 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -478,6 +478,7 @@ pub trait ConnectorActions: Connector { priority: None, connector_transfer_method_id: None, webhook_url: None, + browser_info: None, }, payment_info, )
2025-09-25T13:39:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implement Interac payouts ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Not tested as we don't have creds ## Checklis <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2d580b3afbca861028e010853dc33c75818c9288
juspay/hyperswitch
juspay__hyperswitch-9561
Bug: [BUG]: Decryption failure in chat prevents retrieval of conversation history Internal users are unable to view their past chat conversations through the chat/ai/list endpoint, which is meant to be used for internal users. When attempting to retrieve the chat history, the system fails to decrypt the stored messages, resulting in error.
diff --git a/crates/router/src/utils/chat.rs b/crates/router/src/utils/chat.rs index c32b6190a95..74fcb6d0bc9 100644 --- a/crates/router/src/utils/chat.rs +++ b/crates/router/src/utils/chat.rs @@ -1,10 +1,10 @@ use api_models::chat as chat_api; -use common_utils::{type_name, types::keymanager::Identifier}; -use diesel_models::hyperswitch_ai_interaction::{ - HyperswitchAiInteraction, HyperswitchAiInteractionNew, +use common_utils::{ + crypto::{EncodeMessage, GcmAes256}, + encryption::Encryption, }; +use diesel_models::hyperswitch_ai_interaction::HyperswitchAiInteractionNew; use error_stack::ResultExt; -use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::ExposeInterface; use crate::{ @@ -29,29 +29,20 @@ pub async fn construct_hyperswitch_ai_interaction( encryption_key.as_bytes().to_vec() } }; - let encrypted_user_query = crypto_operation::<String, masking::WithType>( - &state.into(), - type_name!(HyperswitchAiInteraction), - CryptoOperation::Encrypt(req.message.clone()), - Identifier::Merchant(user_from_token.merchant_id.clone()), - &key, - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to encrypt user query")?; + let encrypted_user_query_bytes = GcmAes256 + .encode_message(&key, &req.message.clone().expose().into_bytes()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt user query")?; - let encrypted_response = crypto_operation::<serde_json::Value, masking::WithType>( - &state.into(), - type_name!(HyperswitchAiInteraction), - CryptoOperation::Encrypt(response.response.clone()), - Identifier::Merchant(user_from_token.merchant_id.clone()), - &key, - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to encrypt response")?; + let encrypted_response_bytes = serde_json::to_vec(&response.response.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize response for encryption") + .and_then(|bytes| { + GcmAes256 + .encode_message(&key, &bytes) + .change_context(errors::ApiErrorResponse::InternalServerError) + }) + .attach_printable("Failed to encrypt response")?; Ok(HyperswitchAiInteractionNew { id: request_id.to_owned(), @@ -61,8 +52,8 @@ pub async fn construct_hyperswitch_ai_interaction( profile_id: Some(user_from_token.profile_id.get_string_repr().to_string()), org_id: Some(user_from_token.org_id.get_string_repr().to_string()), role_id: Some(user_from_token.role_id.clone()), - user_query: Some(encrypted_user_query.into()), - response: Some(encrypted_response.into()), + user_query: Some(Encryption::new(encrypted_user_query_bytes.into())), + response: Some(Encryption::new(encrypted_response_bytes.into())), database_query: response.query_executed.clone().map(|q| q.expose()), interaction_status: Some(response.status.clone()), created_at: common_utils::date_time::now(),
2025-09-25T08:36:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR addresses an issue where chat conversation history could not be decrypted in the `chat/ai/list` endpoint. The root cause was an inconsistency between the encryption method used when storing chat interactions (`chat/ai/data`) and the decryption method used when retrieving them (`chat/ai/list`). This change standardizes the encryption process to use the direct `GcmAes256` utility, ensuring compatibility between encryption and decryption, and resolving the data retrieval failures. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes #9561 ## How did you test it? The list endpoint is working fine with new encryption logic: ``` curl --location 'http://localhost:8080/chat/ai/list?merchant_id=merchant_1758788495' \ --header 'Authorization: Bearer JWT' \ ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
94beaf915d62d678fca715ec18bfc64f9166f794
juspay/hyperswitch
juspay__hyperswitch-9558
Bug: [FEATURE] Add finix connector Template ### Feature Description Add template for finix ### Possible Implementation https://github.com/juspay/hyperswitch/pull/9557/files ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/config/config.example.toml b/config/config.example.toml index 98b5519d7b9..56da591f1fc 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -225,6 +225,7 @@ dwolla.base_url = "https://api-sandbox.dwolla.com" 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" +finix.base_url = "https://finix.sandbox-payments-api.com" 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/integration_test.toml b/config/deployments/integration_test.toml index 9ec3fc59162..02ee0124bae 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -64,6 +64,7 @@ dwolla.base_url = "https://api-sandbox.dwolla.com" 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" +finix.base_url = "https://finix.sandbox-payments-api.com" 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 6d297ace7ea..998986b3829 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -68,6 +68,7 @@ dwolla.base_url = "https://api.dwolla.com" ebanx.base_url = "https://api.ebanxpay.com/" elavon.base_url = "https://api.convergepay.com/VirtualMerchant/" facilitapay.base_url = "https://api.facilitapay.com/api/v1" +finix.base_url = "https://finix.live-payments-api.com" 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 c95a878769a..3f16af80c6f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -68,6 +68,7 @@ dwolla.base_url = "https://api-sandbox.dwolla.com" 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" +finix.base_url = "https://finix.sandbox-payments-api.com" 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 6cf74175b26..c15532805db 100644 --- a/config/development.toml +++ b/config/development.toml @@ -263,6 +263,7 @@ dwolla.base_url = "https://api-sandbox.dwolla.com" 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" +finix.base_url = "https://finix.sandbox-payments-api.com" 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 4baabfed538..b5101c53ad0 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -151,6 +151,7 @@ dwolla.base_url = "https://api-sandbox.dwolla.com" 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" +finix.base_url = "https://finix.sandbox-payments-api.com" 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/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 1421acc3373..aed9dbf70de 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -277,6 +277,7 @@ pub struct ConnectorConfig { pub ebanx_payout: Option<ConnectorTomlConfig>, pub elavon: Option<ConnectorTomlConfig>, pub facilitapay: Option<ConnectorTomlConfig>, + pub finix: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, pub fiservemea: Option<ConnectorTomlConfig>, pub fiuu: Option<ConnectorTomlConfig>, diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 9b7da0605e4..4b4bbc6ec83 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7179,6 +7179,10 @@ placeholder = "Enter site where transaction is initiated" required = true type = "Text" +[finix] +[finix.connector_auth.HeaderKey] +api_key = "API Key" + [tesouro] [tesouro.connector_auth.BodyKey] api_key="Client ID" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 660adf43a6a..86eea4d3534 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5916,6 +5916,10 @@ placeholder = "Enter site where transaction is initiated" required = true type = "Text" +[finix] +[finix.connector_auth.HeaderKey] +api_key = "API Key" + [tesouro] [tesouro.connector_auth.BodyKey] api_key="Client ID" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index b9e9abb8199..08ae831a52e 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7157,6 +7157,11 @@ placeholder = "Enter site where transaction is initiated" required = true type = "Text" + +[finix] +[finix.connector_auth.HeaderKey] +api_key = "API Key" + [tesouro] [tesouro.connector_auth.BodyKey] api_key="Client ID" diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 60becb9804c..70abd02eaaa 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -40,6 +40,7 @@ pub mod dwolla; pub mod ebanx; pub mod elavon; pub mod facilitapay; +pub mod finix; pub mod fiserv; pub mod fiservemea; pub mod fiuu; @@ -143,24 +144,24 @@ pub use self::{ coingate::Coingate, cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, custombilling::Custombilling, cybersource::Cybersource, datatrans::Datatrans, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, dwolla::Dwolla, - ebanx::Ebanx, elavon::Elavon, facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, - fiuu::Fiuu, flexiti::Flexiti, forte::Forte, getnet::Getnet, gigadat::Gigadat, - globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments, - helcim::Helcim, hipay::Hipay, hyperswitch_vault::HyperswitchVault, hyperwallet::Hyperwallet, - iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, - juspaythreedsserver::Juspaythreedsserver, katapult::Katapult, klarna::Klarna, - mifinity::Mifinity, mollie::Mollie, moneris::Moneris, mpgs::Mpgs, multisafepay::Multisafepay, - netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, - noon::Noon, nordea::Nordea, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, - paybox::Paybox, payeezy::Payeezy, payload::Payload, payme::Payme, payone::Payone, - paypal::Paypal, paysafe::Paysafe, paystack::Paystack, paytm::Paytm, payu::Payu, - peachpayments::Peachpayments, phonepe::Phonepe, placetopay::Placetopay, plaid::Plaid, - powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, - recurly::Recurly, redsys::Redsys, riskified::Riskified, santander::Santander, shift4::Shift4, - sift::Sift, signifyd::Signifyd, silverflow::Silverflow, square::Square, stax::Stax, - stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, tesouro::Tesouro, - threedsecureio::Threedsecureio, thunes::Thunes, tokenex::Tokenex, tokenio::Tokenio, - trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, + ebanx::Ebanx, elavon::Elavon, facilitapay::Facilitapay, finix::Finix, fiserv::Fiserv, + fiservemea::Fiservemea, fiuu::Fiuu, flexiti::Flexiti, forte::Forte, getnet::Getnet, + gigadat::Gigadat, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, + gpayments::Gpayments, helcim::Helcim, hipay::Hipay, hyperswitch_vault::HyperswitchVault, + hyperwallet::Hyperwallet, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, + jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, katapult::Katapult, + klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, mpgs::Mpgs, + multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, + nmi::Nmi, nomupay::Nomupay, noon::Noon, nordea::Nordea, novalnet::Novalnet, nuvei::Nuvei, + opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payload::Payload, + payme::Payme, payone::Payone, paypal::Paypal, paysafe::Paysafe, paystack::Paystack, + paytm::Paytm, payu::Payu, peachpayments::Peachpayments, phonepe::Phonepe, + placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, + rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, + santander::Santander, shift4::Shift4, sift::Sift, signifyd::Signifyd, silverflow::Silverflow, + square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, + tesouro::Tesouro, threedsecureio::Threedsecureio, thunes::Thunes, tokenex::Tokenex, + tokenio::Tokenio, trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, worldpay::Worldpay, worldpayvantiv::Worldpayvantiv, worldpayxml::Worldpayxml, xendit::Xendit, diff --git a/crates/hyperswitch_connectors/src/connectors/finix.rs b/crates/hyperswitch_connectors/src/connectors/finix.rs new file mode 100644 index 00000000000..d42f50a1532 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/finix.rs @@ -0,0 +1,621 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::{enums, ConnectorIntegrationStatus}; +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 finix; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Finix { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Finix { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} + +impl api::Payment for Finix {} +impl api::PaymentSession for Finix {} +impl api::ConnectorAccessToken for Finix {} +impl api::MandateSetup for Finix {} +impl api::PaymentAuthorize for Finix {} +impl api::PaymentSync for Finix {} +impl api::PaymentCapture for Finix {} +impl api::PaymentVoid for Finix {} +impl api::Refund for Finix {} +impl api::RefundExecute for Finix {} +impl api::RefundSync for Finix {} +impl api::PaymentToken for Finix {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Finix +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Finix +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 Finix { + fn id(&self) -> &'static str { + "finix" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.finix.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = finix::FinixAuthType::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: finix::FinixErrorResponse = + res.response + .parse_struct("FinixErrorResponse") + .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, + connector_metadata: None, + }) + } +} + +impl ConnectorValidation for Finix { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Finix { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Finix {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Finix {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Finix { + 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 = finix::FinixRouterData::from((amount, req)); + let connector_req = finix::FinixPaymentsRequest::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: finix::FinixPaymentsResponse = res + .response + .parse_struct("Finix 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 Finix { + 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: finix::FinixPaymentsResponse = res + .response + .parse_struct("finix 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 Finix { + 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: finix::FinixPaymentsResponse = res + .response + .parse_struct("Finix 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 Finix {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Finix { + 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 = finix::FinixRouterData::from((refund_amount, req)); + let connector_req = finix::FinixRefundRequest::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: finix::RefundResponse = res + .response + .parse_struct("finix 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 Finix { + 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: finix::RefundResponse = res + .response + .parse_struct("finix 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 Finix { + 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)) + } +} + +static FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static FINIX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Finix", + description: "Finix is a payments technology provider enabling businesses to accept and send payments online or in person", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: ConnectorIntegrationStatus::Alpha, +}; + +static FINIX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Finix { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&FINIX_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*FINIX_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&FINIX_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs new file mode 100644 index 00000000000..b09f6ee47b9 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs @@ -0,0 +1,217 @@ +use common_enums::enums; +use common_utils::types::MinorUnit; +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}; + +//TODO: Fill the struct with respective fields +pub struct FinixRouterData<T> { + pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(MinorUnit, T)> for FinixRouterData<T> { + fn from((amount, item): (MinorUnit, 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 FinixPaymentsRequest { + amount: MinorUnit, + card: FinixCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct FinixCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&FinixRouterData<&PaymentsAuthorizeRouterData>> for FinixPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &FinixRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct FinixAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for FinixAuthType { + 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, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum FinixPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<FinixPaymentStatus> for common_enums::AttemptStatus { + fn from(item: FinixPaymentStatus) -> Self { + match item { + FinixPaymentStatus::Succeeded => Self::Charged, + FinixPaymentStatus::Failed => Self::Failure, + FinixPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct FinixPaymentsResponse { + status: FinixPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, FinixPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, FinixPaymentsResponse, 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 FinixRefundRequest { + pub amount: MinorUnit, +} + +impl<F> TryFrom<&FinixRouterData<&RefundsRouterData<F>>> for FinixRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &FinixRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 FinixErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index f035b90a820..f742437f400 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -208,6 +208,7 @@ default_imp_for_authorize_session_token!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -353,6 +354,7 @@ default_imp_for_calculate_tax!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -499,6 +501,7 @@ default_imp_for_session_update!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -645,6 +648,7 @@ default_imp_for_post_session_tokens!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -789,6 +793,7 @@ default_imp_for_create_order!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -935,6 +940,7 @@ default_imp_for_update_metadata!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -1081,6 +1087,7 @@ default_imp_for_cancel_post_capture!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -1220,6 +1227,7 @@ default_imp_for_complete_authorize!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1352,6 +1360,7 @@ default_imp_for_incremental_authorization!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1456,6 +1465,7 @@ macro_rules! default_imp_for_create_customer { } default_imp_for_create_customer!( + connectors::Finix, connectors::Vgs, connectors::Aci, connectors::Adyen, @@ -1632,6 +1642,7 @@ default_imp_for_connector_redirect_response!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1762,6 +1773,7 @@ default_imp_for_pre_authenticate_steps!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1907,6 +1919,7 @@ default_imp_for_authenticate_steps!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2052,6 +2065,7 @@ default_imp_for_post_authenticate_steps!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2195,6 +2209,7 @@ default_imp_for_pre_processing_steps!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2329,6 +2344,7 @@ default_imp_for_post_processing_steps!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2476,6 +2492,7 @@ default_imp_for_approve!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2624,6 +2641,7 @@ default_imp_for_reject!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2773,6 +2791,7 @@ default_imp_for_webhook_source_verification!( connectors::Elavon, connectors::Ebanx, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2918,6 +2937,7 @@ default_imp_for_accept_dispute!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3063,6 +3083,7 @@ default_imp_for_submit_evidence!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3207,6 +3228,7 @@ default_imp_for_defend_dispute!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3355,6 +3377,7 @@ default_imp_for_fetch_disputes!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3502,6 +3525,7 @@ default_imp_for_dispute_sync!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3656,6 +3680,7 @@ default_imp_for_file_upload!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3792,6 +3817,7 @@ default_imp_for_payouts!( connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3934,6 +3960,7 @@ default_imp_for_payouts_create!( connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4080,6 +4107,7 @@ default_imp_for_payouts_retrieve!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4224,6 +4252,7 @@ default_imp_for_payouts_eligibility!( connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4369,6 +4398,7 @@ default_imp_for_payouts_fulfill!( connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4511,6 +4541,7 @@ default_imp_for_payouts_cancel!( connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4657,6 +4688,7 @@ default_imp_for_payouts_quote!( connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4804,6 +4836,7 @@ default_imp_for_payouts_recipient!( connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4951,6 +4984,7 @@ default_imp_for_payouts_recipient_account!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -5099,6 +5133,7 @@ default_imp_for_frm_sale!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -5247,6 +5282,7 @@ default_imp_for_frm_checkout!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -5395,6 +5431,7 @@ default_imp_for_frm_transaction!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -5543,6 +5580,7 @@ default_imp_for_frm_fulfillment!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -5691,6 +5729,7 @@ default_imp_for_frm_record_return!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -5834,6 +5873,7 @@ default_imp_for_revoking_mandates!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -5980,6 +6020,7 @@ default_imp_for_uas_pre_authentication!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -6125,6 +6166,7 @@ default_imp_for_uas_post_authentication!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -6271,6 +6313,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -6409,6 +6452,7 @@ default_imp_for_connector_request_id!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -6549,6 +6593,7 @@ default_imp_for_fraud_check!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -6719,6 +6764,7 @@ default_imp_for_connector_authentication!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -6862,6 +6908,7 @@ default_imp_for_uas_authentication!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -7000,6 +7047,7 @@ default_imp_for_revenue_recovery!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -7170,6 +7218,7 @@ default_imp_for_subscriptions!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -7319,6 +7368,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -7466,6 +7516,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -7613,6 +7664,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Elavon, connectors::Ebanx, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -7754,6 +7806,7 @@ default_imp_for_external_vault!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -7900,6 +7953,7 @@ default_imp_for_external_vault_insert!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -8044,6 +8098,7 @@ default_imp_for_gift_card_balance_check!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -8192,6 +8247,7 @@ default_imp_for_external_vault_retrieve!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -8338,6 +8394,7 @@ default_imp_for_external_vault_delete!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -8487,6 +8544,7 @@ default_imp_for_external_vault_create!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -8633,6 +8691,7 @@ default_imp_for_connector_authentication_token!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -8778,6 +8837,7 @@ default_imp_for_external_vault_proxy_payments_create!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, 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 570977048f8..42236aa86af 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -308,6 +308,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -457,6 +458,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -598,6 +600,7 @@ default_imp_for_new_connector_integration_connector_authentication_token!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -735,6 +738,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -883,6 +887,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1031,6 +1036,7 @@ default_imp_for_new_connector_integration_fetch_disputes!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1180,6 +1186,7 @@ default_imp_for_new_connector_integration_dispute_sync!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1329,6 +1336,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1476,6 +1484,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1634,6 +1643,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1784,6 +1794,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1934,6 +1945,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2084,6 +2096,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2234,6 +2247,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2384,6 +2398,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2534,6 +2549,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2684,6 +2700,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2834,6 +2851,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2982,6 +3000,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3132,6 +3151,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3282,6 +3302,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3432,6 +3453,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3582,6 +3604,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3732,6 +3755,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3880,6 +3904,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4011,6 +4036,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4158,6 +4184,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4294,6 +4321,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4449,6 +4477,7 @@ default_imp_for_new_connector_integration_external_vault!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4596,6 +4625,7 @@ default_imp_for_new_connector_integration_external_vault_proxy!( connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, + connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rs index 7f1657c0a35..a1514c01bc4 100644 --- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs +++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs @@ -55,6 +55,7 @@ pub struct Connectors { pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, + pub finix: 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 3bed6948c39..78ed84edf3f 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -18,32 +18,32 @@ pub use hyperswitch_connectors::connectors::{ cybersource, cybersource::Cybersource, datatrans, datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, dwolla, dwolla::Dwolla, ebanx, ebanx::Ebanx, elavon, elavon::Elavon, facilitapay, - facilitapay::Facilitapay, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, - fiuu::Fiuu, flexiti, flexiti::Flexiti, forte, forte::Forte, getnet, getnet::Getnet, gigadat, - gigadat::Gigadat, globalpay, globalpay::Globalpay, globepay, globepay::Globepay, gocardless, - gocardless::Gocardless, gpayments, gpayments::Gpayments, helcim, helcim::Helcim, hipay, - hipay::Hipay, hyperswitch_vault, hyperswitch_vault::HyperswitchVault, hyperwallet, - hyperwallet::Hyperwallet, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, - itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, - juspaythreedsserver::Juspaythreedsserver, katapult, katapult::Katapult, klarna, klarna::Klarna, - mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, mpgs, - mpgs::Mpgs, multisafepay, multisafepay::Multisafepay, netcetera, netcetera::Netcetera, - nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, - nomupay::Nomupay, noon, noon::Noon, nordea, nordea::Nordea, novalnet, novalnet::Novalnet, - nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, - payeezy, payeezy::Payeezy, payload, payload::Payload, payme, payme::Payme, payone, - payone::Payone, paypal, paypal::Paypal, paysafe, paysafe::Paysafe, paystack, - paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, peachpayments, - peachpayments::Peachpayments, phonepe, phonepe::Phonepe, placetopay, placetopay::Placetopay, - plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, - rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, - redsys::Redsys, riskified, riskified::Riskified, santander, santander::Santander, shift4, - shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, silverflow, - silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, stripe::Stripe, - stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, tesouro, tesouro::Tesouro, - threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, - tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, - trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, + facilitapay::Facilitapay, finix, finix::Finix, fiserv, fiserv::Fiserv, fiservemea, + fiservemea::Fiservemea, fiuu, fiuu::Fiuu, flexiti, flexiti::Flexiti, forte, forte::Forte, + getnet, getnet::Getnet, gigadat, gigadat::Gigadat, globalpay, globalpay::Globalpay, globepay, + globepay::Globepay, gocardless, gocardless::Gocardless, gpayments, gpayments::Gpayments, + helcim, helcim::Helcim, hipay, hipay::Hipay, hyperswitch_vault, + hyperswitch_vault::HyperswitchVault, hyperwallet, hyperwallet::Hyperwallet, iatapay, + iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, + jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, katapult, + katapult::Katapult, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, mollie, + mollie::Mollie, moneris, moneris::Moneris, mpgs, mpgs::Mpgs, multisafepay, + multisafepay::Multisafepay, netcetera, netcetera::Netcetera, nexinets, nexinets::Nexinets, + nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, + nordea, nordea::Nordea, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, + opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payload, + payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paysafe, + paysafe::Paysafe, paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, + peachpayments, peachpayments::Peachpayments, phonepe, phonepe::Phonepe, placetopay, + placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, + prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, + recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, santander, + santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, + silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, + stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, tesouro, + tesouro::Tesouro, threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, + tokenex, tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, + trustpayments, trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, diff --git a/crates/router/tests/connectors/finix.rs b/crates/router/tests/connectors/finix.rs new file mode 100644 index 00000000000..4efe9a9bd82 --- /dev/null +++ b/crates/router/tests/connectors/finix.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 FinixTest; +impl ConnectorActions for FinixTest {} +impl utils::Connector for FinixTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Finix; + utils::construct_connector_data_old( + Box::new(Finix::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .finix + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "finix".to_string() + } +} + +static CONNECTOR: FinixTest = FinixTest {}; + +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 6f671a243e1..9738f6a2b72 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -43,6 +43,7 @@ mod dwolla; mod ebanx; mod elavon; mod facilitapay; +mod finix; mod fiserv; mod fiservemea; mod fiuu; diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index c51c415321d..fbcded72d56 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -53,6 +53,7 @@ pub struct ConnectorAuthentication { pub ebanx: Option<HeaderKey>, pub elavon: Option<HeaderKey>, pub facilitapay: Option<BodyKey>, + pub finix: Option<HeaderKey>, 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 3c76b7c62e6..695a9593e26 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -118,6 +118,7 @@ dwolla.base_url = "https://api-sandbox.dwolla.com" 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" +finix.base_url = "https://finix.sandbox-payments-api.com" 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/scripts/add_connector.sh b/scripts/add_connector.sh index 25dce6cd58b..4e16b0b7357 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 affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet gigadat globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar tesouro threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay finix fiserv fiservemea fiuu flexiti forte getnet gigadat globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar tesouro threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
2025-09-25T07:44:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Template Code for Finix No need test cases . ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
1ff66a720b29a169870b2141e6ffd585b4d5b640
juspay/hyperswitch
juspay__hyperswitch-9564
Bug: [FEATURE] Update county and currency list for nuvei ### Feature Description - change env config to add relavent country and currency for nuvei ### Possible Implementation . ### 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 ea27effe833..9c3ae814080 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -727,19 +727,18 @@ eps = { country = "DE",currency = "EUR" } apple_pay = { country = "DE",currency = "EUR" } paypal = { country = "DE",currency = "EUR" } - [pm_filters.nuvei] -credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -debit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -apple_pay = { country = "AU, HK, JP, NZ, SG, TW, AT, BY, BE, BG, HR, CY, CZ, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT, KZ, JE, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, UA, GB, VA, BR, IL, SA, AE, CA, US",currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, AZN, BYN, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, CHF, UAH, GBP, ARS, BRL, CLP, COP, CRC, DOP, USD, GTQ, MXN, PYG, PEN, UYU, BHD, JOD, KWD, OMR, QAR, SAR, AED, CAD" } -google_pay = { country = "AL, DZ, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, BG, CA, CL, CO, HR, CZ, DK, DO, EG, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, RU, SA, SG, SK, ZA, ES, LK, SE, CH, TW, TH, TR, UA, AE, GB, UY, VN",currency = "ALL, DZD, USD, ARS, AUD, EUR, AZN, BHD, BYN, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, HKD, HUF, INR, IDR, JPY, JOD, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PEN, PHP, PLN, QAR, RON, RUB, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND" } -paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.stax] credit = { country = "US", currency = "USD" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index c381bc0596a..fc6f4aa7cd1 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -501,7 +501,7 @@ apple_pay.country = "AU, AT, BE, BR, BG, CA, HR, CY, CZ, DK, EE, FI, FR, DE, GR, cashapp = { country = "US", currency = "USD" } eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } -google_pay.country = "AU, AT, BE, BR, BG, CA, HR, CZ, DK, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IT, JP, LV, KE, LT, LU, MY, MX, NL, NZ, NO, PL, PT, RO, SG, SK, ZA, ES, SE, CH, TH, AE, GB, US" +google_pay.country = "AU, AT, BE, BR, BG, CA, HR, CZ, DK, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IT, JP, LV, KE, LT, LU, MY, MX, NL, NZ, NO, PL, PT, RO, SG, SK, ZA, ES, SE, CH, TH, AE, GB, US, GI, LI, MT, CY, PH, IS, AR, CL, KR, IL" ideal = { country = "NL", currency = "EUR" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,CAD,CHF,CZK,DKK,EUR,GBP,NOK,NZD,PLN,SEK,USD" } multibanco = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GI,GR,HU,IE,IT,LV,LI,LT,LU,MT,NL,NO,PL,PT,RO,SK,SI,ES,SE,CH,GB", currency = "EUR" } @@ -546,20 +546,18 @@ eps = { country = "DE",currency = "EUR" } apple_pay = { country = "DE",currency = "EUR" } paypal = { country = "DE",currency = "EUR" } - [pm_filters.nuvei] -credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -debit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -apple_pay = { country = "AU, HK, JP, NZ, SG, TW, AT, BY, BE, BG, HR, CY, CZ, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT, KZ, JE, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, UA, GB, VA, BR, IL, SA, AE, CA, US",currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, AZN, BYN, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, CHF, UAH, GBP, ARS, BRL, CLP, COP, CRC, DOP, USD, GTQ, MXN, PYG, PEN, UYU, BHD, JOD, KWD, OMR, QAR, SAR, AED, CAD" } -google_pay = { country = "AL,US, DZ, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, BG, CA, CL, CO, HR, CZ, DK, DO, EG, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, RU, SA, SG, SK, ZA, ES, LK, SE, CH, TW, TH, TR, UA, AE, GB, UY, VN",currency = "ALL, DZD, USD, ARS, AUD, EUR, AZN, BHD, BYN, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, HKD, HUF, INR, IDR, JPY, JOD, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PEN, PHP, PLN, QAR, RON, RUB, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND" } -paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } - +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 34bfffa8f3f..312378b5e17 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -463,19 +463,18 @@ eps = { country = "DE",currency = "EUR" } apple_pay = { country = "DE",currency = "EUR" } paypal = { country = "DE",currency = "EUR" } - [pm_filters.nuvei] -credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -debit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -apple_pay = { country = "AU, HK, JP, NZ, SG, TW, AT, BY, BE, BG, HR, CY, CZ, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT, KZ, JE, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, UA, GB, VA, BR, IL, SA, AE, CA, US",currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, AZN, BYN, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, CHF, UAH, GBP, ARS, BRL, CLP, COP, CRC, DOP, USD, GTQ, MXN, PYG, PEN, UYU, BHD, JOD, KWD, OMR, QAR, SAR, AED, CAD" } -google_pay = { country = "AL,US, DZ, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, BG, CA, CL, CO, HR, CZ, DK, DO, EG, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, RU, SA, SG, SK, ZA, ES, LK, SE, CH, TW, TH, TR, UA, AE, GB, UY, VN",currency = "ALL, DZD, USD, ARS, AUD, EUR, AZN, BHD, BYN, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, HKD, HUF, INR, IDR, JPY, JOD, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PEN, PHP, PLN, QAR, RON, RUB, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND" } -paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.nexixpay] @@ -611,7 +610,7 @@ apple_pay.country = "AU, AT, BE, BR, BG, CA, HR, CY, CZ, DK, EE, FI, FR, DE, GR, cashapp = { country = "US", currency = "USD" } eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } -google_pay.country = "AU, AT, BE, BR, BG, CA, HR, CZ, DK, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IT, JP, LV, KE, LT, LU, MY, MX, NL, NZ, NO, PL, PT, RO, SG, SK, ZA, ES, SE, CH, TH, AE, GB, US" +google_pay.country = "AU, AT, BE, BR, BG, CA, HR, CZ, DK, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IT, JP, LV, KE, LT, LU, MY, MX, NL, NZ, NO, PL, PT, RO, SG, SK, ZA, ES, SE, CH, TH, AE, GB, US, GI, LI, MT, CY, PH, IS, AR, CL, KR, IL" ideal = { country = "NL", currency = "EUR" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,CAD,CHF,CZK,DKK,EUR,GBP,NOK,NZD,PLN,SEK,USD" } multibanco = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GI,GR,HU,IE,IT,LV,LI,LT,LU,MT,NL,NO,PL,PT,RO,SK,SI,ES,SE,CH,GB", currency = "EUR" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index a13157b860e..fbfc2beedf1 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -526,20 +526,18 @@ eps = { country = "DE",currency = "EUR" } apple_pay = { country = "DE",currency = "EUR" } paypal = { country = "DE",currency = "EUR" } - [pm_filters.nuvei] -credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -debit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -apple_pay = { country = "AU, HK, JP, NZ, SG, TW, AT, BY, BE, BG, HR, CY, CZ, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT, KZ, JE, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, UA, GB, VA, BR, IL, SA, AE, CA, US",currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, AZN, BYN, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, CHF, UAH, GBP, ARS, BRL, CLP, COP, CRC, DOP, USD, GTQ, MXN, PYG, PEN, UYU, BHD, JOD, KWD, OMR, QAR, SAR, AED, CAD" } -google_pay = { country = "AL,US, DZ, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, BG, CA, CL, CO, HR, CZ, DK, DO, EG, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, RU, SA, SG, SK, ZA, ES, LK, SE, CH, TW, TH, TR, UA, AE, GB, UY, VN",currency = "ALL, DZD, USD, ARS, AUD, EUR, AZN, BHD, BYN, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, HKD, HUF, INR, IDR, JPY, JOD, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PEN, PHP, PLN, QAR, RON, RUB, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND" } -paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } - +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.globepay] ali_pay = { country = "GB",currency = "GBP,CNY" } @@ -619,7 +617,7 @@ apple_pay.country = "AU, AT, BE, BR, BG, CA, HR, CY, CZ, DK, EE, FI, FR, DE, GR, cashapp = { country = "US", currency = "USD" } eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } -google_pay.country = "AU, AT, BE, BR, BG, CA, HR, CZ, DK, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IT, JP, LV, KE, LT, LU, MY, MX, NL, NZ, NO, PL, PT, RO, SG, SK, ZA, ES, SE, CH, TH, AE, GB, US" +google_pay.country = "AU, AT, BE, BR, BG, CA, HR, CZ, DK, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IT, JP, LV, KE, LT, LU, MY, MX, NL, NZ, NO, PL, PT, RO, SG, SK, ZA, ES, SE, CH, TH, AE, GB, US, GI, LI, MT, CY, PH, IS, AR, CL, KR, IL" ideal = { country = "NL", currency = "EUR" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,CAD,CHF,CZK,DKK,EUR,GBP,NOK,NZD,PLN,SEK,USD" } multibanco = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GI,GR,HU,IE,IT,LV,LI,LT,LU,MT,NL,NO,PL,PT,RO,SK,SI,ES,SE,CH,GB", currency = "EUR" } diff --git a/config/development.toml b/config/development.toml index b05755409e0..7b4db1f124b 100644 --- a/config/development.toml +++ b/config/development.toml @@ -450,7 +450,7 @@ sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } [pm_filters.stripe] -google_pay = { country = "AU, AT, BE, BR, BG, CA, HR, CZ, DK, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IT, JP, LV, KE, LT, LU, MY, MX, NL, NZ, NO, PL, PT, RO, SG, SK, ZA, ES, SE, CH, TH, AE, GB, US" } +google_pay = { country = "AU, AT, BE, BR, BG, CA, HR, CZ, DK, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IT, JP, LV, KE, LT, LU, MY, MX, NL, NZ, NO, PL, PT, RO, SG, SK, ZA, ES, SE, CH, TH, AE, GB, US, GI, LI, MT, CY, PH, IS, AR, CL, KR, IL"} apple_pay = { country = "AU, AT, BE, BR, BG, CA, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, HK, IE, IT, JP, LV, LI, LT, LU, MT, MY, MX, NL, NZ, NO, PL, PT, RO, SK, SG, SI, ZA, ES, SE, CH, GB, AE, US" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,CAD,CHF,CZK,DKK,EUR,GBP,NOK,NZD,PLN,SEK,USD" } 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US", 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,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"} @@ -648,17 +648,17 @@ paypal = { country = "DE",currency = "EUR" } [pm_filters.nuvei] -credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -debit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -apple_pay = { country = "AU, HK, JP, NZ, SG, TW, AT, BY, BE, BG, HR, CY, CZ, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT, KZ, JE, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, UA, GB, VA, BR, IL, SA, AE, CA, US",currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, AZN, BYN, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, CHF, UAH, GBP, ARS, BRL, CLP, COP, CRC, DOP, USD, GTQ, MXN, PYG, PEN, UYU, BHD, JOD, KWD, OMR, QAR, SAR, AED, CAD" } -google_pay = { country = "AL, US,DZ, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, BG, CA, CL, CO, HR, CZ, DK, DO, EG, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, RU, SA, SG, SK, ZA, ES, LK, SE, CH, TW, TH, TR, UA, AE, GB, UY, VN",currency = "ALL, DZD, USD, ARS, AUD, EUR, AZN, BHD, BYN, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, HKD, HUF, INR, IDR, JPY, JOD, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PEN, PHP, PLN, QAR, RON, RUB, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND" } -paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.checkout] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 896f3eeba6b..057f41ba635 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -700,18 +700,17 @@ supported_connectors = "adyen" adyen = "Star,Pulse,Accel,Nyce" [pm_filters.nuvei] -credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -debit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -apple_pay = { country = "AU, HK, JP, NZ, SG, TW, AT, BY, BE, BG, HR, CY, CZ, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT, KZ, JE, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, UA, GB, VA, BR, IL, SA, AE, CA, US",currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, AZN, BYN, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, CHF, UAH, GBP, ARS, BRL, CLP, COP, CRC, DOP, USD, GTQ, MXN, PYG, PEN, UYU, BHD, JOD, KWD, OMR, QAR, SAR, AED, CAD" } -google_pay = { country = "AL, DZ, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, BG, CA, CL, CO, HR, CZ, DK, DO, EG, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, RU, SA, SG, SK, ZA, ES, LK, SE, CH, TW, TH, TR, UA, AE, GB, UY, VN",currency = "ALL, DZD, USD, ARS, AUD, EUR, AZN, BHD, BYN, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, HKD, HUF, INR, IDR, JPY, JOD, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PEN, PHP, PLN, QAR, RON, RUB, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND" } -paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } - +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index e072a370b91..fd66c223683 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -382,19 +382,18 @@ eps = { country = "DE", currency = "EUR" } apple_pay = { country = "DE", currency = "EUR" } paypal = { country = "DE", currency = "EUR" } - [pm_filters.nuvei] -credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -debit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } -apple_pay = { country = "AU, HK, JP, NZ, SG, TW, AT, BY, BE, BG, HR, CY, CZ, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT, KZ, JE, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, UA, GB, VA, BR, IL, SA, AE, CA, US",currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, AZN, BYN, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, CHF, UAH, GBP, ARS, BRL, CLP, COP, CRC, DOP, USD, GTQ, MXN, PYG, PEN, UYU, BHD, JOD, KWD, OMR, QAR, SAR, AED, CAD" } -google_pay = { country = "AL, DZ, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, BG, CA, CL, CO, HR, CZ, DK, DO, EG, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, RU, SA, SG, SK, ZA, ES, LK, SE, CH, TW, TH, TR, UA, AE, GB, UY, VN",currency = "ALL, DZD, USD, ARS, AUD, EUR, AZN, BHD, BYN, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, HKD, HUF, INR, IDR, JPY, JOD, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PEN, PHP, PLN, QAR, RON, RUB, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND" } -paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +google_pay = { country = "AF,AX,AL,DZ,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,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,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,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,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,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } [pm_filters.payload] debit = { currency = "USD,CAD" }
2025-09-25T09:10:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Add missing countries and currencies for nuvei ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b26e845198407f3672a7f80d8eea670419858e0e
juspay/hyperswitch
juspay__hyperswitch-9549
Bug: Add support to call payments service with Internal API key for PSync
diff --git a/config/config.example.toml b/config/config.example.toml index 91966eaab12..d7273fe35b3 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1269,3 +1269,8 @@ encryption_key = "" # Key to encrypt and decrypt chat proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] connector_list = "worldpayvantiv" + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index b798d912dc9..d48ab2d148d 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -24,6 +24,10 @@ queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 clie [api_keys] hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # API key hashing key. +[internal_merchant_id_profile_id_auth] +enabled = false +internal_api_key = "test_internal_api_key" + [applepay_decrypt_keys] apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" # Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key generated by Elliptic-curve prime256v1 curve. You can use `openssl ecparam -out private.key -name prime256v1 -genkey` to generate the private key diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 8219ccf2206..489a865426c 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -904,3 +904,8 @@ connector_list = "worldpayvantiv" [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 394067bd85a..c4247d27839 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -914,3 +914,8 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 07333518f64..052f8d1cae2 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -922,3 +922,8 @@ connector_list = "worldpayvantiv" [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/config/development.toml b/config/development.toml index 06283933305..70fca988bad 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1383,3 +1383,7 @@ encryption_key = "" proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] connector_list = "worldpayvantiv" + +[internal_merchant_id_profile_id_auth] +enabled = false +internal_api_key = "test_internal_api_key" \ No newline at end of file diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 881de3aa4dc..0d77e4c66a5 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1278,3 +1278,8 @@ version = "HOSTNAME" # value of HOSTNAME from deployment which tells its proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] connector_list = "worldpayvantiv" + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 53ce32b033e..67b6854922a 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -576,6 +576,7 @@ pub(crate) async fn fetch_raw_secrets( debit_routing_config: conf.debit_routing_config, clone_connector_allowlist: conf.clone_connector_allowlist, merchant_id_auth: conf.merchant_id_auth, + internal_merchant_id_profile_id_auth: conf.internal_merchant_id_profile_id_auth, infra_values: conf.infra_values, enhancement: conf.enhancement, proxy_status_mapping: conf.proxy_status_mapping, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 1923af66b35..5b669885d24 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -163,6 +163,7 @@ pub struct Settings<S: SecretState> { pub revenue_recovery: revenue_recovery::RevenueRecoverySettings, pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>, pub merchant_id_auth: MerchantIdAuthSettings, + pub internal_merchant_id_profile_id_auth: InternalMerchantIdProfileIdAuthSettings, #[serde(default)] pub infra_values: Option<HashMap<String, String>>, #[serde(default)] @@ -849,6 +850,13 @@ pub struct MerchantIdAuthSettings { pub merchant_id_auth_enabled: bool, } +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct InternalMerchantIdProfileIdAuthSettings { + pub enabled: bool, + pub internal_api_key: Secret<String>, +} + #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct ProxyStatusMapping { diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index c746410aa0d..679ef8aff32 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -67,6 +67,7 @@ pub mod headers { pub const X_API_VERSION: &str = "X-ApiVersion"; pub const X_FORWARDED_FOR: &str = "X-Forwarded-For"; pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; + pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key"; pub const X_ORGANIZATION_ID: &str = "X-Organization-Id"; pub const X_LOGIN: &str = "X-Login"; pub const X_TRANS_KEY: &str = "X-Trans-Key"; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0d7da850f11..6aee34e8256 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1174,7 +1174,7 @@ pub struct Subscription; #[cfg(all(feature = "oltp", feature = "v1"))] impl Subscription { pub fn server(state: AppState) -> Scope { - let route = web::scope("/subscription").app_data(web::Data::new(state.clone())); + let route = web::scope("/subscriptions").app_data(web::Data::new(state.clone())); route .service(web::resource("/create").route( diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index c1970b64c28..3bf2f472837 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -78,6 +78,25 @@ pub async fn payments_create( let locking_action = payload.get_locking_input(flow.clone()); + let auth_type = match env::which() { + env::Env::Production => { + &auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: true, + })) + } + _ => auth::auth_type( + &auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: true, + })), + &auth::InternalMerchantIdProfileIdAuth(auth::JWTAuth { + permission: Permission::ProfilePaymentWrite, + }), + req.headers(), + ), + }; + Box::pin(api::server_wrap( flow, state, @@ -98,22 +117,7 @@ pub async fn payments_create( api::AuthFlow::Client, ) }, - match env::which() { - env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth { - is_connected_allowed: false, - is_platform_allowed: true, - }), - _ => auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth { - is_connected_allowed: false, - is_platform_allowed: true, - }), - &auth::JWTAuth { - permission: Permission::ProfilePaymentWrite, - }, - req.headers(), - ), - }, + auth_type, locking_action, )) .await @@ -569,11 +573,15 @@ pub async fn payments_retrieve( is_platform_allowed: true, }; - let (auth_type, auth_flow) = - match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { - Ok(auth) => auth, - Err(err) => return api::log_and_return_error_response(report!(err)), - }; + let (auth_type, auth_flow) = match auth::check_internal_api_key_auth( + req.headers(), + &payload, + api_auth, + state.conf.internal_merchant_id_profile_id_auth.clone(), + ) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(report!(err)), + }; let locking_action = payload.get_locking_input(flow.clone()); diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 851c2cf21b9..13d224a1cd7 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -38,6 +38,7 @@ use crate::core::errors::UserResult; #[cfg(all(feature = "partial-auth", feature = "v1"))] use crate::core::metrics; use crate::{ + configs::settings, core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, @@ -155,6 +156,10 @@ pub enum AuthenticationType { WebhookAuth { merchant_id: id_type::MerchantId, }, + InternalMerchantIdProfileId { + merchant_id: id_type::MerchantId, + profile_id: Option<id_type::ProfileId>, + }, NoAuth, } @@ -184,7 +189,8 @@ impl AuthenticationType { user_id: _, } | Self::MerchantJwtWithProfileId { merchant_id, .. } - | Self::WebhookAuth { merchant_id } => Some(merchant_id), + | Self::WebhookAuth { merchant_id } + | Self::InternalMerchantIdProfileId { merchant_id, .. } => Some(merchant_id), Self::AdminApiKey | Self::OrganizationJwt { .. } | Self::UserJwt { .. } @@ -1958,6 +1964,10 @@ impl<'a> HeaderMapStruct<'a> { }) } + pub fn get_header_value_by_key(&self, key: &str) -> Option<&str> { + self.headers.get(key).and_then(|value| value.to_str().ok()) + } + pub fn get_auth_string_from_header(&self) -> RouterResult<&str> { self.headers .get(headers::AUTHORIZATION) @@ -2309,6 +2319,96 @@ where } } +/// InternalMerchantIdProfileIdAuth authentication which first tries to authenticate using `X-Internal-API-Key`, +/// `X-Merchant-Id` and `X-Profile-Id` headers. If any of these headers are missing, +/// it falls back to the provided authentication mechanism. +#[cfg(feature = "v1")] +pub struct InternalMerchantIdProfileIdAuth<F>(pub F); + +#[cfg(feature = "v1")] +#[async_trait] +impl<A, F> AuthenticateAndFetch<AuthenticationData, A> for InternalMerchantIdProfileIdAuth<F> +where + A: SessionStateInfo + Sync + Send, + F: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + if !state.conf().internal_merchant_id_profile_id_auth.enabled { + return self.0.authenticate_and_fetch(request_headers, state).await; + } + let merchant_id = HeaderMapStruct::new(request_headers) + .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID) + .ok(); + let internal_api_key = HeaderMapStruct::new(request_headers) + .get_header_value_by_key(headers::X_INTERNAL_API_KEY) + .map(|s| s.to_string()); + let profile_id = HeaderMapStruct::new(request_headers) + .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID) + .ok(); + if let (Some(internal_api_key), Some(merchant_id), Some(profile_id)) = + (internal_api_key, merchant_id, profile_id) + { + let config = state.conf(); + if internal_api_key + != *config + .internal_merchant_id_profile_id_auth + .internal_api_key + .peek() + { + return Err(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Internal API key authentication failed"); + } + 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 _profile = state + .store() + .find_business_profile_by_merchant_id_profile_id( + key_manager_state, + &key_store, + &merchant_id, + &profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + 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)?; + let auth = AuthenticationData { + merchant_account: merchant, + key_store, + profile_id: Some(profile_id.clone()), + platform_merchant_account: None, + }; + Ok(( + auth.clone(), + AuthenticationType::InternalMerchantIdProfileId { + merchant_id, + profile_id: Some(profile_id), + }, + )) + } else { + Ok(self + .0 + .authenticate_and_fetch(request_headers, state) + .await?) + } + } +} + #[derive(Debug)] #[cfg(feature = "v2")] pub struct MerchantIdAndProfileIdAuth { @@ -4362,6 +4462,41 @@ pub fn is_jwt_auth(headers: &HeaderMap) -> bool { } } +pub fn is_internal_api_key_merchant_id_profile_id_auth( + headers: &HeaderMap, + internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings, +) -> bool { + internal_api_key_auth.enabled + && headers.contains_key(headers::X_INTERNAL_API_KEY) + && headers.contains_key(headers::X_MERCHANT_ID) + && headers.contains_key(headers::X_PROFILE_ID) +} + +#[cfg(feature = "v1")] +pub fn check_internal_api_key_auth<T>( + headers: &HeaderMap, + payload: &impl ClientSecretFetch, + api_auth: ApiKeyAuth, + internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings, +) -> RouterResult<( + Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, + api::AuthFlow, +)> +where + T: SessionStateInfo + Sync + Send, + ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, +{ + if is_internal_api_key_merchant_id_profile_id_auth(headers, internal_api_key_auth) { + Ok(( + // HeaderAuth(api_auth) will never be called in this case as the internal auth will be checked first + Box::new(InternalMerchantIdProfileIdAuth(HeaderAuth(api_auth))), + api::AuthFlow::Merchant, + )) + } else { + check_client_secret_and_get_auth(headers, payload, api_auth) + } +} + pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T> where T: serde::de::DeserializeOwned, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 320488eddd2..c0bd9a58d2c 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -855,3 +855,8 @@ max_retry_count_for_thirty_day = 20 [revenue_recovery.card_config.discover] max_retries_per_day = 20 max_retry_count_for_thirty_day = 20 + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file
2025-09-24T13:54:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces a new authentication mechanism for internal service communication using a shared API key, merchant ID, and profile ID. The changes add configuration options for this authentication method across all environment config files, update the core settings and secrets transformers to support it, and implement the logic for handling requests authenticated via these headers in the payments route and authentication service. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Considering subscription as microservice, payment will be its dependant service, so for all the calls to payments service we need an authentication mechanism instead of using the actual merchant API key auth. so to achieve this we are adding a new authentication which will accept the merchant_id, profile_id and internal_api_key in the request headers and use it for authentication, API key auth/ Fallback auth will be used if one of the required parameter is missing the request. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create Merchant, API Key, Create Connector 2. Create a Payment with API key Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom-dbd' \ --header 'api-key: dev_CLbdgP5Lj11ZF7RfJgM4ck8Qk8AK5yzhEgpPr7d0MmSWC7FvLaQAKKUSOfXBasRD' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"payment_id":"pay_EsecigedwijD3sy0IdXz","merchant_id":"merchant_1758720430","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"cybersource","client_secret":"pay_EsecigedwijD3sy0IdXz_secret_uzmcKlyyzyDvVfJfYav2","created":"2025-09-24T13:44:59.316Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"avs_response":{"code":"Y","codeRaw":"Y"},"card_verification":{"resultCode":"M","resultCodeRaw":"M"}},"authentication_data":null},"billing":null},"payment_token":"token_qdq6SaWLktu6jk7HSVeB","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","origin_zip":null},"phone":{"number":"8056594427","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","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":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":"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":1758721499,"expires":1758725099,"secret":"epk_2ff5fccb274e4aaab7e8802e6c06e54c"},"manual_retry_allowed":null,"connector_transaction_id":"7587215004986946903814","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_EsecigedwijD3sy0IdXz_1","payment_link":null,"profile_id":"pro_W3ToWs6EezKDjps5wTlv","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_4rxNg9ZFdVITFBkrkyWO","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-24T13:59:59.316Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":"016153570198200","payment_method_status":null,"updated":"2025-09-24T13:45:01.180Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` 3. Create a payment without API key and Internal API key Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758720430' \ --header 'x-profile-id: pro_W3ToWs6EezKDjps5wTlv' \ --header 'x-internal-api-key: test_internal_api_key' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"payment_id":"pay_uBRYL3QTCWj5H21GbWTa","merchant_id":"merchant_1758720430","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"cybersource","client_secret":"pay_uBRYL3QTCWj5H21GbWTa_secret_RM3Ch7Ux9P8QPFFxwM5p","created":"2025-09-24T13:46:37.902Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"avs_response":{"code":"Y","codeRaw":"Y"},"card_verification":{"resultCode":"M","resultCodeRaw":"M"}},"authentication_data":null},"billing":null},"payment_token":"token_TBdELmgqZJCVa9guAIIv","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","origin_zip":null},"phone":{"number":"8056594427","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","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":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":"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":1758721597,"expires":1758725197,"secret":"epk_90617482ef1e43e0a833db8cb04fb2e9"},"manual_retry_allowed":null,"connector_transaction_id":"7587215991316984603814","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_uBRYL3QTCWj5H21GbWTa_1","payment_link":null,"profile_id":"pro_W3ToWs6EezKDjps5wTlv","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_4rxNg9ZFdVITFBkrkyWO","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-24T14:01:37.902Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":"016153570198200","payment_method_status":null,"updated":"2025-09-24T13:46:39.783Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` 4. Create a payment with both API key and Internal API key missing Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"error":{"type":"invalid_request","message":"API key not provided or invalid API key used","code":"IR_01"}} ``` 5. Create a payment with API Key and one of the required header missing Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758720430' \ --header 'x-profile-id: pro_W3ToWs6EezKDjps5wTlv' \ --header 'api-key: dev_CLbdgP5Lj11ZF7RfJgM4ck8Qk8AK5yzhEgpPr7d0MmSWC7FvLaQAKKUSOfXBasRD' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"payment_id":"pay_jZTH3Kb5c8W15TZ9lzWN","merchant_id":"merchant_1758720430","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"cybersource","client_secret":"pay_jZTH3Kb5c8W15TZ9lzWN_secret_rLDuvU2PG61w94lS0DTI","created":"2025-09-24T13:48:50.432Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"avs_response":{"code":"Y","codeRaw":"Y"},"card_verification":{"resultCode":"M","resultCodeRaw":"M"}},"authentication_data":null},"billing":null},"payment_token":"token_pthFLPrsyFFd7LKMNIN9","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","origin_zip":null},"phone":{"number":"8056594427","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","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":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":"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":1758721730,"expires":1758725330,"secret":"epk_2bd324735af649278a7afdc0fab609fd"},"manual_retry_allowed":null,"connector_transaction_id":"7587217314886872803813","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_jZTH3Kb5c8W15TZ9lzWN_1","payment_link":null,"profile_id":"pro_W3ToWs6EezKDjps5wTlv","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_4rxNg9ZFdVITFBkrkyWO","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-24T14:03:50.432Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":"016153570198200","payment_method_status":null,"updated":"2025-09-24T13:48:52.097Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` 6. Create a payment with API key and all required headers for Internal API Auth with incorrect internal API key Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758720430' \ --header 'x-profile-id: pro_W3ToWs6EezKDjps5wTlv' \ --header 'x-internal-api-key: test_internal_api_keys' \ --header 'api-key: dev_CLbdgP5Lj11ZF7RfJgM4ck8Qk8AK5yzhEgpPr7d0MmSWC7FvLaQAKKUSOfXBasRD' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"error":{"type":"invalid_request","message":"API key not provided or invalid API key used","code":"IR_01"}} ``` 7. Payment Sync with client secret ``` curl --location 'http://localhost:8080/payments/pay_b5o0Y2uk1KNGXHqTQxCF?client_secret=pay_b5o0Y2uk1KNGXHqTQxCF_secret_CD48nj9Ef7Os5peUPMHt' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_78bec5909ea84a92bee1f6ae9e243ea8' ``` Response ``` { "payment_id": "pay_b5o0Y2uk1KNGXHqTQxCF", "merchant_id": "merchant_1758799800", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "cybersource", "client_secret": "pay_b5o0Y2uk1KNGXHqTQxCF_secret_CD48nj9Ef7Os5peUPMHt", "created": "2025-09-25T14:31:26.721Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_R5qt6L28kHcTGNklyS2v", "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", "origin_zip": null }, "phone": { "number": "8056594427", "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": 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": "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": null, "connector_transaction_id": "7588106881976314703814", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_b5o0Y2uk1KNGXHqTQxCF_1", "payment_link": null, "profile_id": "pro_ZLxuLxjbtAvxP8UluouT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_szN2aVSuqzlKQWlg5Uxx", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-25T14:46:26.721Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": "016153570198200", "payment_method_status": null, "updated": "2025-09-25T14:31:29.010Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 8. Payment Sync with API key ``` curl --location 'http://localhost:8080/payments/pay_b5o0Y2uk1KNGXHqTQxCF' \ --header 'Accept: application/json' \ --header 'api-key: dev_MjuJcRJNsddyqcjvIgQornBitkJdxnLjtpCxWr6kCZ99TacNP92VykGNqyIUgBns' ``` Response ``` { "payment_id": "pay_b5o0Y2uk1KNGXHqTQxCF", "merchant_id": "merchant_1758799800", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "cybersource", "client_secret": "pay_b5o0Y2uk1KNGXHqTQxCF_secret_CD48nj9Ef7Os5peUPMHt", "created": "2025-09-25T14:31:26.721Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_R5qt6L28kHcTGNklyS2v", "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", "origin_zip": null }, "phone": { "number": "8056594427", "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": 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": "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": null, "connector_transaction_id": "7588106881976314703814", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_b5o0Y2uk1KNGXHqTQxCF_1", "payment_link": null, "profile_id": "pro_ZLxuLxjbtAvxP8UluouT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_szN2aVSuqzlKQWlg5Uxx", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-25T14:46:26.721Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": "016153570198200", "payment_method_status": null, "updated": "2025-09-25T14:31:29.010Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 9. Payment Sync with Internal API Key ``` curl --location 'http://localhost:8080/payments/pay_b5o0Y2uk1KNGXHqTQxCF' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758799800' \ --header 'x-profile-id: pro_ZLxuLxjbtAvxP8UluouT' \ --header 'x-internal-api-key: test_internal_api_key' ``` Response ``` {"payment_id":"pay_b5o0Y2uk1KNGXHqTQxCF","merchant_id":"merchant_1758799800","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"cybersource","client_secret":"pay_b5o0Y2uk1KNGXHqTQxCF_secret_CD48nj9Ef7Os5peUPMHt","created":"2025-09-25T14:31:26.721Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"avs_response":{"code":"Y","codeRaw":"Y"},"card_verification":{"resultCode":"M","resultCodeRaw":"M"}},"authentication_data":null},"billing":null},"payment_token":"token_R5qt6L28kHcTGNklyS2v","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","origin_zip":null},"phone":{"number":"8056594427","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","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":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":"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":null,"connector_transaction_id":"7588106881976314703814","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_b5o0Y2uk1KNGXHqTQxCF_1","payment_link":null,"profile_id":"pro_ZLxuLxjbtAvxP8UluouT","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_szN2aVSuqzlKQWlg5Uxx","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-25T14:46:26.721Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":"016153570198200","payment_method_status":null,"updated":"2025-09-25T14:31:29.010Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` 10. Payment Sync with invalid Internal API Key ``` curl --location 'http://localhost:8080/payments/pay_b5o0Y2uk1KNGXHqTQxCF' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758799800' \ --header 'x-profile-id: pro_ZLxuLxjbtAvxP8UluouT' \ --header 'x-internal-api-key: test_internal_api_keys' ``` Response ``` { "error": { "type": "invalid_request", "message": "API key not provided or invalid API key used", "code": "IR_01" } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f02d18038c854466907ef7d296f97bc921c60a90
juspay/hyperswitch
juspay__hyperswitch-9548
Bug: add new authentication to communicate between Subscription microservice and payments microservice
diff --git a/config/config.example.toml b/config/config.example.toml index 91966eaab12..d7273fe35b3 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1269,3 +1269,8 @@ encryption_key = "" # Key to encrypt and decrypt chat proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] connector_list = "worldpayvantiv" + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index b798d912dc9..d48ab2d148d 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -24,6 +24,10 @@ queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 clie [api_keys] hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # API key hashing key. +[internal_merchant_id_profile_id_auth] +enabled = false +internal_api_key = "test_internal_api_key" + [applepay_decrypt_keys] apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" # Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key generated by Elliptic-curve prime256v1 curve. You can use `openssl ecparam -out private.key -name prime256v1 -genkey` to generate the private key diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 8219ccf2206..489a865426c 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -904,3 +904,8 @@ connector_list = "worldpayvantiv" [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 394067bd85a..c4247d27839 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -914,3 +914,8 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 07333518f64..052f8d1cae2 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -922,3 +922,8 @@ connector_list = "worldpayvantiv" [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/config/development.toml b/config/development.toml index 06283933305..70fca988bad 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1383,3 +1383,7 @@ encryption_key = "" proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] connector_list = "worldpayvantiv" + +[internal_merchant_id_profile_id_auth] +enabled = false +internal_api_key = "test_internal_api_key" \ No newline at end of file diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 881de3aa4dc..0d77e4c66a5 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1278,3 +1278,8 @@ version = "HOSTNAME" # value of HOSTNAME from deployment which tells its proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] connector_list = "worldpayvantiv" + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 53ce32b033e..67b6854922a 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -576,6 +576,7 @@ pub(crate) async fn fetch_raw_secrets( debit_routing_config: conf.debit_routing_config, clone_connector_allowlist: conf.clone_connector_allowlist, merchant_id_auth: conf.merchant_id_auth, + internal_merchant_id_profile_id_auth: conf.internal_merchant_id_profile_id_auth, infra_values: conf.infra_values, enhancement: conf.enhancement, proxy_status_mapping: conf.proxy_status_mapping, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 1923af66b35..5b669885d24 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -163,6 +163,7 @@ pub struct Settings<S: SecretState> { pub revenue_recovery: revenue_recovery::RevenueRecoverySettings, pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>, pub merchant_id_auth: MerchantIdAuthSettings, + pub internal_merchant_id_profile_id_auth: InternalMerchantIdProfileIdAuthSettings, #[serde(default)] pub infra_values: Option<HashMap<String, String>>, #[serde(default)] @@ -849,6 +850,13 @@ pub struct MerchantIdAuthSettings { pub merchant_id_auth_enabled: bool, } +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct InternalMerchantIdProfileIdAuthSettings { + pub enabled: bool, + pub internal_api_key: Secret<String>, +} + #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct ProxyStatusMapping { diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index c746410aa0d..679ef8aff32 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -67,6 +67,7 @@ pub mod headers { pub const X_API_VERSION: &str = "X-ApiVersion"; pub const X_FORWARDED_FOR: &str = "X-Forwarded-For"; pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; + pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key"; pub const X_ORGANIZATION_ID: &str = "X-Organization-Id"; pub const X_LOGIN: &str = "X-Login"; pub const X_TRANS_KEY: &str = "X-Trans-Key"; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0d7da850f11..6aee34e8256 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1174,7 +1174,7 @@ pub struct Subscription; #[cfg(all(feature = "oltp", feature = "v1"))] impl Subscription { pub fn server(state: AppState) -> Scope { - let route = web::scope("/subscription").app_data(web::Data::new(state.clone())); + let route = web::scope("/subscriptions").app_data(web::Data::new(state.clone())); route .service(web::resource("/create").route( diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index c1970b64c28..3bf2f472837 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -78,6 +78,25 @@ pub async fn payments_create( let locking_action = payload.get_locking_input(flow.clone()); + let auth_type = match env::which() { + env::Env::Production => { + &auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: true, + })) + } + _ => auth::auth_type( + &auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: true, + })), + &auth::InternalMerchantIdProfileIdAuth(auth::JWTAuth { + permission: Permission::ProfilePaymentWrite, + }), + req.headers(), + ), + }; + Box::pin(api::server_wrap( flow, state, @@ -98,22 +117,7 @@ pub async fn payments_create( api::AuthFlow::Client, ) }, - match env::which() { - env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth { - is_connected_allowed: false, - is_platform_allowed: true, - }), - _ => auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth { - is_connected_allowed: false, - is_platform_allowed: true, - }), - &auth::JWTAuth { - permission: Permission::ProfilePaymentWrite, - }, - req.headers(), - ), - }, + auth_type, locking_action, )) .await @@ -569,11 +573,15 @@ pub async fn payments_retrieve( is_platform_allowed: true, }; - let (auth_type, auth_flow) = - match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { - Ok(auth) => auth, - Err(err) => return api::log_and_return_error_response(report!(err)), - }; + let (auth_type, auth_flow) = match auth::check_internal_api_key_auth( + req.headers(), + &payload, + api_auth, + state.conf.internal_merchant_id_profile_id_auth.clone(), + ) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(report!(err)), + }; let locking_action = payload.get_locking_input(flow.clone()); diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 851c2cf21b9..13d224a1cd7 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -38,6 +38,7 @@ use crate::core::errors::UserResult; #[cfg(all(feature = "partial-auth", feature = "v1"))] use crate::core::metrics; use crate::{ + configs::settings, core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, @@ -155,6 +156,10 @@ pub enum AuthenticationType { WebhookAuth { merchant_id: id_type::MerchantId, }, + InternalMerchantIdProfileId { + merchant_id: id_type::MerchantId, + profile_id: Option<id_type::ProfileId>, + }, NoAuth, } @@ -184,7 +189,8 @@ impl AuthenticationType { user_id: _, } | Self::MerchantJwtWithProfileId { merchant_id, .. } - | Self::WebhookAuth { merchant_id } => Some(merchant_id), + | Self::WebhookAuth { merchant_id } + | Self::InternalMerchantIdProfileId { merchant_id, .. } => Some(merchant_id), Self::AdminApiKey | Self::OrganizationJwt { .. } | Self::UserJwt { .. } @@ -1958,6 +1964,10 @@ impl<'a> HeaderMapStruct<'a> { }) } + pub fn get_header_value_by_key(&self, key: &str) -> Option<&str> { + self.headers.get(key).and_then(|value| value.to_str().ok()) + } + pub fn get_auth_string_from_header(&self) -> RouterResult<&str> { self.headers .get(headers::AUTHORIZATION) @@ -2309,6 +2319,96 @@ where } } +/// InternalMerchantIdProfileIdAuth authentication which first tries to authenticate using `X-Internal-API-Key`, +/// `X-Merchant-Id` and `X-Profile-Id` headers. If any of these headers are missing, +/// it falls back to the provided authentication mechanism. +#[cfg(feature = "v1")] +pub struct InternalMerchantIdProfileIdAuth<F>(pub F); + +#[cfg(feature = "v1")] +#[async_trait] +impl<A, F> AuthenticateAndFetch<AuthenticationData, A> for InternalMerchantIdProfileIdAuth<F> +where + A: SessionStateInfo + Sync + Send, + F: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + if !state.conf().internal_merchant_id_profile_id_auth.enabled { + return self.0.authenticate_and_fetch(request_headers, state).await; + } + let merchant_id = HeaderMapStruct::new(request_headers) + .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID) + .ok(); + let internal_api_key = HeaderMapStruct::new(request_headers) + .get_header_value_by_key(headers::X_INTERNAL_API_KEY) + .map(|s| s.to_string()); + let profile_id = HeaderMapStruct::new(request_headers) + .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID) + .ok(); + if let (Some(internal_api_key), Some(merchant_id), Some(profile_id)) = + (internal_api_key, merchant_id, profile_id) + { + let config = state.conf(); + if internal_api_key + != *config + .internal_merchant_id_profile_id_auth + .internal_api_key + .peek() + { + return Err(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Internal API key authentication failed"); + } + 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 _profile = state + .store() + .find_business_profile_by_merchant_id_profile_id( + key_manager_state, + &key_store, + &merchant_id, + &profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + 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)?; + let auth = AuthenticationData { + merchant_account: merchant, + key_store, + profile_id: Some(profile_id.clone()), + platform_merchant_account: None, + }; + Ok(( + auth.clone(), + AuthenticationType::InternalMerchantIdProfileId { + merchant_id, + profile_id: Some(profile_id), + }, + )) + } else { + Ok(self + .0 + .authenticate_and_fetch(request_headers, state) + .await?) + } + } +} + #[derive(Debug)] #[cfg(feature = "v2")] pub struct MerchantIdAndProfileIdAuth { @@ -4362,6 +4462,41 @@ pub fn is_jwt_auth(headers: &HeaderMap) -> bool { } } +pub fn is_internal_api_key_merchant_id_profile_id_auth( + headers: &HeaderMap, + internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings, +) -> bool { + internal_api_key_auth.enabled + && headers.contains_key(headers::X_INTERNAL_API_KEY) + && headers.contains_key(headers::X_MERCHANT_ID) + && headers.contains_key(headers::X_PROFILE_ID) +} + +#[cfg(feature = "v1")] +pub fn check_internal_api_key_auth<T>( + headers: &HeaderMap, + payload: &impl ClientSecretFetch, + api_auth: ApiKeyAuth, + internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings, +) -> RouterResult<( + Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, + api::AuthFlow, +)> +where + T: SessionStateInfo + Sync + Send, + ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, +{ + if is_internal_api_key_merchant_id_profile_id_auth(headers, internal_api_key_auth) { + Ok(( + // HeaderAuth(api_auth) will never be called in this case as the internal auth will be checked first + Box::new(InternalMerchantIdProfileIdAuth(HeaderAuth(api_auth))), + api::AuthFlow::Merchant, + )) + } else { + check_client_secret_and_get_auth(headers, payload, api_auth) + } +} + pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T> where T: serde::de::DeserializeOwned, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 320488eddd2..c0bd9a58d2c 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -855,3 +855,8 @@ max_retry_count_for_thirty_day = 20 [revenue_recovery.card_config.discover] max_retries_per_day = 20 max_retry_count_for_thirty_day = 20 + +# Authentication to communicate between internal services using common_api_key, merchant id and profile id +[internal_merchant_id_profile_id_auth] +enabled = false # Enable or disable internal api key, merchant id and profile id based authentication +internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication \ No newline at end of file
2025-09-24T13:54:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces a new authentication mechanism for internal service communication using a shared API key, merchant ID, and profile ID. The changes add configuration options for this authentication method across all environment config files, update the core settings and secrets transformers to support it, and implement the logic for handling requests authenticated via these headers in the payments route and authentication service. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Considering subscription as microservice, payment will be its dependant service, so for all the calls to payments service we need an authentication mechanism instead of using the actual merchant API key auth. so to achieve this we are adding a new authentication which will accept the merchant_id, profile_id and internal_api_key in the request headers and use it for authentication, API key auth/ Fallback auth will be used if one of the required parameter is missing the request. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create Merchant, API Key, Create Connector 2. Create a Payment with API key Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom-dbd' \ --header 'api-key: dev_CLbdgP5Lj11ZF7RfJgM4ck8Qk8AK5yzhEgpPr7d0MmSWC7FvLaQAKKUSOfXBasRD' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"payment_id":"pay_EsecigedwijD3sy0IdXz","merchant_id":"merchant_1758720430","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"cybersource","client_secret":"pay_EsecigedwijD3sy0IdXz_secret_uzmcKlyyzyDvVfJfYav2","created":"2025-09-24T13:44:59.316Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"avs_response":{"code":"Y","codeRaw":"Y"},"card_verification":{"resultCode":"M","resultCodeRaw":"M"}},"authentication_data":null},"billing":null},"payment_token":"token_qdq6SaWLktu6jk7HSVeB","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","origin_zip":null},"phone":{"number":"8056594427","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","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":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":"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":1758721499,"expires":1758725099,"secret":"epk_2ff5fccb274e4aaab7e8802e6c06e54c"},"manual_retry_allowed":null,"connector_transaction_id":"7587215004986946903814","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_EsecigedwijD3sy0IdXz_1","payment_link":null,"profile_id":"pro_W3ToWs6EezKDjps5wTlv","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_4rxNg9ZFdVITFBkrkyWO","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-24T13:59:59.316Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":"016153570198200","payment_method_status":null,"updated":"2025-09-24T13:45:01.180Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` 3. Create a payment without API key and Internal API key Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758720430' \ --header 'x-profile-id: pro_W3ToWs6EezKDjps5wTlv' \ --header 'x-internal-api-key: test_internal_api_key' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"payment_id":"pay_uBRYL3QTCWj5H21GbWTa","merchant_id":"merchant_1758720430","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"cybersource","client_secret":"pay_uBRYL3QTCWj5H21GbWTa_secret_RM3Ch7Ux9P8QPFFxwM5p","created":"2025-09-24T13:46:37.902Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"avs_response":{"code":"Y","codeRaw":"Y"},"card_verification":{"resultCode":"M","resultCodeRaw":"M"}},"authentication_data":null},"billing":null},"payment_token":"token_TBdELmgqZJCVa9guAIIv","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","origin_zip":null},"phone":{"number":"8056594427","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","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":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":"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":1758721597,"expires":1758725197,"secret":"epk_90617482ef1e43e0a833db8cb04fb2e9"},"manual_retry_allowed":null,"connector_transaction_id":"7587215991316984603814","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_uBRYL3QTCWj5H21GbWTa_1","payment_link":null,"profile_id":"pro_W3ToWs6EezKDjps5wTlv","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_4rxNg9ZFdVITFBkrkyWO","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-24T14:01:37.902Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":"016153570198200","payment_method_status":null,"updated":"2025-09-24T13:46:39.783Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` 4. Create a payment with both API key and Internal API key missing Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"error":{"type":"invalid_request","message":"API key not provided or invalid API key used","code":"IR_01"}} ``` 5. Create a payment with API Key and one of the required header missing Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758720430' \ --header 'x-profile-id: pro_W3ToWs6EezKDjps5wTlv' \ --header 'api-key: dev_CLbdgP5Lj11ZF7RfJgM4ck8Qk8AK5yzhEgpPr7d0MmSWC7FvLaQAKKUSOfXBasRD' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"payment_id":"pay_jZTH3Kb5c8W15TZ9lzWN","merchant_id":"merchant_1758720430","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"cybersource","client_secret":"pay_jZTH3Kb5c8W15TZ9lzWN_secret_rLDuvU2PG61w94lS0DTI","created":"2025-09-24T13:48:50.432Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"avs_response":{"code":"Y","codeRaw":"Y"},"card_verification":{"resultCode":"M","resultCodeRaw":"M"}},"authentication_data":null},"billing":null},"payment_token":"token_pthFLPrsyFFd7LKMNIN9","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","origin_zip":null},"phone":{"number":"8056594427","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","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":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":"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":1758721730,"expires":1758725330,"secret":"epk_2bd324735af649278a7afdc0fab609fd"},"manual_retry_allowed":null,"connector_transaction_id":"7587217314886872803813","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_jZTH3Kb5c8W15TZ9lzWN_1","payment_link":null,"profile_id":"pro_W3ToWs6EezKDjps5wTlv","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_4rxNg9ZFdVITFBkrkyWO","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-24T14:03:50.432Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":"016153570198200","payment_method_status":null,"updated":"2025-09-24T13:48:52.097Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` 6. Create a payment with API key and all required headers for Internal API Auth with incorrect internal API key Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758720430' \ --header 'x-profile-id: pro_W3ToWs6EezKDjps5wTlv' \ --header 'x-internal-api-key: test_internal_api_keys' \ --header 'api-key: dev_CLbdgP5Lj11ZF7RfJgM4ck8Qk8AK5yzhEgpPr7d0MmSWC7FvLaQAKKUSOfXBasRD' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` {"error":{"type":"invalid_request","message":"API key not provided or invalid API key used","code":"IR_01"}} ``` 7. Payment Sync with client secret ``` curl --location 'http://localhost:8080/payments/pay_b5o0Y2uk1KNGXHqTQxCF?client_secret=pay_b5o0Y2uk1KNGXHqTQxCF_secret_CD48nj9Ef7Os5peUPMHt' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_78bec5909ea84a92bee1f6ae9e243ea8' ``` Response ``` { "payment_id": "pay_b5o0Y2uk1KNGXHqTQxCF", "merchant_id": "merchant_1758799800", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "cybersource", "client_secret": "pay_b5o0Y2uk1KNGXHqTQxCF_secret_CD48nj9Ef7Os5peUPMHt", "created": "2025-09-25T14:31:26.721Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_R5qt6L28kHcTGNklyS2v", "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", "origin_zip": null }, "phone": { "number": "8056594427", "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": 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": "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": null, "connector_transaction_id": "7588106881976314703814", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_b5o0Y2uk1KNGXHqTQxCF_1", "payment_link": null, "profile_id": "pro_ZLxuLxjbtAvxP8UluouT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_szN2aVSuqzlKQWlg5Uxx", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-25T14:46:26.721Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": "016153570198200", "payment_method_status": null, "updated": "2025-09-25T14:31:29.010Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 8. Payment Sync with API key ``` curl --location 'http://localhost:8080/payments/pay_b5o0Y2uk1KNGXHqTQxCF' \ --header 'Accept: application/json' \ --header 'api-key: dev_MjuJcRJNsddyqcjvIgQornBitkJdxnLjtpCxWr6kCZ99TacNP92VykGNqyIUgBns' ``` Response ``` { "payment_id": "pay_b5o0Y2uk1KNGXHqTQxCF", "merchant_id": "merchant_1758799800", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "cybersource", "client_secret": "pay_b5o0Y2uk1KNGXHqTQxCF_secret_CD48nj9Ef7Os5peUPMHt", "created": "2025-09-25T14:31:26.721Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_R5qt6L28kHcTGNklyS2v", "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", "origin_zip": null }, "phone": { "number": "8056594427", "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": 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": "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": null, "connector_transaction_id": "7588106881976314703814", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_b5o0Y2uk1KNGXHqTQxCF_1", "payment_link": null, "profile_id": "pro_ZLxuLxjbtAvxP8UluouT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_szN2aVSuqzlKQWlg5Uxx", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-25T14:46:26.721Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": "016153570198200", "payment_method_status": null, "updated": "2025-09-25T14:31:29.010Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 9. Payment Sync with Internal API Key ``` curl --location 'http://localhost:8080/payments/pay_b5o0Y2uk1KNGXHqTQxCF' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758799800' \ --header 'x-profile-id: pro_ZLxuLxjbtAvxP8UluouT' \ --header 'x-internal-api-key: test_internal_api_key' ``` Response ``` {"payment_id":"pay_b5o0Y2uk1KNGXHqTQxCF","merchant_id":"merchant_1758799800","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"cybersource","client_secret":"pay_b5o0Y2uk1KNGXHqTQxCF_secret_CD48nj9Ef7Os5peUPMHt","created":"2025-09-25T14:31:26.721Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"avs_response":{"code":"Y","codeRaw":"Y"},"card_verification":{"resultCode":"M","resultCodeRaw":"M"}},"authentication_data":null},"billing":null},"payment_token":"token_R5qt6L28kHcTGNklyS2v","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","origin_zip":null},"phone":{"number":"8056594427","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","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":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":"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":null,"connector_transaction_id":"7588106881976314703814","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_b5o0Y2uk1KNGXHqTQxCF_1","payment_link":null,"profile_id":"pro_ZLxuLxjbtAvxP8UluouT","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_szN2aVSuqzlKQWlg5Uxx","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-25T14:46:26.721Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":"016153570198200","payment_method_status":null,"updated":"2025-09-25T14:31:29.010Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` 10. Payment Sync with invalid Internal API Key ``` curl --location 'http://localhost:8080/payments/pay_b5o0Y2uk1KNGXHqTQxCF' \ --header 'Accept: application/json' \ --header 'x-merchant-id: merchant_1758799800' \ --header 'x-profile-id: pro_ZLxuLxjbtAvxP8UluouT' \ --header 'x-internal-api-key: test_internal_api_keys' ``` Response ``` { "error": { "type": "invalid_request", "message": "API key not provided or invalid API key used", "code": "IR_01" } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f02d18038c854466907ef7d296f97bc921c60a90
juspay/hyperswitch
juspay__hyperswitch-9542
Bug: [FEATURE] Add resume api to resume/continue the tasks in process tracker for revenue_recovery Add resume api to resume/continue the tasks in process tracker for revenue_recovery. This PR enables us to resume the EXECUTE and CALCULATE that are stuck in an intermediate state .
diff --git a/crates/api_models/src/events/revenue_recovery.rs b/crates/api_models/src/events/revenue_recovery.rs index 8327dfdded2..ee6bf464d1f 100644 --- a/crates/api_models/src/events/revenue_recovery.rs +++ b/crates/api_models/src/events/revenue_recovery.rs @@ -1,6 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; -use crate::process_tracker::revenue_recovery::{RevenueRecoveryId, RevenueRecoveryResponse}; +use crate::process_tracker::revenue_recovery::{ + RevenueRecoveryId, RevenueRecoveryResponse, RevenueRecoveryRetriggerRequest, +}; impl ApiEventMetric for RevenueRecoveryResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { @@ -12,3 +14,8 @@ impl ApiEventMetric for RevenueRecoveryId { Some(ApiEventsType::ProcessTracker) } } +impl ApiEventMetric for RevenueRecoveryRetriggerRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::ProcessTracker) + } +} diff --git a/crates/api_models/src/process_tracker/revenue_recovery.rs b/crates/api_models/src/process_tracker/revenue_recovery.rs index 7baeb547a68..131766e72d5 100644 --- a/crates/api_models/src/process_tracker/revenue_recovery.rs +++ b/crates/api_models/src/process_tracker/revenue_recovery.rs @@ -8,7 +8,11 @@ use crate::enums; pub struct RevenueRecoveryResponse { pub id: String, pub name: Option<String>, + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub schedule_time_for_payment: Option<PrimitiveDateTime>, + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub schedule_time_for_psync: Option<PrimitiveDateTime>, #[schema(value_type = ProcessTrackerStatus, example = "finish")] pub status: enums::ProcessTrackerStatus, @@ -19,3 +23,17 @@ pub struct RevenueRecoveryResponse { pub struct RevenueRecoveryId { pub revenue_recovery_id: id_type::GlobalPaymentId, } + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct RevenueRecoveryRetriggerRequest { + /// The task we want to resume + pub revenue_recovery_task: String, + /// Time at which the job was scheduled at + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub schedule_time: Option<PrimitiveDateTime>, + /// Status of The Process Tracker Task + pub status: enums::ProcessTrackerStatus, + /// Business Status of The Process Tracker Task + pub business_status: String, +} diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index f9662a745dd..dee8a6ee9ff 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -5,7 +5,7 @@ use std::marker::PhantomData; use api_models::{ enums, - payments::{self as api_payments, PaymentsResponse}, + payments::{self as api_payments, PaymentsGetIntentRequest, PaymentsResponse}, process_tracker::revenue_recovery, webhooks, }; @@ -16,10 +16,10 @@ use common_utils::{ id_type, }; use diesel_models::{enums as diesel_enum, process_tracker::business_status}; -use error_stack::{self, ResultExt}; +use error_stack::{self, report, ResultExt}; use hyperswitch_domain_models::{ merchant_context, - payments::{PaymentIntent, PaymentStatusData}, + payments::{PaymentIntent, PaymentIntentData, PaymentStatusData}, revenue_recovery as domain_revenue_recovery, ApiModelToDieselModelConvertor, }; use scheduler::errors as sch_errors; @@ -43,12 +43,11 @@ use crate::{ storage::{self, revenue_recovery as pcr}, transformers::{ForeignFrom, ForeignInto}, }, - workflows, + workflows::revenue_recovery as revenue_recovery_workflow, }; - -pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW"; -pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW"; pub const CALCULATE_WORKFLOW: &str = "CALCULATE_WORKFLOW"; +pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW"; +pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW"; #[allow(clippy::too_many_arguments)] pub async fn upsert_calculate_pcr_task( @@ -530,25 +529,26 @@ pub async fn perform_calculate_workflow( .await?; // 2. Get best available token - let best_time_to_schedule = match workflows::revenue_recovery::get_token_with_schedule_time_based_on_retry_algorithm_type( - state, - &connector_customer_id, - payment_intent, - retry_algorithm_type, - process.retry_count, - ) - .await - { - Ok(token_opt) => token_opt, - Err(e) => { - logger::error!( - error = ?e, - connector_customer_id = %connector_customer_id, - "Failed to get best PSP token" - ); - None - } - }; + let best_time_to_schedule = + match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type( + state, + &connector_customer_id, + payment_intent, + retry_algorithm_type, + process.retry_count, + ) + .await + { + Ok(token_opt) => token_opt, + Err(e) => { + logger::error!( + error = ?e, + connector_customer_id = %connector_customer_id, + "Failed to get best PSP token" + ); + None + } + }; match best_time_to_schedule { Some(scheduled_time) => { @@ -1017,6 +1017,116 @@ pub async fn retrieve_revenue_recovery_process_tracker( Ok(ApplicationResponse::Json(response)) } +pub async fn resume_revenue_recovery_process_tracker( + state: SessionState, + id: id_type::GlobalPaymentId, + request_retrigger: revenue_recovery::RevenueRecoveryRetriggerRequest, +) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> { + let db = &*state.store; + let task = request_retrigger.revenue_recovery_task; + let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; + let process_tracker_id = id.get_execute_revenue_recovery_id(&task, runner); + + let process_tracker = db + .find_process_by_id(&process_tracker_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) + .attach_printable("error retrieving the process tracker id")? + .get_required_value("Process Tracker") + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Entry For the following id doesn't exists".to_owned(), + })?; + + let tracking_data = process_tracker + .tracking_data + .clone() + .parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize Pcr Workflow Tracking Data")?; + + //Call payment intent to check the status + let request = PaymentsGetIntentRequest { id: id.clone() }; + let revenue_recovery_payment_data = + revenue_recovery_workflow::extract_data_and_perform_action(&state, &tracking_data) + .await + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Failed to extract the revenue recovery data".to_owned(), + })?; + let merchant_context_from_revenue_recovery_payment_data = + domain::MerchantContext::NormalMerchant(Box::new(domain::Context( + revenue_recovery_payment_data.merchant_account.clone(), + revenue_recovery_payment_data.key_store.clone(), + ))); + let create_intent_response = payments::payments_intent_core::< + router_api_types::PaymentGetIntent, + router_api_types::payments::PaymentsIntentResponse, + _, + _, + PaymentIntentData<router_api_types::PaymentGetIntent>, + >( + state.clone(), + state.get_req_state(), + merchant_context_from_revenue_recovery_payment_data, + revenue_recovery_payment_data.profile.clone(), + payments::operations::PaymentGetIntent, + request, + tracking_data.global_payment_id.clone(), + hyperswitch_domain_models::payments::HeaderPayload::default(), + ) + .await?; + + let response = create_intent_response + .get_json_body() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unexpected response from payments core")?; + + match response.status { + enums::IntentStatus::Failed => { + let pt_update = storage::ProcessTrackerUpdate::Update { + name: process_tracker.name.clone(), + tracking_data: Some(process_tracker.tracking_data.clone()), + business_status: Some(request_retrigger.business_status.clone()), + status: Some(request_retrigger.status), + updated_at: Some(common_utils::date_time::now()), + retry_count: Some(process_tracker.retry_count + 1), + schedule_time: Some(request_retrigger.schedule_time.unwrap_or( + common_utils::date_time::now().saturating_add(time::Duration::seconds(600)), + )), + }; + let updated_pt = db + .update_process(process_tracker, pt_update) + .await + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Failed to update the process tracker".to_owned(), + })?; + let response = revenue_recovery::RevenueRecoveryResponse { + id: updated_pt.id, + name: updated_pt.name, + schedule_time_for_payment: updated_pt.schedule_time, + schedule_time_for_psync: None, + status: updated_pt.status, + business_status: updated_pt.business_status, + }; + Ok(ApplicationResponse::Json(response)) + } + enums::IntentStatus::Succeeded + | enums::IntentStatus::Cancelled + | enums::IntentStatus::CancelledPostCapture + | enums::IntentStatus::Processing + | enums::IntentStatus::RequiresCustomerAction + | enums::IntentStatus::RequiresMerchantAction + | enums::IntentStatus::RequiresPaymentMethod + | enums::IntentStatus::RequiresConfirmation + | enums::IntentStatus::RequiresCapture + | enums::IntentStatus::PartiallyCaptured + | enums::IntentStatus::PartiallyCapturedAndCapturable + | enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture + | enums::IntentStatus::Conflicted + | enums::IntentStatus::Expired => Err(report!(errors::ApiErrorResponse::NotSupported { + message: "Invalid Payment Status ".to_owned(), + })), + } +} pub async fn get_payment_response_using_payment_get_operation( state: &SessionState, payment_intent_id: &id_type::GlobalPaymentId, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 56ebfa66062..1de0029f767 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2944,8 +2944,16 @@ impl ProcessTracker { web::scope("/v2/process-trackers/revenue-recovery-workflow") .app_data(web::Data::new(state.clone())) .service( - web::resource("/{revenue_recovery_id}") - .route(web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api)), + web::scope("/{revenue_recovery_id}") + .service( + web::resource("").route( + web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api), + ), + ) + .service( + web::resource("/resume") + .route(web::post().to(revenue_recovery::revenue_recovery_resume_api)), + ), ) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 63972a938fe..992edb61c35 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -63,11 +63,9 @@ impl From<Flow> for ApiIdentifier { | Flow::MerchantTransferKey | Flow::MerchantAccountList | Flow::EnablePlatformAccount => Self::MerchantAccount, - Flow::OrganizationCreate | Flow::OrganizationRetrieve | Flow::OrganizationUpdate => { Self::Organization } - Flow::RoutingCreateConfig | Flow::RoutingLinkConfig | Flow::RoutingUnlinkConfig @@ -93,36 +91,29 @@ impl From<Flow> for ApiIdentifier { Flow::CreateSubscription => Self::Subscription, Flow::RetrieveForexFlow => Self::Forex, - Flow::AddToBlocklist => Self::Blocklist, Flow::DeleteFromBlocklist => Self::Blocklist, Flow::ListBlocklist => Self::Blocklist, Flow::ToggleBlocklistGuard => Self::Blocklist, - Flow::MerchantConnectorsCreate | Flow::MerchantConnectorsRetrieve | Flow::MerchantConnectorsUpdate | Flow::MerchantConnectorsDelete | Flow::MerchantConnectorsList => Self::MerchantConnector, - Flow::ConfigKeyCreate | Flow::ConfigKeyFetch | Flow::ConfigKeyUpdate | Flow::ConfigKeyDelete | Flow::CreateConfigKey => Self::Configs, - Flow::CustomersCreate | Flow::CustomersRetrieve | Flow::CustomersUpdate | Flow::CustomersDelete | Flow::CustomersGetMandates | Flow::CustomersList => Self::Customers, - Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral, - Flow::DeepHealthCheck | Flow::HealthCheck => Self::Health, Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates, - Flow::PaymentMethodsCreate | Flow::PaymentMethodsMigrate | Flow::PaymentMethodsBatchUpdate @@ -138,9 +129,7 @@ impl From<Flow> for ApiIdentifier { | Flow::DefaultPaymentMethodsSet | Flow::PaymentMethodSave | Flow::TotalPaymentMethodCount => Self::PaymentMethods, - Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth, - Flow::PaymentsCreate | Flow::PaymentsRetrieve | Flow::PaymentsRetrieveForceSync @@ -177,7 +166,6 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsRetrieveUsingMerchantReferenceId | Flow::PaymentAttemptsList | Flow::RecoveryPaymentsCreate => Self::Payments, - Flow::PayoutsCreate | Flow::PayoutsRetrieve | Flow::PayoutsUpdate @@ -188,7 +176,6 @@ impl From<Flow> for ApiIdentifier { | Flow::PayoutsAccounts | Flow::PayoutsConfirm | Flow::PayoutLinkInitiate => Self::Payouts, - Flow::RefundsCreate | Flow::RefundsRetrieve | Flow::RefundsRetrieveForceSync @@ -198,7 +185,6 @@ impl From<Flow> for ApiIdentifier { | Flow::RefundsAggregate | Flow::RefundsManualUpdate => Self::Refunds, Flow::Relay | Flow::RelayRetrieve => Self::Relay, - Flow::FrmFulfillment | Flow::IncomingWebhookReceive | Flow::IncomingRelayWebhookReceive @@ -207,13 +193,11 @@ impl From<Flow> for ApiIdentifier { | Flow::WebhookEventDeliveryRetry | Flow::RecoveryIncomingWebhookReceive | Flow::IncomingNetworkTokenWebhookReceive => Self::Webhooks, - Flow::ApiKeyCreate | Flow::ApiKeyRetrieve | Flow::ApiKeyUpdate | Flow::ApiKeyRevoke | Flow::ApiKeyList => Self::ApiKeys, - Flow::DisputesRetrieve | Flow::DisputesList | Flow::DisputesFilters @@ -222,16 +206,12 @@ impl From<Flow> for ApiIdentifier { | Flow::RetrieveDisputeEvidence | Flow::DisputesAggregate | Flow::DeleteDisputeEvidence => Self::Disputes, - Flow::CardsInfo | Flow::CardsInfoCreate | Flow::CardsInfoUpdate | Flow::CardsInfoMigrate => Self::CardsInfo, - Flow::CreateFile | Flow::DeleteFile | Flow::RetrieveFile => Self::Files, - Flow::CacheInvalidate => Self::Cache, - Flow::ProfileCreate | Flow::ProfileUpdate | Flow::ProfileRetrieve @@ -239,23 +219,18 @@ impl From<Flow> for ApiIdentifier { | Flow::ProfileList | Flow::ToggleExtendedCardInfo | Flow::ToggleConnectorAgnosticMit => Self::Profile, - Flow::PaymentLinkRetrieve | Flow::PaymentLinkInitiate | Flow::PaymentSecureLinkInitiate | Flow::PaymentLinkList | Flow::PaymentLinkStatus => Self::PaymentLink, - Flow::Verification => Self::Verification, - Flow::RustLockerMigration => Self::RustLockerMigration, Flow::GsmRuleCreate | Flow::GsmRuleRetrieve | Flow::GsmRuleUpdate | Flow::GsmRuleDelete => Self::Gsm, - Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration, - Flow::UserConnectAccount | Flow::UserSignUp | Flow::UserSignIn @@ -341,44 +316,34 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateRole | Flow::UserFromEmail | Flow::ListUsersInLineage => Self::UserRole, - Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding } - Flow::ReconMerchantUpdate | Flow::ReconTokenRequest | Flow::ReconServiceRequest | Flow::ReconVerifyToken => Self::Recon, - Flow::RetrievePollStatus => Self::Poll, - Flow::FeatureMatrix => Self::Documentation, - Flow::TokenizeCard | Flow::TokenizeCardUsingPaymentMethodId | Flow::TokenizeCardBatch => Self::CardNetworkTokenization, - Flow::HypersenseTokenRequest | Flow::HypersenseVerifyToken | Flow::HypersenseSignoutToken => Self::Hypersense, - Flow::PaymentMethodSessionCreate | Flow::PaymentMethodSessionRetrieve | Flow::PaymentMethodSessionConfirm | Flow::PaymentMethodSessionUpdateSavedPaymentMethod | Flow::PaymentMethodSessionDeleteSavedPaymentMethod | Flow::PaymentMethodSessionUpdate => Self::PaymentMethodSession, - - Flow::RevenueRecoveryRetrieve => Self::ProcessTracker, - + Flow::RevenueRecoveryRetrieve | Flow::RevenueRecoveryResume => Self::ProcessTracker, Flow::AuthenticationCreate | Flow::AuthenticationEligibility | Flow::AuthenticationSync | Flow::AuthenticationSyncPostUpdate | Flow::AuthenticationAuthenticate => Self::Authentication, Flow::Proxy => Self::Proxy, - Flow::ProfileAcquirerCreate | Flow::ProfileAcquirerUpdate => Self::ProfileAcquirer, Flow::ThreeDsDecisionRuleExecute => Self::ThreeDsDecisionRule, Flow::TokenizationCreate | Flow::TokenizationRetrieve | Flow::TokenizationDelete => { diff --git a/crates/router/src/routes/process_tracker/revenue_recovery.rs b/crates/router/src/routes/process_tracker/revenue_recovery.rs index b0deb62fa87..db939436c61 100644 --- a/crates/router/src/routes/process_tracker/revenue_recovery.rs +++ b/crates/router/src/routes/process_tracker/revenue_recovery.rs @@ -37,3 +37,27 @@ pub async fn revenue_recovery_pt_retrieve_api( )) .await } + +pub async fn revenue_recovery_resume_api( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<common_utils::id_type::GlobalPaymentId>, + json_payload: web::Json<revenue_recovery_api::RevenueRecoveryRetriggerRequest>, +) -> HttpResponse { + let flow = Flow::RevenueRecoveryResume; + let id = path.into_inner(); + let payload = json_payload.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, _, payload, _| { + revenue_recovery::resume_revenue_recovery_process_tracker(state, id.clone(), payload) + }, + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ace7635bf40..50c47489108 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -620,6 +620,8 @@ pub enum Flow { TotalPaymentMethodCount, /// Process Tracker Revenue Recovery Workflow Retrieve RevenueRecoveryRetrieve, + /// Process Tracker Revenue Recovery Workflow Resume + RevenueRecoveryResume, /// Tokenization flow TokenizationCreate, /// Tokenization retrieve flow
2025-09-21T13:57:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add resume api to resume/continue the tasks in process tracker for revenue_recovery. This PR enables us to resume the EXECUTE and CALCULATE that are stuck in an intermediate state . ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create a MA and MCA and Billing MCA - Create an intent and initiate a process tracker entry - We can change the process tracker schedule time for revenue_recovery workflows , to resume some jobs ```curl curl --location 'http://localhost:8080/v2/process-trackers/revenue-recovery-workflow/12345_pay_01997ac9a9a87612b86629dad872b519/resume' \ --header 'Content-Type: application/json' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: dev_zxcOiG9TUvXT2jtzQAMLGllDYWw5KpXJyxTlGxy1SjjJ2Y5ScXLhKUfQK2PHUHSz' \ --data '{ "revenue_recovery_task": "EXECUTE_WORKFLOW", "schedule_time": "2025-08-28T12:44:44Z", "status": "pending", "business_status": "Pending" }' ```` <img width="3456" height="2234" alt="Screenshot 2025-09-24 at 1 47 02 PM" src="https://github.com/user-attachments/assets/1928497f-02c7-4079-9813-f56737c9fb74" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9dbfeda43de895d66729e6d88401e400f4f8ebed
juspay/hyperswitch
juspay__hyperswitch-9551
Bug: [BUG] Fix Ideal Giropay Country Currency Config ### Bug Description Ideal Giropay are European Payment Methods but is appearing for CNY currency. ### Expected Behavior Ideal Giropay Country Currency Config are appearing for CNY currency. ### Actual Behavior Ideal Giropay are European Payment Methods but is appearing for CNY currency. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index a8f9ea22c43..386339c7c2e 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -733,8 +733,8 @@ credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,B 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } @@ -934,8 +934,8 @@ credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,G debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } [pm_filters.datatrans] diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index fcdf05c9e43..fd742a12c20 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -552,8 +552,8 @@ credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,B 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } @@ -818,8 +818,8 @@ credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,G debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } [pm_filters.paysafe] diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 8f414935fef..dc63cf64955 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -469,8 +469,8 @@ credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,B 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } @@ -820,8 +820,8 @@ credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,G debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } [pm_filters.datatrans] diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 2589bde4a28..360d217e761 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -532,8 +532,8 @@ credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,B 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } @@ -830,8 +830,8 @@ credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,G debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } [pm_filters.datatrans] diff --git a/config/development.toml b/config/development.toml index 8027c8763ab..74e07c6b38c 100644 --- a/config/development.toml +++ b/config/development.toml @@ -653,8 +653,8 @@ credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,B 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } @@ -979,8 +979,8 @@ credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,G debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } [pm_filters.datatrans] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 5cc80eeb068..7e859b33c6e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -705,8 +705,8 @@ credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,B 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } @@ -962,8 +962,8 @@ credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,G debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } [pm_filters.datatrans] diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 62debb99693..cba41705b09 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -388,8 +388,8 @@ credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,B 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,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,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -ideal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } -giropay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" } @@ -665,8 +665,8 @@ credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,G debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } -ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { currency = "EUR" } +ideal = { currency = "EUR" } sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } [pm_filters.datatrans]
2025-09-24T15:27:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9551) ## Description <!-- Describe your changes in detail --> Fixed ideal giropay country currency config ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
bf048e4d830ee5088a7451e0da57a45e9a444394
juspay/hyperswitch
juspay__hyperswitch-9540
Bug: [BUG] payment link's checkout widget has visible scrollbars on Windows browsers ### Bug Description Windows browsers render a visible scrollbar on the checkout widget (which is set to `overflow: auto`). ### Expected Behavior There shouldn't be any visible scrollbars ### Actual Behavior There are visible scrollbars ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css index 37d132fff3a..79ee80573a0 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 @@ -635,6 +635,10 @@ body { text-align: center; } +#payment-form::-webkit-scrollbar { + display: none; +} + #submit { cursor: pointer; margin-top: 20px;
2025-09-24T09:48:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR hides the visible scrollbars on payment link's checkout widget. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context ## How did you test it? Can only be tested on windows device. Tested by using below payment link config on windows device ``` "payment_link_config": { "payment_link_ui_rules": { "#submit": { "color": "#003264 !important", "padding": "25px 0", "fontSize": "19px", "fontWeight": "700", "borderRadius": "5px", "backgroundColor": "#CBB7FF !important" }, "#payment-form-wrap": { "width": "100% !important", "backgroundColor": "#FFFFFF !important" }, "#payment-form::-webkit-scrollbar": { "display": "none" } } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9dbfeda43de895d66729e6d88401e400f4f8ebed
juspay/hyperswitch
juspay__hyperswitch-9535
Bug: [FIX][Tokenex] fix tokenize flow response handling data in tokenize flow for tokenex accepts only length of 13-19 chars, we are sending complete card data.
diff --git a/crates/hyperswitch_connectors/src/connectors/tokenex.rs b/crates/hyperswitch_connectors/src/connectors/tokenex.rs index 3dbe640beb3..1a4d2fc5021 100644 --- a/crates/hyperswitch_connectors/src/connectors/tokenex.rs +++ b/crates/hyperswitch_connectors/src/connectors/tokenex.rs @@ -151,11 +151,13 @@ impl ConnectorCommon for Tokenex { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let (code, message) = response.error.split_once(':').unwrap_or(("", "")); + Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: code.to_string(), + message: message.to_string(), + reason: Some(response.message), attempt_status: None, connector_transaction_id: None, network_advice_code: None, diff --git a/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs index 9d7082746b3..1904ac1840d 100644 --- a/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs @@ -1,10 +1,7 @@ -use common_utils::{ - ext_traits::{Encode, StringExt}, - types::StringMinorUnit, -}; +use common_utils::types::StringMinorUnit; use error_stack::ResultExt; use hyperswitch_domain_models::{ - router_data::{ConnectorAuthType, RouterData}, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ExternalVaultInsertFlow, ExternalVaultRetrieveFlow}, router_request_types::VaultRequestData, router_response_types::VaultResponseData, @@ -12,7 +9,7 @@ use hyperswitch_domain_models::{ vault::PaymentMethodVaultingData, }; use hyperswitch_interfaces::errors; -use masking::{ExposeInterface, Secret}; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::types::ResponseRouterData; @@ -24,7 +21,6 @@ pub struct TokenexRouterData<T> { impl<T> From<(StringMinorUnit, T)> for TokenexRouterData<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, @@ -34,21 +30,16 @@ impl<T> From<(StringMinorUnit, T)> for TokenexRouterData<T> { #[derive(Default, Debug, Serialize, PartialEq)] pub struct TokenexInsertRequest { - data: Secret<String>, + data: cards::CardNumber, //Currently only card number is tokenized. Data can be stringified and can be tokenized } impl<F> TryFrom<&VaultRouterData<F>> for TokenexInsertRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> { match item.request.payment_method_vaulting_data.clone() { - Some(PaymentMethodVaultingData::Card(req_card)) => { - let stringified_card = req_card - .encode_to_string_of_json() - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Self { - data: Secret::new(stringified_card), - }) - } + Some(PaymentMethodVaultingData::Card(req_card)) => Ok(Self { + data: req_card.card_number.clone(), + }), _ => Err(errors::ConnectorError::NotImplemented( "Payment method apart from card".to_string(), ) @@ -56,9 +47,6 @@ impl<F> TryFrom<&VaultRouterData<F>> for TokenexInsertRequest { } } } - -//TODO: Fill the struct with respective fields -// Auth Struct pub struct TokenexAuthType { pub(super) api_key: Secret<String>, pub(super) tokenex_id: Secret<String>, @@ -78,10 +66,14 @@ impl TryFrom<&ConnectorAuthType> for TokenexAuthType { } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct TokenexInsertResponse { - token: String, - first_six: String, + token: Option<String>, + first_six: Option<String>, + last_four: Option<String>, success: bool, + error: String, + message: Option<String>, } impl TryFrom< @@ -103,20 +95,49 @@ impl >, ) -> Result<Self, Self::Error> { let resp = item.response; + match resp.success && resp.error.is_empty() { + true => { + let token = resp + .token + .clone() + .ok_or(errors::ConnectorError::ResponseDeserializationFailed) + .attach_printable("Token is missing in tokenex response")?; + Ok(Self { + status: common_enums::AttemptStatus::Started, + response: Ok(VaultResponseData::ExternalVaultInsertResponse { + connector_vault_id: token.clone(), + //fingerprint is not provided by tokenex, using token as fingerprint + fingerprint_id: token.clone(), + }), + ..item.data + }) + } + false => { + let (code, message) = resp.error.split_once(':').unwrap_or(("", "")); + + let response = Err(ErrorResponse { + code: code.to_string(), + message: message.to_string(), + reason: resp.message, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }); - Ok(Self { - status: common_enums::AttemptStatus::Started, - response: Ok(VaultResponseData::ExternalVaultInsertResponse { - connector_vault_id: resp.token.clone(), - //fingerprint is not provided by tokenex, using token as fingerprint - fingerprint_id: resp.token.clone(), - }), - ..item.data - }) + Ok(Self { + response, + ..item.data + }) + } + } } } - #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct TokenexRetrieveRequest { token: Secret<String>, //Currently only card number is tokenized. Data can be stringified and can be tokenized cache_cvv: bool, @@ -124,8 +145,10 @@ pub struct TokenexRetrieveRequest { #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TokenexRetrieveResponse { - value: Secret<String>, + value: Option<cards::CardNumber>, success: bool, + error: String, + message: Option<String>, } impl<F> TryFrom<&VaultRouterData<F>> for TokenexRetrieveRequest { @@ -164,30 +187,48 @@ impl ) -> Result<Self, Self::Error> { let resp = item.response; - let card_detail: api_models::payment_methods::CardDetail = resp - .value - .clone() - .expose() - .parse_struct("CardDetail") - .change_context(errors::ConnectorError::ParsingFailed)?; + match resp.success && resp.error.is_empty() { + true => { + let data = resp + .value + .clone() + .ok_or(errors::ConnectorError::ResponseDeserializationFailed) + .attach_printable("Card number is missing in tokenex response")?; + Ok(Self { + status: common_enums::AttemptStatus::Started, + response: Ok(VaultResponseData::ExternalVaultRetrieveResponse { + vault_data: PaymentMethodVaultingData::CardNumber(data), + }), + ..item.data + }) + } + false => { + let (code, message) = resp.error.split_once(':').unwrap_or(("", "")); + + let response = Err(ErrorResponse { + code: code.to_string(), + message: message.to_string(), + reason: resp.message, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }); - Ok(Self { - status: common_enums::AttemptStatus::Started, - response: Ok(VaultResponseData::ExternalVaultRetrieveResponse { - vault_data: PaymentMethodVaultingData::Card(card_detail), - }), - ..item.data - }) + Ok(Self { + response, + ..item.data + }) + } + } } } -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct TokenexErrorResponse { - pub status_code: u16, - pub code: String, + pub error: String, pub message: String, - pub reason: Option<String>, - pub network_advice_code: Option<String>, - pub network_decline_code: Option<String>, - pub network_error_message: Option<String>, } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 932244a986d..6bc9062eea2 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -7,10 +7,8 @@ use api_models::{ payments::{additional_info as payment_additional_types, ExtendedCardInfo}, }; use common_enums::enums as api_enums; -#[cfg(feature = "v2")] -use common_utils::ext_traits::OptionExt; use common_utils::{ - ext_traits::StringExt, + ext_traits::{OptionExt, StringExt}, id_type, new_type::{ MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, @@ -18,7 +16,7 @@ use common_utils::{ payout_method_utils, pii::{self, Email}, }; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::Date; @@ -2327,6 +2325,13 @@ impl PaymentMethodsData { Self::BankDetails(_) | Self::WalletDetails(_) | Self::NetworkToken(_) => None, } } + pub fn get_card_details(&self) -> Option<CardDetailsPaymentMethod> { + if let Self::Card(card) = self { + Some(card.clone()) + } else { + None + } + } } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -2593,8 +2598,6 @@ impl // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked let name_on_card = if let Some(name) = card_holder_name.clone() { - use masking::ExposeInterface; - if name.clone().expose().is_empty() { card_token_data .and_then(|token_data| token_data.card_holder_name.clone()) @@ -2626,3 +2629,63 @@ impl } } } + +#[cfg(feature = "v1")] +impl + TryFrom<( + cards::CardNumber, + Option<&CardToken>, + Option<payment_methods::CoBadgedCardData>, + CardDetailsPaymentMethod, + )> for Card +{ + type Error = error_stack::Report<common_utils::errors::ValidationError>; + fn try_from( + value: ( + cards::CardNumber, + Option<&CardToken>, + Option<payment_methods::CoBadgedCardData>, + CardDetailsPaymentMethod, + ), + ) -> Result<Self, Self::Error> { + let (card_number, card_token_data, co_badged_card_data, card_details) = value; + + // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked + let name_on_card = if let Some(name) = card_details.card_holder_name.clone() { + if name.clone().expose().is_empty() { + card_token_data + .and_then(|token_data| token_data.card_holder_name.clone()) + .or(Some(name)) + } else { + Some(name) + } + } else { + card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) + }; + + Ok(Self { + card_number, + card_exp_month: card_details + .expiry_month + .get_required_value("expiry_month")? + .clone(), + card_exp_year: card_details + .expiry_year + .get_required_value("expiry_year")? + .clone(), + card_holder_name: name_on_card, + card_cvc: card_token_data + .cloned() + .unwrap_or_default() + .card_cvc + .unwrap_or_default(), + card_issuer: card_details.card_issuer, + card_network: card_details.card_network, + card_type: card_details.card_type, + card_issuing_country: card_details.issuer_country, + bank_code: None, + nick_name: card_details.nick_name, + co_badged_card_data, + }) + } +} diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rs index 9ba63f50233..94f23b4fbb3 100644 --- a/crates/hyperswitch_domain_models/src/vault.rs +++ b/crates/hyperswitch_domain_models/src/vault.rs @@ -12,6 +12,7 @@ pub enum PaymentMethodVaultingData { Card(payment_methods::CardDetail), #[cfg(feature = "v2")] NetworkToken(payment_method_data::NetworkTokenDetails), + CardNumber(cards::CardNumber), } impl PaymentMethodVaultingData { @@ -20,6 +21,7 @@ impl PaymentMethodVaultingData { Self::Card(card) => Some(card), #[cfg(feature = "v2")] Self::NetworkToken(_) => None, + Self::CardNumber(_) => None, } } pub fn get_payment_methods_data(&self) -> payment_method_data::PaymentMethodsData { @@ -35,6 +37,23 @@ impl PaymentMethodVaultingData { ), ) } + Self::CardNumber(_card_number) => payment_method_data::PaymentMethodsData::Card( + payment_method_data::CardDetailsPaymentMethod { + last4_digits: None, + issuer_country: None, + expiry_month: None, + expiry_year: None, + nick_name: None, + card_holder_name: None, + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: false, + #[cfg(feature = "v1")] + co_badged_card_data: None, + }, + ), } } } @@ -49,6 +68,7 @@ impl VaultingDataInterface for PaymentMethodVaultingData { Self::Card(card) => card.card_number.to_string(), #[cfg(feature = "v2")] Self::NetworkToken(network_token) => network_token.network_token.to_string(), + Self::CardNumber(card_number) => card_number.to_string(), } } } diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index b07b89e1328..ed78b942e9c 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -2201,18 +2201,7 @@ pub async fn create_pm_additional_data_update( external_vault_source: Option<id_type::MerchantConnectorAccountId>, ) -> RouterResult<storage::PaymentMethodUpdate> { let encrypted_payment_method_data = pmd - .map( - |payment_method_vaulting_data| match payment_method_vaulting_data { - domain::PaymentMethodVaultingData::Card(card) => domain::PaymentMethodsData::Card( - domain::CardDetailsPaymentMethod::from(card.clone()), - ), - domain::PaymentMethodVaultingData::NetworkToken(network_token) => { - domain::PaymentMethodsData::NetworkToken( - domain::NetworkTokenDetailsPaymentMethod::from(network_token.clone()), - ) - } - }, - ) + .map(|payment_method_vaulting_data| payment_method_vaulting_data.get_payment_methods_data()) .async_map(|payment_method_details| async { let key_manager_state = &(state).into(); diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 771df3d97c7..98888520d59 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1964,9 +1964,12 @@ pub fn get_vault_response_for_retrieve_payment_method_data_v1<F>( } }, Err(err) => { - logger::error!("Failed to retrieve payment method: {:?}", err); + logger::error!( + "Failed to retrieve payment method from external vault: {:?}", + err + ); Err(report!(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to retrieve payment method")) + .attach_printable("Failed to retrieve payment method from external vault")) } } } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 044466523d4..10d72baf282 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2512,10 +2512,30 @@ pub async fn fetch_card_details_from_external_vault( ) .await?; + let payment_methods_data = payment_method_info.get_payment_methods_data(); + match vault_resp { hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card) => Ok( domain::Card::from((card, card_token_data, co_badged_card_data)), ), + hyperswitch_domain_models::vault::PaymentMethodVaultingData::CardNumber(card_number) => { + let payment_methods_data = payment_methods_data + .get_required_value("PaymentMethodsData") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Payment methods data not present")?; + + let card = payment_methods_data + .get_card_details() + .get_required_value("CardDetails") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Card details not present")?; + + Ok( + domain::Card::try_from((card_number, card_token_data, co_badged_card_data, card)) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to generate card data")?, + ) + } } } #[cfg(feature = "v1")]
2025-09-23T16:55:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> data in tokenize flow for tokenex accepts only length of 13-19 chars, we are sending complete card data. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Please refer to this pr - https://github.com/juspay/hyperswitch/pull/9274 on how to enable external vault for profile - create tokenex mca ``` curl --location 'http://localhost:8080/account/merchant_1758632854/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data '{ "connector_type": "vault_processor", "connector_name": "tokenex", "connector_account_details": { "auth_type": "BodyKey", "api_key": "api_key", "key1": "key1" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ ], "metadata": { "endpoint_prefix": "ghjg", "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" } } ], "merchant_info": { "merchant_name": "Narayan Bhat" } } }, "connector_webhook_details": { "merchant_secret": "7091687210DF6DCA38B2E670B3D68EB53516A26CA85590E29024FFBD7CD23980" }, "profile_id":"pro_KH7MujUjH2miLhfzGlAB" }' ``` - enable external vault for profile - make a payment with customer acceptance and setup_future_usage - on_session/off_session <img width="1055" height="941" alt="Screenshot 2025-09-24 at 10 48 05 AM" src="https://github.com/user-attachments/assets/46c43aed-022d-4cad-8204-912357f1a298" /> <img width="1059" height="947" alt="Screenshot 2025-09-24 at 12 48 36 PM" src="https://github.com/user-attachments/assets/31cf863a-a126-4ac2-bd76-1d08950dae10" /> request - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jN7RVfxJgyz3GB7OASKFved09yY2lA17xEJSBbj47tBN03inP9rCADUooCF5Ozz6' \ --data-raw ' { "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id":"cu_1758488194", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ], "profile_id": "pro_KH7MujUjH2miLhfzGlAB" }' ``` response- ``` { "payment_id": "pay_yx1fFGndifp7EQB3opNZ", "merchant_id": "merchant_1758632854", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "adyen", "client_secret": "pay_yx1fFGndifp7EQB3opNZ_secret_0RiRDFg3M0R56irWcNPa", "created": "2025-09-24T05:13:52.934Z", "currency": "USD", "customer_id": "cu_1758488194", "customer": { "id": "cu_1758488194", "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": "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": 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": "John", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "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": "PiX", "last_name": "ss", "origin_zip": null }, "phone": null, "email": null }, "order_details": [ { "sku": null, "upc": null, "brand": null, "amount": 0, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "description": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": null, "unit_of_measure": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null, "unit_discount_amount": null } ], "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1758488194", "created_at": 1758690832, "expires": 1758694432, "secret": "epk_5ee608c074874637922ff9a945f075d9" }, "manual_retry_allowed": null, "connector_transaction_id": "TLVXXSHZFB55CG75", "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_yx1fFGndifp7EQB3opNZ_1", "payment_link": null, "profile_id": "pro_KH7MujUjH2miLhfzGlAB", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_K1J4djESc692nk5upGnL", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-24T05:28:52.934Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": "043891143898481", "payment_method_status": null, "updated": "2025-09-24T05:13:55.173Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` - payment method entry will be created. <img width="1728" height="624" alt="Screenshot 2025-09-24 at 10 47 48 AM" src="https://github.com/user-attachments/assets/56a4f33e-ac42-4763-8ba5-cafa37581fc9" /> - raw connector request & response of tokenex <img width="1714" height="475" alt="Screenshot 2025-09-24 at 10 46 20 AM" src="https://github.com/user-attachments/assets/51704ea6-0846-4fee-8b69-77f0d4310eb4" /> ![Screenshot 2025-09-25 at 1 10 38 PM](https://github.com/user-attachments/assets/09b7a3e7-733c-4482-bb2a-2e43e33455e3) <img width="1004" height="960" alt="Screenshot 2025-09-25 at 1 12 28 PM" src="https://github.com/user-attachments/assets/2b074348-d4f0-4317-bcfe-fcb708670727" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ceacec909bdeb4287571eb00622e60f7c21f30e4
juspay/hyperswitch
juspay__hyperswitch-9544
Bug: [FEATURE]: [GIGADAT] integrate interac bank redirect payment method
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index c381bc0596a..c198eda909d 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -762,6 +762,10 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } 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" } + +[pm_filters.gigadat] +interac = { currency = "CAD"} + [payout_method_filters.adyenplatform] sepa = { country = "AT,BE,CH,CZ,DE,EE,ES,FI,FR,GB,HU,IE,IT,LT,LV,NL,NO,PL,PT,SE,SK", currency = "EUR,CZK,DKK,HUF,NOK,PLN,SEK,GBP,CHF" } credit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT,LU,LV,MT,NL,NO,PL,PT,RO,SE,SI,SK,US", currency = "EUR,USD,GBP" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 34bfffa8f3f..502b98ebca3 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -786,6 +786,10 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } 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" } + +[pm_filters.gigadat] +interac = { currency = "CAD"} + [pm_filters.coingate] crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index a13157b860e..e22b12b2385 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -798,6 +798,9 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } 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" } +[pm_filters.gigadat] +interac = { currency = "CAD"} + [pm_filters.coingate] crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } diff --git a/config/development.toml b/config/development.toml index b05755409e0..52a61c759bb 100644 --- a/config/development.toml +++ b/config/development.toml @@ -778,6 +778,8 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } 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" } +[pm_filters.gigadat] +interac = { currency = "CAD"} [pm_filters.mollie] credit = { not_available_flows = { capture_method = "manual" } } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 896f3eeba6b..3fbc01d5450 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -929,6 +929,9 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } 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" } +[pm_filters.gigadat] +interac = { currency = "CAD"} + [pm_filters.coingate] crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index e2832a6b954..a4369cd7862 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -102,6 +102,7 @@ pub enum RoutableConnectors { Flexiti, Forte, Getnet, + Gigadat, Globalpay, Globepay, Gocardless, @@ -277,6 +278,7 @@ pub enum Connector { Flexiti, Forte, Getnet, + Gigadat, Globalpay, Globepay, Gocardless, @@ -475,6 +477,7 @@ impl Connector { | Self::Flexiti | Self::Forte | Self::Getnet + | Self::Gigadat | Self::Globalpay | Self::Globepay | Self::Gocardless @@ -660,6 +663,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Flexiti => Self::Flexiti, RoutableConnectors::Forte => Self::Forte, RoutableConnectors::Getnet => Self::Getnet, + RoutableConnectors::Gigadat => Self::Gigadat, RoutableConnectors::Globalpay => Self::Globalpay, RoutableConnectors::Globepay => Self::Globepay, RoutableConnectors::Gocardless => Self::Gocardless, @@ -857,6 +861,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Zsl => Ok(Self::Zsl), Connector::Recurly => Ok(Self::Recurly), Connector::Getnet => Ok(Self::Getnet), + Connector::Gigadat => Ok(Self::Gigadat), Connector::Hipay => Ok(Self::Hipay), Connector::Inespay => Ok(Self::Inespay), Connector::Redsys => Ok(Self::Redsys), diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index be97726a194..97703c54532 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -111,6 +111,7 @@ pub struct ApiModelMetaData { pub tenant_id: Option<String>, pub platform_url: Option<String>, pub account_id: Option<serde_json::Value>, + pub site: Option<String>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 3c868782155..2940b16e7fd 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -177,6 +177,7 @@ pub struct ConfigMetadata { pub route: Option<InputData>, pub mid: Option<InputData>, pub tid: Option<InputData>, + pub site: Option<InputData>, } #[serde_with::skip_serializing_none] @@ -486,6 +487,7 @@ impl ConnectorConfig { Connector::Flexiti => Ok(connector_data.flexiti), Connector::Forte => Ok(connector_data.forte), Connector::Getnet => Ok(connector_data.getnet), + Connector::Gigadat => Ok(connector_data.gigadat), Connector::Globalpay => Ok(connector_data.globalpay), Connector::Globepay => Ok(connector_data.globepay), Connector::Gocardless => Ok(connector_data.gocardless), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 713f8750753..857d756d710 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7096,5 +7096,15 @@ api_key = "API Key" key1 = "TokenEx ID" [gigadat] -[gigadat.connector_auth.HeaderKey] -api_key = "API Key" +[gigadat.connector_auth.SignatureKey] +api_key = "Username" +api_secret = "Password" +key1 = "Compaign Id" +[[gigadat.bank_redirect]] +payment_method_type = "interac" +[gigadat.metadata.site] +name = "site" +label = "Site where transaction is initiated" +placeholder = "Enter site where transaction is initiated" +required = true +type = "Text" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 6068ad7f0c5..2af909e8ca7 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5833,5 +5833,15 @@ type="Text" api_key = "API Key" [gigadat] -[gigadat.connector_auth.HeaderKey] -api_key = "API Key" +[gigadat.connector_auth.SignatureKey] +api_key = "Username" +api_secret = "Password" +key1 = "Compaign Id" +[[gigadat.bank_redirect]] +payment_method_type = "interac" +[gigadat.metadata.site] +name = "site" +label = "Site where transaction is initiated" +placeholder = "Enter site where transaction is initiated" +required = true +type = "Text" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 99ed75fa9c0..33e227037fd 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7076,5 +7076,15 @@ type="Text" api_key = "API Key" [gigadat] -[gigadat.connector_auth.HeaderKey] -api_key = "API Key" +[gigadat.connector_auth.SignatureKey] +api_key = "Username" +api_secret = "Password" +key1 = "Compaign Id" +[[gigadat.bank_redirect]] +payment_method_type = "interac" +[gigadat.metadata.site] +name = "site" +label = "Site where transaction is initiated" +placeholder = "Enter site where transaction is initiated" +required = true +type = "Text" diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat.rs b/crates/hyperswitch_connectors/src/connectors/gigadat.rs index bebad38b04c..6b566ef3bee 100644 --- a/crates/hyperswitch_connectors/src/connectors/gigadat.rs +++ b/crates/hyperswitch_connectors/src/connectors/gigadat.rs @@ -1,13 +1,13 @@ pub mod transformers; -use std::sync::LazyLock; - +use base64::Engine; use common_enums::enums; use common_utils::{ + consts, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -24,11 +24,12 @@ use hyperswitch_domain_models::{ RefundsData, SetupMandateRequestData, }, router_response_types::{ - ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -37,25 +38,27 @@ use hyperswitch_interfaces::{ ConnectorValidation, }, configs::Connectors, - errors, + consts as api_consts, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; +use lazy_static::lazy_static; +use masking::{Mask, PeekInterface}; use transformers as gigadat; +use uuid::Uuid; use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Gigadat { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), } impl Gigadat { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &FloatMajorUnitForConnector, } } } @@ -121,9 +124,11 @@ impl ConnectorCommon for Gigadat { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = gigadat::GigadatAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let auth_key = format!("{}:{}", auth.username.peek(), auth.password.peek()); + let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), + auth_header.into_masked(), )]) } @@ -142,9 +147,9 @@ impl ConnectorCommon for Gigadat { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response.err.clone(), + message: response.err.clone(), + reason: Some(response.err).clone(), attempt_status: None, connector_transaction_id: None, network_advice_code: None, @@ -204,10 +209,16 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, - _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(format!( + "{}api/payment-token/{}", + self.base_url(connectors), + auth.campaign_id.peek() + )) } fn get_request_body( @@ -222,7 +233,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData )?; let connector_router_data = gigadat::GigadatRouterData::from((amount, req)); - let connector_req = gigadat::GigadatPaymentsRequest::try_from(&connector_router_data)?; + let connector_req = gigadat::GigadatCpiRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -254,12 +265,14 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: gigadat::GigadatPaymentsResponse = res + let response: gigadat::GigadatPaymentResponse = res .response - .parse_struct("Gigadat PaymentsAuthorizeResponse") + .parse_struct("GigadatPaymentResponse") .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(), @@ -291,10 +304,18 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Gig 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 transaction_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}api/transactions/{transaction_id}", + self.base_url(connectors) + )) } fn build_request( @@ -318,7 +339,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Gig event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: gigadat::GigadatPaymentsResponse = res + let response: gigadat::GigadatTransactionStatusResponse = res .response .parse_struct("gigadat PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -395,7 +416,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: gigadat::GigadatPaymentsResponse = res + let response: gigadat::GigadatTransactionStatusResponse = res .response .parse_struct("Gigadat PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -423,9 +444,22 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gigadat fn get_headers( &self, req: &RefundsRouterData<Execute>, - connectors: &Connectors, + _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) + let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let auth_key = format!("{}:{}", auth.username.peek(), auth.password.peek()); + let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); + Ok(vec![ + ( + headers::AUTHORIZATION.to_string(), + auth_header.into_masked(), + ), + ( + headers::IDEMPOTENCY_KEY.to_string(), + Uuid::new_v4().to_string().into_masked(), + ), + ]) } fn get_content_type(&self) -> &'static str { @@ -435,9 +469,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gigadat fn get_url( &self, _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}refunds", self.base_url(connectors),)) } fn get_request_body( @@ -499,75 +533,41 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gigadat res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gigadat { - 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: gigadat::RefundResponse = res + let response: gigadat::GigadatRefundErrorResponse = res .response - .parse_struct("gigadat RefundSyncResponse") + .parse_struct("GigadatRefundErrorResponse") .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, + + let code = response + .error + .first() + .and_then(|error_detail| error_detail.code.clone()) + .unwrap_or(api_consts::NO_ERROR_CODE.to_string()); + let message = response + .error + .first() + .map(|error_detail| error_detail.detail.clone()) + .unwrap_or(api_consts::NO_ERROR_MESSAGE.to_string()); + Ok(ErrorResponse { + status_code: res.status_code, + code, + message, + reason: Some(response.message).clone(), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, }) } +} - 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 Gigadat { + //Gigadat does not support Refund Sync } #[async_trait::async_trait] @@ -594,21 +594,36 @@ impl webhooks::IncomingWebhook for Gigadat { } } -static GIGADAT_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = - LazyLock::new(SupportedPaymentMethods::new); - -static GIGADAT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Gigadat", - description: "Gigadat connector", - connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, - integration_status: enums::ConnectorIntegrationStatus::Sandbox, -}; - -static GIGADAT_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; +lazy_static! { + static ref GIGADAT_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; + + let mut gigadat_supported_payment_methods = SupportedPaymentMethods::new(); + gigadat_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Interac, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + gigadat_supported_payment_methods + }; + static ref GIGADAT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Gigadat", + description: "Gigadat is a financial services product that offers a single API for payment integration. It provides Canadian businesses with a secure payment gateway and various pay-in and pay-out solutions, including Interac e-Transfer", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, + }; + static ref GIGADAT_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); +} impl ConnectorSpecifications for Gigadat { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&GIGADAT_CONNECTOR_INFO) + Some(&*GIGADAT_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -616,6 +631,6 @@ impl ConnectorSpecifications for Gigadat { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&GIGADAT_SUPPORTED_WEBHOOK_FLOWS) + Some(&*GIGADAT_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs index db58300ed34..d87bb6374eb 100644 --- a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs @@ -1,28 +1,35 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_enums::{enums, Currency}; +use common_utils::{ + id_type, + pii::{self, Email, IpAddress}, + request::Method, + types::FloatMajorUnit, +}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, + payment_method_data::{BankRedirectData, PaymentMethodData}, router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, + router_flow_types::refunds::Execute, router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; -use crate::types::{RefundsResponseRouterData, ResponseRouterData}; +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{self, BrowserInformationData, PaymentsAuthorizeRequestData, RouterData as _}, +}; -//TODO: Fill the struct with respective fields pub struct GigadatRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } -impl<T> From<(StringMinorUnit, T)> for GigadatRouterData<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<(FloatMajorUnit, T)> for GigadatRouterData<T> { + fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, @@ -30,93 +37,214 @@ impl<T> From<(StringMinorUnit, T)> for GigadatRouterData<T> { } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] -pub struct GigadatPaymentsRequest { - amount: StringMinorUnit, - card: GigadatCard, +const CONNECTOR_BASE_URL: &str = "https://interac.express-connect.com/"; + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct GigadatConnectorMetadataObject { + pub site: String, +} + +impl TryFrom<&Option<pii::SecretSerdeValue>> for GigadatConnectorMetadataObject { + 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: "merchant_connector_account.metadata", + })?; + Ok(metadata) + } +} + +// CPI (Combined Pay-in) Request Structure for Gigadat +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct GigadatCpiRequest { + pub user_id: id_type::CustomerId, + pub site: String, + pub user_ip: Secret<String, IpAddress>, + pub currency: Currency, + pub amount: FloatMajorUnit, + pub transaction_id: String, + #[serde(rename = "type")] + pub transaction_type: GidadatTransactionType, + pub name: Secret<String>, + pub email: Email, + pub mobile: Secret<String>, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct GigadatCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum GidadatTransactionType { + Cpi, } -impl TryFrom<&GigadatRouterData<&PaymentsAuthorizeRouterData>> for GigadatPaymentsRequest { +impl TryFrom<&GigadatRouterData<&PaymentsAuthorizeRouterData>> for GigadatCpiRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &GigadatRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { + let metadata: GigadatConnectorMetadataObject = + utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "merchant_connector_account.metadata", + })?; match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( - "Card payment method not implemented".to_string(), + PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => { + let router_data = item.router_data; + let name = router_data.get_billing_full_name()?; + let email = router_data.get_billing_email()?; + let mobile = router_data.get_billing_phone_number()?; + let currency = item.router_data.request.currency; + + let user_ip = router_data.request.get_browser_info()?.get_ip_address()?; + + Ok(Self { + user_id: router_data.get_customer_id()?, + site: metadata.site, + user_ip, + currency, + amount: item.amount, + transaction_id: router_data.connector_request_reference_id.clone(), + transaction_type: GidadatTransactionType::Cpi, + name, + email, + mobile, + }) + } + PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Gigadat"), + ))?, + + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Gigadat"), ) .into()), - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } -//TODO: Fill the struct with respective fields -// Auth Struct +#[derive(Debug, Clone)] pub struct GigadatAuthType { - pub(super) api_key: Secret<String>, + pub campaign_id: Secret<String>, + pub username: Secret<String>, + pub password: Secret<String>, } impl TryFrom<&ConnectorAuthType> for GigadatAuthType { 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(), + ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self { + password: api_secret.to_owned(), + username: api_key.to_owned(), + campaign_id: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct GigadatPaymentResponse { + pub token: Secret<String>, + pub data: GigadatPaymentData, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct GigadatPaymentData { + pub transaction_id: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GigadatPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, + StatusInited, + StatusSuccess, + StatusRejected, + StatusRejected1, + StatusExpired, + StatusAborted1, + StatusPending, + StatusFailed, } -impl From<GigadatPaymentStatus> for common_enums::AttemptStatus { +impl From<GigadatPaymentStatus> for enums::AttemptStatus { fn from(item: GigadatPaymentStatus) -> Self { match item { - GigadatPaymentStatus::Succeeded => Self::Charged, - GigadatPaymentStatus::Failed => Self::Failure, - GigadatPaymentStatus::Processing => Self::Authorizing, + GigadatPaymentStatus::StatusSuccess => Self::Charged, + GigadatPaymentStatus::StatusInited | GigadatPaymentStatus::StatusPending => { + Self::Pending + } + GigadatPaymentStatus::StatusRejected + | GigadatPaymentStatus::StatusExpired + | GigadatPaymentStatus::StatusRejected1 + | GigadatPaymentStatus::StatusAborted1 + | GigadatPaymentStatus::StatusFailed => Self::Failure, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct GigadatPaymentsResponse { - status: GigadatPaymentStatus, - id: String, +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct GigadatTransactionStatusResponse { + pub status: GigadatPaymentStatus, } -impl<F, T> TryFrom<ResponseRouterData<F, GigadatPaymentsResponse, T, PaymentsResponseData>> +impl<F, T> TryFrom<ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, GigadatPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { + // Will be raising a sepearte PR to populate a field connect_base_url in routerData and use it here + let base_url = CONNECTOR_BASE_URL; + + let redirect_url = format!( + "{}/webflow?transaction={}&token={}", + base_url, + item.data.connector_request_reference_id, + item.response.token.peek() + ); + + let redirection_data = Some(RedirectForm::Form { + endpoint: redirect_url, + method: Method::Get, + form_fields: Default::default(), + }); Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), + status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), + resource_id: ResponseId::ConnectorTransactionId(item.response.data.transaction_id), + redirection_data: Box::new(redirection_data), + 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 + }) + } +} + +impl<F, T> TryFrom<ResponseRouterData<F, GigadatTransactionStatusResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, GigadatTransactionStatusResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, @@ -130,50 +258,31 @@ impl<F, T> TryFrom<ResponseRouterData<F, GigadatPaymentsResponse, T, PaymentsRes } } -//TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct GigadatRefundRequest { - pub amount: StringMinorUnit, + pub amount: FloatMajorUnit, + pub transaction_id: String, + pub campaign_id: Secret<String>, } impl<F> TryFrom<&GigadatRouterData<&RefundsRouterData<F>>> for GigadatRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &GigadatRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + let auth_type = GigadatAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { amount: item.amount.to_owned(), + transaction_id: item.router_data.request.connector_transaction_id.clone(), + campaign_id: auth_type.campaign_id, }) } } -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Copy, 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)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { - id: String, - status: RefundStatus, + success: bool, + data: GigadatPaymentData, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { @@ -181,39 +290,35 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRout 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 - }) - } -} + let refund_status = match item.http_code { + 200 => enums::RefundStatus::Success, + 400 | 401 | 422 => enums::RefundStatus::Failure, + _ => enums::RefundStatus::Pending, + }; -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), + connector_refund_id: item.response.data.transaction_id.to_string(), + refund_status, }), ..item.data }) } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct GigadatErrorResponse { - pub status_code: u16, - pub code: String, + pub err: String, +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct GigadatRefundErrorResponse { + pub error: Vec<Error>, pub message: String, - pub reason: Option<String>, - pub network_advice_code: Option<String>, - pub network_decline_code: Option<String>, - pub network_error_message: Option<String>, +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct Error { + pub code: Option<String>, + pub detail: String, } 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 bfb3e36b291..5a5d20c9e2b 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -2310,10 +2310,25 @@ fn get_bank_redirect_required_fields( ), ( enums::PaymentMethodType::Interac, - connectors(vec![( - Connector::Paysafe, - fields(vec![], vec![RequiredField::BillingEmail], vec![]), - )]), + connectors(vec![ + ( + Connector::Paysafe, + fields(vec![], vec![RequiredField::BillingEmail], vec![]), + ), + ( + Connector::Gigadat, + fields( + vec![], + vec![ + RequiredField::BillingEmail, + RequiredField::BillingUserFirstName, + RequiredField::BillingUserLastName, + RequiredField::BillingPhone, + ], + vec![], + ), + ), + ]), ), ]) } diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index a4bc945b935..8c9ef01017c 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -263,6 +263,13 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { getnet::transformers::GetnetAuthType::try_from(self.auth_type)?; Ok(()) } + api_enums::Connector::Gigadat => { + gigadat::transformers::GigadatAuthType::try_from(self.auth_type)?; + gigadat::transformers::GigadatConnectorMetadataObject::try_from( + self.connector_meta_data, + )?; + Ok(()) + } api_enums::Connector::Globalpay => { globalpay::transformers::GlobalpayAuthType::try_from(self.auth_type)?; globalpay::transformers::GlobalPayMeta::try_from(self.connector_meta_data)?; diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index d0b2d5560ca..61dcf050479 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -270,6 +270,9 @@ impl ConnectorData { enums::Connector::Getnet => { Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new()))) } + enums::Connector::Gigadat => { + Ok(ConnectorEnum::Old(Box::new(connector::Gigadat::new()))) + } enums::Connector::Globalpay => { Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new()))) } diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index 9f514337a68..4537b42452f 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -188,6 +188,9 @@ impl FeatureMatrixConnectorData { enums::Connector::Getnet => { Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new()))) } + enums::Connector::Gigadat => { + Ok(ConnectorEnum::Old(Box::new(connector::Gigadat::new()))) + } enums::Connector::Globalpay => { Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new()))) } diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index ae8dfa26727..7cc41f7bc79 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -67,6 +67,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Flexiti => Self::Flexiti, api_enums::Connector::Forte => Self::Forte, api_enums::Connector::Getnet => Self::Getnet, + api_enums::Connector::Gigadat => Self::Gigadat, api_enums::Connector::Globalpay => Self::Globalpay, api_enums::Connector::Globepay => Self::Globepay, api_enums::Connector::Gocardless => Self::Gocardless, diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index e44d56a57d6..1208173abd1 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -59,7 +59,7 @@ pub struct ConnectorAuthentication { pub flexiti: Option<HeaderKey>, pub forte: Option<MultiAuthKey>, pub getnet: Option<HeaderKey>, - pub gigadat: Option<HeaderKey>, + pub gigadat: Option<SignatureKey>, pub globalpay: Option<BodyKey>, pub globepay: Option<BodyKey>, pub gocardless: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index e072a370b91..308369352f5 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -592,6 +592,10 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } 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" } + +[pm_filters.gigadat] +interac = { currency = "CAD"} + [pm_filters.authorizedotnet] credit = { currency = "CAD,USD" } debit = { currency = "CAD,USD" }
2025-09-23T15:19:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implement payments, psync and refunds flow for Gigadat ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Tested using mock server Create mca for Gigadat ``` curl --location 'http://localhost:8080/account/merchant_1758701666/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_uhygCOBanQSOQkTpXmNryzdiJbf9SKUvNWAQG0cVbtuFjfzwxte8xWr9N3EtTmks' \ --data '{ "connector_type": "payment_processor", "business_country": "US", "business_label": "food", "connector_name": "gigadat", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "_", "key1": "_", "api_secret" : "_" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "interac", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "site" : "https://google.com/" } } ' ``` 2. Create interac payment method ``` { "amount": 1500, "currency": "CAD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "profile_id": "pro_PWARez1e6xNJ9JgXgmgu", "authentication_type": "three_ds", "payment_method": "bank_redirect", "payment_method_type": "interac", "payment_method_data": { "bank_redirect": { "interac": {} } }, "billing": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "CA", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` Response ``` { "payment_id": "pay_8VkI5Udmj7k2PyZHwvEZ", "merchant_id": "merchant_1758701666", "status": "requires_customer_action", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 1500, "amount_received": null, "connector": "gigadat", "client_secret": "pay_8VkI5Udmj7k2PyZHwvEZ_secret_lfEVqcrXUtTsyuPiNllV", "created": "2025-09-24T09:34:43.061Z", "currency": "CAD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "CA", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_8VkI5Udmj7k2PyZHwvEZ/merchant_1758701666/pay_8VkI5Udmj7k2PyZHwvEZ_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "interac", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "aaaa", "created_at": 1758706483, "expires": 1758710083, "secret": "epk_f6fec077f5324182b567bac694e7a356" }, "manual_retry_allowed": null, "connector_transaction_id": "pay_8VkI5Udmj7k2PyZHwvEZ_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_PWARez1e6xNJ9JgXgmgu", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_kDGqP2nExsX1Mx3qtjtt", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-24T09:49:43.061Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-24T09:34:43.091Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9dbfeda43de895d66729e6d88401e400f4f8ebed
juspay/hyperswitch
juspay__hyperswitch-9556
Bug: [FEATURE] Add connector template code for Tesouro Template PR for Tesouro integration
diff --git a/config/config.example.toml b/config/config.example.toml index b69f959fbe3..fb2a9107f0a 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -304,6 +304,7 @@ stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" +tesouro.base_url = "https://api.sandbox.tesouro.com" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" tokenex.base_url = "https://test-api.tokenex.com" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index fdcb7891f30..067a84374cd 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -142,6 +142,7 @@ stripe.base_url = "https://api.stripe.com/" stripe.base_url_file_upload = "https://files.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" +tesouro.base_url = "https://api.sandbox.tesouro.com" thunes.base_url = "https://api.limonetikqualif.com/" tokenex.base_url = "https://test-api.tokenex.com" tokenio.base_url = "https://api.sandbox.token.io" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 552a6ebb0ed..eddcba5f2cf 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -146,6 +146,7 @@ stripe.base_url = "https://api.stripe.com/" stripe.base_url_file_upload = "https://files.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.taxjar.com/v2/" +tesouro.base_url = "https://api.tesouro.com" thunes.base_url = "https://api.limonetik.com/" tokenex.base_url = "https://api.tokenex.com" tokenio.base_url = "https://api.token.io" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 520883d5558..5e5ffabb103 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -146,6 +146,7 @@ stripe.base_url = "https://api.stripe.com/" stripe.base_url_file_upload = "https://files.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" +tesouro.base_url = "https://api.sandbox.tesouro.com" thunes.base_url = "https://api.limonetikqualif.com/" tokenex.base_url = "https://test-api.tokenex.com" tokenio.base_url = "https://api.sandbox.token.io" diff --git a/config/development.toml b/config/development.toml index 3bab0fc27bb..dde12f9d7e1 100644 --- a/config/development.toml +++ b/config/development.toml @@ -342,6 +342,7 @@ stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" +tesouro.base_url = "https://api.sandbox.tesouro.com" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" tokenex.base_url = "https://test-api.tokenex.com" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index fa082b35522..cad8c309fd9 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -230,6 +230,7 @@ stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" +tesouro.base_url = "https://api.sandbox.tesouro.com" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" tokenex.base_url = "https://test-api.tokenex.com" diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index fec33f7a096..1421acc3373 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -365,6 +365,7 @@ pub struct ConnectorConfig { pub zen: Option<ConnectorTomlConfig>, pub zsl: Option<ConnectorTomlConfig>, pub taxjar: Option<ConnectorTomlConfig>, + pub tesouro: Option<ConnectorTomlConfig>, pub ctp_mastercard: Option<ConnectorTomlConfig>, pub unified_authentication_service: Option<ConnectorTomlConfig>, } diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 06324d681bb..298825066f1 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7178,3 +7178,8 @@ label = "Site where transaction is initiated" placeholder = "Enter site where transaction is initiated" required = true type = "Text" + +[tesouro] +[tesouro.connector_auth.BodyKey] +api_key="Client ID" +key1="Client Secret" \ No newline at end of file diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 9f481999194..14db75303c3 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5915,3 +5915,8 @@ label = "Site where transaction is initiated" placeholder = "Enter site where transaction is initiated" required = true type = "Text" + +[tesouro] +[tesouro.connector_auth.BodyKey] +api_key="Client ID" +key1="Client Secret" \ No newline at end of file diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 9084f0c7635..ca5ea1459dc 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7156,3 +7156,8 @@ label = "Site where transaction is initiated" placeholder = "Enter site where transaction is initiated" required = true type = "Text" + +[tesouro] +[tesouro.connector_auth.BodyKey] +api_key="Client ID" +key1="Client Secret" \ No newline at end of file diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index d0b8ed74eb9..60becb9804c 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -109,6 +109,7 @@ pub mod stax; pub mod stripe; pub mod stripebilling; pub mod taxjar; +pub mod tesouro; pub mod threedsecureio; pub mod thunes; pub mod tokenex; @@ -157,9 +158,9 @@ pub use self::{ powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, santander::Santander, shift4::Shift4, sift::Sift, signifyd::Signifyd, silverflow::Silverflow, square::Square, stax::Stax, - stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, - thunes::Thunes, tokenex::Tokenex, tokenio::Tokenio, trustpay::Trustpay, - trustpayments::Trustpayments, tsys::Tsys, + stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, tesouro::Tesouro, + threedsecureio::Threedsecureio, thunes::Thunes, tokenex::Tokenex, tokenio::Tokenio, + trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, worldpay::Worldpay, worldpayvantiv::Worldpayvantiv, worldpayxml::Worldpayxml, xendit::Xendit, diff --git a/crates/hyperswitch_connectors/src/connectors/tesouro.rs b/crates/hyperswitch_connectors/src/connectors/tesouro.rs new file mode 100644 index 00000000000..cdd0d81c6df --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/tesouro.rs @@ -0,0 +1,624 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::enums; +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 tesouro; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Tesouro { + amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), +} + +impl Tesouro { + pub fn new() -> &'static Self { + &Self { + amount_converter: &FloatMajorUnitForConnector, + } + } +} + +impl api::Payment for Tesouro {} +impl api::PaymentSession for Tesouro {} +impl api::ConnectorAccessToken for Tesouro {} +impl api::MandateSetup for Tesouro {} +impl api::PaymentAuthorize for Tesouro {} +impl api::PaymentSync for Tesouro {} +impl api::PaymentCapture for Tesouro {} +impl api::PaymentVoid for Tesouro {} +impl api::Refund for Tesouro {} +impl api::RefundExecute for Tesouro {} +impl api::RefundSync for Tesouro {} +impl api::PaymentToken for Tesouro {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Tesouro +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Tesouro +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 Tesouro { + fn id(&self) -> &'static str { + "tesouro" + } + + 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.tesouro.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = tesouro::TesouroAuthType::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: tesouro::TesouroErrorResponse = res + .response + .parse_struct("TesouroErrorResponse") + .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, + connector_metadata: None, + }) + } +} + +impl ConnectorValidation for Tesouro { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Tesouro { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Tesouro {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Tesouro {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Tesouro { + 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 = tesouro::TesouroRouterData::from((amount, req)); + let connector_req = tesouro::TesouroPaymentsRequest::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: tesouro::TesouroPaymentsResponse = res + .response + .parse_struct("Tesouro 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 Tesouro { + 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: tesouro::TesouroPaymentsResponse = res + .response + .parse_struct("tesouro 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 Tesouro { + 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: tesouro::TesouroPaymentsResponse = res + .response + .parse_struct("Tesouro 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 Tesouro {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tesouro { + 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 = tesouro::TesouroRouterData::from((refund_amount, req)); + let connector_req = tesouro::TesouroRefundRequest::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: tesouro::RefundResponse = res + .response + .parse_struct("tesouro 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 Tesouro { + 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: tesouro::RefundResponse = res + .response + .parse_struct("tesouro 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 Tesouro { + 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)) + } +} + +static TESOURO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static TESOURO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Tesouro", + description: "Tesouro connects software companies and banks in one unified ecosystem, simplifying payments", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, +}; + +static TESOURO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Tesouro { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&TESOURO_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*TESOURO_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&TESOURO_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs new file mode 100644 index 00000000000..89ca59873ee --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs @@ -0,0 +1,219 @@ +use common_enums::enums; +use common_utils::types::FloatMajorUnit; +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}; + +//TODO: Fill the struct with respective fields +pub struct TesouroRouterData<T> { + pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(FloatMajorUnit, T)> for TesouroRouterData<T> { + fn from((amount, item): (FloatMajorUnit, 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 TesouroPaymentsRequest { + amount: FloatMajorUnit, + card: TesouroCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct TesouroCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&TesouroRouterData<&PaymentsAuthorizeRouterData>> for TesouroPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &TesouroRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct TesouroAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for TesouroAuthType { + 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, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum TesouroPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<TesouroPaymentStatus> for common_enums::AttemptStatus { + fn from(item: TesouroPaymentStatus) -> Self { + match item { + TesouroPaymentStatus::Succeeded => Self::Charged, + TesouroPaymentStatus::Failed => Self::Failure, + TesouroPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct TesouroPaymentsResponse { + status: TesouroPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, TesouroPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, TesouroPaymentsResponse, 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 TesouroRefundRequest { + pub amount: FloatMajorUnit, +} + +impl<F> TryFrom<&TesouroRouterData<&RefundsRouterData<F>>> for TesouroRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &TesouroRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 TesouroErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 2d7e5e34746..f035b90a820 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -275,6 +275,7 @@ default_imp_for_authorize_session_token!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::UnifiedAuthenticationService, connectors::Volt, connectors::Threedsecureio, @@ -420,6 +421,7 @@ default_imp_for_calculate_tax!( connectors::Square, connectors::Stripe, connectors::Stripebilling, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -527,6 +529,7 @@ default_imp_for_session_update!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -672,6 +675,7 @@ default_imp_for_post_session_tokens!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -814,6 +818,7 @@ default_imp_for_create_order!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -960,6 +965,7 @@ default_imp_for_update_metadata!( connectors::Stax, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -1106,6 +1112,7 @@ default_imp_for_cancel_post_capture!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -1268,6 +1275,7 @@ default_imp_for_complete_authorize!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1410,6 +1418,7 @@ default_imp_for_incremental_authorization!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1548,6 +1557,7 @@ default_imp_for_create_customer!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1679,6 +1689,7 @@ default_imp_for_connector_redirect_response!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1818,6 +1829,7 @@ default_imp_for_pre_authenticate_steps!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1962,6 +1974,7 @@ default_imp_for_authenticate_steps!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2106,6 +2119,7 @@ default_imp_for_post_authenticate_steps!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2239,6 +2253,7 @@ default_imp_for_pre_processing_steps!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2382,6 +2397,7 @@ default_imp_for_post_processing_steps!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2529,6 +2545,7 @@ default_imp_for_approve!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2676,6 +2693,7 @@ default_imp_for_reject!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2822,6 +2840,7 @@ default_imp_for_webhook_source_verification!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2968,6 +2987,7 @@ default_imp_for_accept_dispute!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3111,6 +3131,7 @@ default_imp_for_submit_evidence!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3255,6 +3276,7 @@ default_imp_for_defend_dispute!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3402,6 +3424,7 @@ default_imp_for_fetch_disputes!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3548,6 +3571,7 @@ default_imp_for_dispute_sync!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3700,6 +3724,7 @@ default_imp_for_file_upload!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3831,6 +3856,7 @@ default_imp_for_payouts!( connectors::Stax, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Tokenex, connectors::Tokenio, @@ -3973,6 +3999,7 @@ default_imp_for_payouts_create!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4119,6 +4146,7 @@ default_imp_for_payouts_retrieve!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4264,6 +4292,7 @@ default_imp_for_payouts_eligibility!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4404,6 +4433,7 @@ default_imp_for_payouts_fulfill!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4548,6 +4578,7 @@ default_imp_for_payouts_cancel!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4694,6 +4725,7 @@ default_imp_for_payouts_quote!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4839,6 +4871,7 @@ default_imp_for_payouts_recipient!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4985,6 +5018,7 @@ default_imp_for_payouts_recipient_account!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -5132,6 +5166,7 @@ default_imp_for_frm_sale!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -5279,6 +5314,7 @@ default_imp_for_frm_checkout!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -5426,6 +5462,7 @@ default_imp_for_frm_transaction!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -5573,6 +5610,7 @@ default_imp_for_frm_fulfillment!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -5720,6 +5758,7 @@ default_imp_for_frm_record_return!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -5863,6 +5902,7 @@ default_imp_for_revoking_mandates!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -6008,6 +6048,7 @@ default_imp_for_uas_pre_authentication!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -6152,6 +6193,7 @@ default_imp_for_uas_post_authentication!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -6297,6 +6339,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -6433,6 +6476,7 @@ default_imp_for_connector_request_id!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -6572,6 +6616,7 @@ default_imp_for_fraud_check!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -6741,6 +6786,7 @@ default_imp_for_connector_authentication!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, @@ -6884,6 +6930,7 @@ default_imp_for_uas_authentication!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -7022,6 +7069,7 @@ default_imp_for_revenue_recovery!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -7191,6 +7239,7 @@ default_imp_for_subscriptions!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -7338,6 +7387,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Stax, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -7484,6 +7534,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Stax, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -7632,6 +7683,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Stripebilling, connectors::Threedsecureio, connectors::Taxjar, + connectors::Tesouro, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, @@ -7771,6 +7823,7 @@ default_imp_for_external_vault!( connectors::Stripebilling, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenio, @@ -7916,6 +7969,7 @@ default_imp_for_external_vault_insert!( connectors::Stripebilling, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenio, @@ -8059,6 +8113,7 @@ default_imp_for_gift_card_balance_check!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -8206,6 +8261,7 @@ default_imp_for_external_vault_retrieve!( connectors::Stripebilling, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenio, @@ -8351,6 +8407,7 @@ default_imp_for_external_vault_delete!( connectors::Stripebilling, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -8497,6 +8554,7 @@ default_imp_for_external_vault_create!( connectors::Stripebilling, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -8643,6 +8701,7 @@ default_imp_for_connector_authentication_token!( connectors::Stripebilling, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -8788,6 +8847,7 @@ default_imp_for_external_vault_proxy_payments_create!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 621e41dcb93..570977048f8 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -377,6 +377,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -524,6 +525,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -660,6 +662,7 @@ default_imp_for_new_connector_integration_connector_authentication_token!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -801,6 +804,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -948,6 +952,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1095,6 +1100,7 @@ default_imp_for_new_connector_integration_fetch_disputes!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1243,6 +1249,7 @@ default_imp_for_new_connector_integration_dispute_sync!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1391,6 +1398,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1537,6 +1545,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1694,6 +1703,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1843,6 +1853,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -1992,6 +2003,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2141,6 +2153,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2290,6 +2303,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2439,6 +2453,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2588,6 +2603,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2737,6 +2753,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -2886,6 +2903,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3033,6 +3051,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3182,6 +3201,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3331,6 +3351,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3480,6 +3501,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3629,6 +3651,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3778,6 +3801,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -3923,6 +3947,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4038,6 +4063,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Stripe, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4182,6 +4208,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Stripe, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4318,6 +4345,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Stripe, connectors::Square, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4490,6 +4518,7 @@ default_imp_for_new_connector_integration_external_vault!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, @@ -4636,6 +4665,7 @@ default_imp_for_new_connector_integration_external_vault_proxy!( connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, + connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rs index cca03101902..7f1657c0a35 100644 --- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs +++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs @@ -125,6 +125,7 @@ pub struct Connectors { pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, + pub tesouro: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub tokenex: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 895d9ae1a2e..3bed6948c39 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -40,10 +40,10 @@ pub use hyperswitch_connectors::connectors::{ redsys::Redsys, riskified, riskified::Riskified, santander, santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, stripe::Stripe, - stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, threedsecureio, - threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, tokenex::Tokenex, tokenio, - tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, - tsys, tsys::Tsys, unified_authentication_service, + stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, tesouro, tesouro::Tesouro, + threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, + tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, + trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index fbabe1155f4..6f671a243e1 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -111,6 +111,7 @@ mod stax; mod stripe; mod stripebilling; mod taxjar; +mod tesouro; mod tokenex; mod tokenio; mod trustpay; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 5b79c5ef2e7..f48e67aff87 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -369,4 +369,8 @@ api_key="EOrder Token" [peachpayments] api_key="API Key" -key1="Tenant ID" \ No newline at end of file +key1="Tenant ID" + +[tesouro] +api_key="Client ID" +key1="Client Secret" \ No newline at end of file diff --git a/crates/router/tests/connectors/tesouro.rs b/crates/router/tests/connectors/tesouro.rs new file mode 100644 index 00000000000..44e74552fa1 --- /dev/null +++ b/crates/router/tests/connectors/tesouro.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 TesouroTest; +impl ConnectorActions for TesouroTest {} +impl utils::Connector for TesouroTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Tesouro; + utils::construct_connector_data_old( + Box::new(Tesouro::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .tesouro + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "tesouro".to_string() + } +} + +static CONNECTOR: TesouroTest = TesouroTest {}; + +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/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 1208173abd1..c51c415321d 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -119,6 +119,7 @@ pub struct ConnectorAuthentication { pub stripe: Option<HeaderKey>, pub stripebilling: Option<HeaderKey>, pub taxjar: Option<HeaderKey>, + pub tesouro: Option<HeaderKey>, pub threedsecureio: Option<HeaderKey>, pub thunes: Option<HeaderKey>, pub tokenex: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 5818cee9519..d15eea9da40 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -197,6 +197,7 @@ stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" +tesouro.base_url = "https://api.sandbox.tesouro.com" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" tokenex.base_url = "https://test-api.tokenex.com" diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 22573052f11..25dce6cd58b 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 affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet gigadat globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet gigadat globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar tesouro threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
2025-09-25T07:01:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Template for Tesouro integration ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
93b97ef5202c592aded23d7819bcef8eb27a2977
juspay/hyperswitch
juspay__hyperswitch-9510
Bug: [BUG] (nuvei) 4xx error when eci_provider = nill for applepay ### Bug Description For some card eci provider is nill . ### Expected Behavior No error should be thrown ### Actual Behavior - ### 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? None
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 1329bd0a056..39776916056 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -1221,15 +1221,7 @@ fn get_apple_pay_decrypt_data( .online_payment_cryptogram .clone(), ), - eci_provider: Some( - apple_pay_predecrypt_data - .payment_data - .eci_indicator - .clone() - .ok_or_else(missing_field_err( - "payment_method_data.wallet.apple_pay.payment_data.eci_indicator", - ))?, - ), + eci_provider: apple_pay_predecrypt_data.payment_data.eci_indicator.clone(), }), ..Default::default() }),
2025-09-23T09:52:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Some cards have optional `eci_provider` which causes 4xx missing field error. Make that optional. ### Test : ### Request ```json { "amount": 6500, "currency": "USD", "email": "[email protected]", "customer_id": "hello5", "capture_method": "automatic", "confirm": true, "return_url": "https://hyperswitch-demo-store.netlify.app/?isTestingMode=true&hyperswitchClientUrl=https://beta.hyperswitch.io/v1&hyperswitchCustomPodUri=&hyperswitchCustomBackendUrl=&publishableKey=pk_snd_e6c328fa58824247865647d532583e66&secretKey=snd_H0f0rZqfaXlv6kz81O6tQptd2e250u5vlFsA1L50ogMglapamZmDzJ7qRlj4mNlM&profileId=pro_PxNHqEwbZM6rbIfgClSg&environment=Sandbox", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "eyJkYXRhIjoiSWRNbUFu***************d****************2NDQ5NDlmMWUxNGZiYmM4NTdiNjk5N2NkYWJlMzczZGEyOTI3ZmU5NzcifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 0492", "network": "Visa", "type": "debit" }, "transaction_identifier": "85ea39d59610a6860eb723644949f1e14fbbc857b6997cdabe373da2927fe977" } } }, "payment_method": "wallet", "payment_method_type": "apple_pay", "connector": [ "nuvei" ], "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "en-US", "color_depth": 24, "screen_height": 1117, "screen_width": 1728, "ip_address": "192.168.1.1", "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "device_model": "Macintosh", "os_type": "macOS", "os_version": "10.15.7" }, "payment_type": "normal" } ``` ### response ```json { "payment_id": "pay_7wu0YSHTd8LFDE8KD2UN", "merchant_id": "merchant_1758115709", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "nuvei", "client_secret": "pay_7wu0YSHTd8LFDE8KD2UN_secret_kIWxoLIlS4kexcOCmHz1", "created": "2025-09-18T07:35:21.765Z", "currency": "USD", "customer_id": "hello5", "customer": { "id": "hello5", "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": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "0492", "card_network": "Visa", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://hyperswitch-demo-store.netlify.app/?isTestingMode=true&hyperswitchClientUrl=https://beta.hyperswitch.io/v1&hyperswitchCustomPodUri=&hyperswitchCustomBackendUrl=&publishableKey=pk_snd_e6c328fa58824247865647d532583e66&secretKey=snd_H0f0rZqfaXlv6kz81O6tQptd2e250u5vlFsA1L50ogMglapamZmDzJ7qRlj4mNlM&profileId=pro_PxNHqEwbZM6rbIfgClSg&environment=Sandbox", "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": "apple_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "hello5", "created_at": 1758180921, "expires": 1758184521, "secret": "epk_228ed6b0222a461b9497d73df63c5e11" }, "manual_retry_allowed": null, "connector_transaction_id": "7110000000017082220", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8937234111", "payment_link": null, "profile_id": "pro_G0scDt6GAZBxs3brIkts", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_4ioDaxsfaPf9R3aZCrE6", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-18T07:50:21.765Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "192.168.1.1", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15", "color_depth": 24, "device_model": "Macintosh", "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_channel": null, "payment_method_id": null, "network_transaction_id": "", "payment_method_status": null, "updated": "2025-09-18T07:35:25.366Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ab00b083e963a5d5228af6b061b603a68d7efa17
juspay/hyperswitch
juspay__hyperswitch-9520
Bug: chore: address Rust 1.90.0 clippy lints Address the clippy lints occurring due to new rust version 1.90.0 See [#3391](https://github.com/juspay/hyperswitch/issues/3391) for more information.
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 926c28684e8..c7b704d0e8b 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -112,7 +112,7 @@ where fn encode_by_ref( &self, buf: &mut PgArgumentBuffer, - ) -> Result<sqlx::encode::IsNull, Box<(dyn std::error::Error + Send + Sync + 'static)>> { + ) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync + 'static>> { <String as Encode<'q, Postgres>>::encode(self.0.to_string(), buf) } fn size_hint(&self) -> usize { diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index ebc244832b0..02ea56b6d36 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -115,12 +115,6 @@ struct CreditCardDetails { card_code: Option<Secret<String>>, } -#[derive(Serialize, Deserialize, Debug)] -#[serde(rename_all = "camelCase")] -struct BankAccountDetails { - account_number: Secret<String>, -} - #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] enum PaymentDetails { diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs index 056e546db20..dcda455e2b6 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs @@ -287,13 +287,6 @@ pub enum UsageMode { UseNetworkToken, } -#[derive(Default, Debug, Serialize, Deserialize)] -pub struct GlobalPayPayer { - /// Unique identifier for the Payer on the Global Payments system. - #[serde(rename = "id", skip_serializing_if = "Option::is_none")] - pub payer_id: Option<String>, -} - #[derive(Default, Debug, Serialize)] pub struct GlobalPayPaymentMethodsRequest { pub reference: String, diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs index daa629641e6..89f5da8ba1d 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs @@ -49,19 +49,6 @@ pub struct Card { pub brand_reference: Option<Secret<String>>, } -/// A string used to identify the payment method provider being used to execute this -/// transaction. -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ApmProvider { - Giropay, - Ideal, - Paypal, - Sofort, - Eps, - Testpay, -} - /// Indicates where a transaction is in its lifecycle. #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] @@ -112,18 +99,6 @@ pub enum GlobalpayWebhookStatus { Unknown, } -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum GlobalpayPaymentMethodStatus { - /// The entity is ACTIVE and can be used. - Active, - /// The entity is INACTIVE and cannot be used. - Inactive, - /// The status is DELETED. Once returned in an action response for a resource. - /// The resource has been removed from the platform. - Delete, -} - #[derive(Debug, Serialize, Deserialize)] pub struct GlobalpayPaymentMethodsResponse { #[serde(rename = "id")] diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 68ad70da2a7..930f4aa1595 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -413,12 +413,6 @@ pub struct NexixpayCard { cvv: Secret<String>, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -struct Recurrence { - action: String, -} - #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentsResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/payload/responses.rs b/crates/hyperswitch_connectors/src/connectors/payload/responses.rs index 888213be527..f04e6b73a6e 100644 --- a/crates/hyperswitch_connectors/src/connectors/payload/responses.rs +++ b/crates/hyperswitch_connectors/src/connectors/payload/responses.rs @@ -49,14 +49,6 @@ pub struct PayloadCardsResponseData { pub response_type: Option<String>, } -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct PayloadCardResponse { - pub card_brand: String, - pub card_number: String, // Masked card number like "xxxxxxxxxxxx4242" - pub card_type: String, - pub expiry: Secret<String>, -} - // Type definition for Refund Response // Added based on assumptions since this is not provided in the documentation #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] diff --git a/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs index 4df231a918e..c23bc40a975 100644 --- a/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs +++ b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs @@ -163,7 +163,7 @@ impl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest { item_is_digital: order_detail .product_type .as_ref() - .map(|product| (product == &common_enums::ProductType::Digital)), + .map(|product| product == &common_enums::ProductType::Digital), }) .collect::<Vec<_>>(); let metadata: SignifydFrmMetadata = item @@ -397,7 +397,7 @@ impl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest { item_is_digital: order_detail .product_type .as_ref() - .map(|product| (product == &common_enums::ProductType::Digital)), + .map(|product| product == &common_enums::ProductType::Digital), }) .collect::<Vec<_>>(); let metadata: SignifydFrmMetadata = item diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs index a43ffb7cfa1..d8aeea2b3bb 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs @@ -161,16 +161,6 @@ pub struct BillingAddress { pub country_code: common_enums::CountryAlpha2, } -#[derive( - Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, -)] -#[serde(rename_all = "camelCase")] -pub enum Channel { - #[default] - Ecom, - Moto, -} - #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Customer { diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs index b1a3a86a04f..3f684a694d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs @@ -258,11 +258,6 @@ pub struct EventLinks { pub events: Option<String>, } -#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] -pub struct PaymentLink { - pub href: String, -} - pub fn get_resource_id<T, F>( response: WorldpayPaymentsResponse, connector_transaction_id: Option<String>, @@ -455,19 +450,5 @@ pub struct WorldpayWebhookEventType { pub event_details: EventDetails, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "camelCase")] -pub enum WorldpayWebhookStatus { - SentForSettlement, - Authorized, - SentForAuthorization, - Cancelled, - Error, - Expired, - Refused, - SentForRefund, - RefundFailed, -} - /// Worldpay's unique reference ID for a request pub(super) const WP_CORRELATION_ID: &str = "WP-CorrelationId"; diff --git a/crates/router/src/core/fraud_check/operation.rs b/crates/router/src/core/fraud_check/operation.rs index 4750fd11177..b1b9540d9c1 100644 --- a/crates/router/src/core/fraud_check/operation.rs +++ b/crates/router/src/core/fraud_check/operation.rs @@ -22,7 +22,7 @@ pub trait FraudCheckOperation<F, D>: Send + std::fmt::Debug { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("get tracker interface not found for {self:?}")) } - fn to_domain(&self) -> RouterResult<&(dyn Domain<F, D>)> { + fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("domain interface not found for {self:?}")) } diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs index 7dbe590ca35..5ebeadf900c 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs @@ -54,7 +54,7 @@ where fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> { Ok(*self) } - fn to_domain(&self) -> RouterResult<&(dyn Domain<F, D>)> { + fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> { Ok(*self) } fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> { @@ -74,7 +74,7 @@ where fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> { Ok(self) } - fn to_domain(&self) -> RouterResult<&(dyn Domain<F, D>)> { + fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> { Ok(self) } fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> { diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs index 0c42bdeacb3..829fa33311f 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs @@ -45,7 +45,7 @@ where fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> { Ok(*self) } - fn to_domain(&self) -> RouterResult<&(dyn Domain<F, D>)> { + fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> { Ok(*self) } fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> { @@ -61,7 +61,7 @@ where fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> { Ok(self) } - fn to_domain(&self) -> RouterResult<&(dyn Domain<F, D>)> { + fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> { Ok(self) } fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> { diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index ab3b7cba577..2e420dc5cec 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -151,7 +151,7 @@ pub trait StorageInterface: { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface>; - fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)>; + fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>; } #[async_trait::async_trait] @@ -166,7 +166,7 @@ pub trait GlobalStorageInterface: + RedisConnInterface + 'static { - fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)>; + fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>; } #[async_trait::async_trait] @@ -224,14 +224,14 @@ impl StorageInterface for Store { Box::new(self.clone()) } - fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } #[async_trait::async_trait] impl GlobalStorageInterface for Store { - fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } @@ -247,14 +247,14 @@ impl StorageInterface for MockDb { Box::new(self.clone()) } - fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } #[async_trait::async_trait] impl GlobalStorageInterface for MockDb { - fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 68ef8d19619..8bbee6ab8cf 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3316,13 +3316,13 @@ impl StorageInterface for KafkaStore { Box::new(self.clone()) } - fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } impl GlobalStorageInterface for KafkaStore { - fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 56ebfa66062..2a4c02efbe3 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -233,7 +233,7 @@ impl SessionStateInfo for SessionState { fn session_state(&self) -> SessionState { self.clone() } - fn global_store(&self) -> Box<(dyn GlobalStorageInterface)> { + fn global_store(&self) -> Box<dyn GlobalStorageInterface> { self.global_store.to_owned() } } diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index d690ebd3277..9e54e673b9c 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -24,10 +24,7 @@ pub trait RequestBuilder: Send + Sync { fn send( self, ) -> CustomResult< - Box< - (dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> - + 'static), - >, + Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>, ApiClientError, >; } @@ -154,10 +151,7 @@ impl RequestBuilder for RouterRequestBuilder { fn send( self, ) -> CustomResult< - Box< - (dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> - + 'static), - >, + Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>, ApiClientError, > { Ok(Box::new(
2025-09-23T10:28:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR addresses the clippy lints occurring due to new rust version 1.90.0 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1866" height="513" alt="image" src="https://github.com/user-attachments/assets/9358b4cc-2c33-4350-b61f-d52c4d1b2cd2" /> <img width="1866" height="589" alt="image" src="https://github.com/user-attachments/assets/f0a03929-98c7-4aa6-ad78-0c9fc0f08d8a" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ab00b083e963a5d5228af6b061b603a68d7efa17
juspay/hyperswitch
juspay__hyperswitch-9534
Bug: [FEATURE] Stored credential Indicator ### Feature Description Connectors like Nuvei requires a field called as storedCredentialMode which represents if the merchant is using a card details which they previously used for same connector or any other PSP. This is used for risk lowering based on PSP's. Make a is_stored_credential in payment request if the merchant knows this is stored_credential. ( in this case merchant stores the card in his server . No way hyperswitch knows if this is stored or not) if is_stored_credential = false but using payment token or mandate or recurring flow : throw error. if is_stored_credential = None but using payment token or mandate or recurring flow : make the is_stored_credential as true in core ### Possible Implementation - ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 840ab7537f0..55e13f5b094 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1291,6 +1291,10 @@ pub struct PaymentsRequest { #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<bool>, example = true)] pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, + + /// Boolean flag indicating whether this payment method is stored and has been previously used for payments + #[schema(value_type = Option<bool>, example = true)] + pub is_stored_credential: Option<bool>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -1445,6 +1449,24 @@ impl PaymentsRequest { }) .transpose() } + pub fn validate_stored_credential( + &self, + ) -> common_utils::errors::CustomResult<(), ValidationError> { + if self.is_stored_credential == Some(false) + && (self.recurring_details.is_some() + || self.payment_token.is_some() + || self.mandate_id.is_some()) + { + Err(ValidationError::InvalidValue { + message: + "is_stored_credential should be true when reusing stored payment method data" + .to_string(), + } + .into()) + } else { + Ok(()) + } + } } #[cfg(feature = "v1")] @@ -5692,6 +5714,10 @@ pub struct PaymentsResponse { /// Contains card network response details (e.g., Visa/Mastercard advice codes). #[schema(value_type = Option<NetworkDetails>)] pub network_details: Option<NetworkDetails>, + + /// Boolean flag indicating whether this payment method is stored and has been previously used for payments + #[schema(value_type = Option<bool>, example = true)] + pub is_stored_credential: Option<bool>, } #[cfg(feature = "v2")] diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 8cd2525b84a..002c9f7d5b6 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -107,6 +107,7 @@ pub struct PaymentAttempt { pub network_transaction_id: Option<String>, pub is_overcapture_enabled: Option<OvercaptureEnabledBool>, pub network_details: Option<NetworkDetails>, + pub is_stored_credential: Option<bool>, #[diesel(deserialize_as = RequiredFromNullable<storage_enums::PaymentMethod>)] pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, @@ -226,6 +227,7 @@ pub struct PaymentAttempt { pub network_transaction_id: Option<String>, pub is_overcapture_enabled: Option<OvercaptureEnabledBool>, pub network_details: Option<NetworkDetails>, + pub is_stored_credential: Option<bool>, } #[cfg(feature = "v1")] @@ -328,6 +330,7 @@ pub struct PaymentAttemptNew { pub connector_response_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, + pub is_stored_credential: Option<bool>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, @@ -452,6 +455,7 @@ pub struct PaymentAttemptNew { pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, + pub is_stored_credential: Option<bool>, } #[cfg(feature = "v1")] @@ -487,6 +491,7 @@ pub enum PaymentAttemptUpdate { updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, routing_approach: Option<storage_enums::RoutingApproach>, + is_stored_credential: Option<bool>, }, AuthenticationTypeUpdate { authentication_type: storage_enums::AuthenticationType, @@ -529,6 +534,7 @@ pub enum PaymentAttemptUpdate { routing_approach: Option<storage_enums::RoutingApproach>, connector_request_reference_id: Option<String>, network_transaction_id: Option<String>, + is_stored_credential: Option<bool>, request_extended_authorization: Option<RequestExtendedAuthorizationBool>, }, VoidUpdate { @@ -1017,6 +1023,7 @@ impl PaymentAttemptUpdateInternal { is_overcapture_enabled: source.is_overcapture_enabled, network_details: source.network_details, attempts_group_id: source.attempts_group_id, + is_stored_credential: source.is_stored_credential, } } } @@ -1086,6 +1093,7 @@ pub struct PaymentAttemptUpdateInternal { pub network_transaction_id: Option<String>, pub is_overcapture_enabled: Option<OvercaptureEnabledBool>, pub network_details: Option<NetworkDetails>, + pub is_stored_credential: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, } @@ -1281,6 +1289,7 @@ impl PaymentAttemptUpdate { network_transaction_id, is_overcapture_enabled, network_details, + is_stored_credential, request_extended_authorization, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); PaymentAttempt { @@ -1354,6 +1363,7 @@ impl PaymentAttemptUpdate { network_transaction_id: network_transaction_id.or(source.network_transaction_id), is_overcapture_enabled: is_overcapture_enabled.or(source.is_overcapture_enabled), network_details: network_details.or(source.network_details), + is_stored_credential: is_stored_credential.or(source.is_stored_credential), request_extended_authorization: request_extended_authorization .or(source.request_extended_authorization), ..source @@ -2696,6 +2706,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::AuthenticationTypeUpdate { @@ -2764,6 +2775,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::ConfirmUpdate { @@ -2803,6 +2815,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { routing_approach, connector_request_reference_id, network_transaction_id, + is_stored_credential, request_extended_authorization, } => Self { amount: Some(amount), @@ -2867,6 +2880,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id, is_overcapture_enabled: None, network_details: None, + is_stored_credential, request_extended_authorization, }, PaymentAttemptUpdate::VoidUpdate { @@ -2936,6 +2950,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::RejectUpdate { @@ -3006,6 +3021,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::BlocklistUpdate { @@ -3076,6 +3092,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::ConnectorMandateDetailUpdate { @@ -3144,6 +3161,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::PaymentMethodDetailsUpdate { @@ -3212,6 +3230,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::ResponseUpdate { @@ -3310,6 +3329,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id, is_overcapture_enabled, network_details: None, + is_stored_credential: None, request_extended_authorization: None, } } @@ -3398,6 +3418,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details, + is_stored_credential: None, request_extended_authorization: None, } } @@ -3464,6 +3485,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::UpdateTrackers { @@ -3476,6 +3498,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, merchant_connector_id, routing_approach, + is_stored_credential, } => Self { payment_token, modified_at: common_utils::date_time::now(), @@ -3539,6 +3562,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential, request_extended_authorization: None, }, PaymentAttemptUpdate::UnresolvedResponseUpdate { @@ -3620,6 +3644,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, } } @@ -3700,6 +3725,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, } } @@ -3770,6 +3796,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::AmountToCaptureUpdate { @@ -3839,6 +3866,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::ConnectorResponse { @@ -3917,6 +3945,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, } } @@ -3986,6 +4015,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::AuthenticationUpdate { @@ -4057,6 +4087,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, PaymentAttemptUpdate::ManualUpdate { @@ -4137,6 +4168,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, } } @@ -4206,6 +4238,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_transaction_id: None, is_overcapture_enabled: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 4de3c14806e..7cddb536033 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1083,6 +1083,7 @@ diesel::table! { network_transaction_id -> Nullable<Varchar>, is_overcapture_enabled -> Nullable<Bool>, network_details -> Nullable<Jsonb>, + is_stored_credential -> Nullable<Bool>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 38b8a6a6c40..93ad4299c54 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1025,6 +1025,7 @@ diesel::table! { network_transaction_id -> Nullable<Varchar>, is_overcapture_enabled -> Nullable<Bool>, network_details -> Nullable<Jsonb>, + is_stored_credential -> Nullable<Bool>, payment_method_type_v2 -> Nullable<Varchar>, #[max_length = 128] connector_payment_id -> Nullable<Varchar>, diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 9dc2f03a5b0..5f6aa33b0bb 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -220,6 +220,7 @@ pub struct PaymentAttemptBatchNew { pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, + pub is_stored_credential: Option<bool>, } #[cfg(feature = "v1")] @@ -309,6 +310,7 @@ impl PaymentAttemptBatchNew { connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, + is_stored_credential: self.is_stored_credential, } } } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index e9d766f912b..5463496165b 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -17,7 +17,7 @@ use common_utils::{ }; use error_stack::ResultExt; use hyperswitch_domain_models::{ - address::Address, + address::{Address, AddressDetails}, payment_method_data::{ self, ApplePayWalletData, BankRedirectData, CardDetailsForNetworkTransactionId, GooglePayWalletData, PayLaterData, PaymentMethodData, WalletData, @@ -106,6 +106,7 @@ trait NuveiAuthorizePreprocessingCommon { ) -> Result<Option<AuthenticationData>, error_stack::Report<errors::ConnectorError>> { Ok(None) } + fn get_is_stored_credential(&self) -> Option<StoredCredentialMode>; } impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData { @@ -187,6 +188,10 @@ impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData { fn get_ntid(&self) -> Option<String> { None } + + fn get_is_stored_credential(&self) -> Option<StoredCredentialMode> { + StoredCredentialMode::get_optional_stored_credential(self.is_stored_credential) + } } impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { @@ -260,6 +265,10 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { self.enable_partial_authorization .map(PartialApprovalFlag::from) } + + fn get_is_stored_credential(&self) -> Option<StoredCredentialMode> { + StoredCredentialMode::get_optional_stored_credential(self.is_stored_credential) + } } impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { @@ -333,6 +342,10 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { fn get_ntid(&self) -> Option<String> { None } + + fn get_is_stored_credential(&self) -> Option<StoredCredentialMode> { + StoredCredentialMode::get_optional_stored_credential(self.is_stored_credential) + } } #[derive(Debug, Serialize, Default, Deserialize)] @@ -785,8 +798,36 @@ pub struct Card { pub issuer_country: Option<String>, pub is_prepaid: Option<String>, pub external_token: Option<ExternalToken>, + pub stored_credentials: Option<StoredCredentialMode>, } +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredCredentialMode { + pub stored_credentials_mode: Option<StoredCredentialModeType>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum StoredCredentialModeType { + #[serde(rename = "0")] + First, + #[serde(rename = "1")] + Used, +} + +impl StoredCredentialMode { + pub fn get_optional_stored_credential(is_stored_credential: Option<bool>) -> Option<Self> { + is_stored_credential.and_then(|is_stored_credential| { + if is_stored_credential { + Some(Self { + stored_credentials_mode: Some(StoredCredentialModeType::Used), + }) + } else { + None + } + }) + } +} #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ExternalToken { @@ -1015,6 +1056,7 @@ pub struct NuveiCardDetails { card: payment_method_data::Card, three_d: Option<ThreeD>, card_holder_name: Option<Secret<String>>, + stored_credentials: Option<StoredCredentialMode>, } // Define new structs with camelCase serialization @@ -1884,6 +1926,7 @@ where amount_details, items: l2_l3_items, is_partial_approval: item.request.get_is_partial_approval(), + ..request }) } @@ -1903,7 +1946,7 @@ where None }; - let address = item + let address: Option<&AddressDetails> = item .get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()); @@ -1999,6 +2042,7 @@ where card: card_details.clone(), three_d, card_holder_name: item.get_optional_billing_full_name(), + stored_credentials: item.request.get_is_stored_credential(), }), is_moto, ..Default::default() @@ -2015,6 +2059,7 @@ impl From<NuveiCardDetails> for PaymentOption { expiration_year: Some(card.card_exp_year), three_d: card_details.three_d, cvv: Some(card.card_cvc), + stored_credentials: card_details.stored_credentials, ..Default::default() }), ..Default::default() @@ -2038,6 +2083,9 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> card, three_d: None, card_holder_name: item.get_optional_billing_full_name(), + stored_credentials: StoredCredentialMode::get_optional_stored_credential( + item.request.is_stored_credential, + ), }), device_details, ..Default::default() diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 85051693105..73327dfd3c3 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -6759,6 +6759,7 @@ pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data( payment_channel: data.request.payment_channel.clone(), enable_partial_authorization: data.request.enable_partial_authorization, enable_overcapture: None, + is_stored_credential: data.request.is_stored_credential, } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index f1b50182f78..bcce5d59780 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1038,6 +1038,7 @@ pub struct PaymentAttempt { pub network_transaction_id: Option<String>, pub is_overcapture_enabled: Option<OvercaptureEnabledBool>, pub network_details: Option<NetworkDetails>, + pub is_stored_credential: Option<bool>, } #[cfg(feature = "v1")] @@ -1336,6 +1337,7 @@ pub struct PaymentAttemptNew { pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, + pub is_stored_credential: Option<bool>, } #[cfg(feature = "v1")] @@ -1369,6 +1371,7 @@ pub enum PaymentAttemptUpdate { updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, routing_approach: Option<storage_enums::RoutingApproach>, + is_stored_credential: Option<bool>, }, AuthenticationTypeUpdate { authentication_type: storage_enums::AuthenticationType, @@ -1407,6 +1410,7 @@ pub enum PaymentAttemptUpdate { routing_approach: Option<storage_enums::RoutingApproach>, connector_request_reference_id: Option<String>, network_transaction_id: Option<String>, + is_stored_credential: Option<bool>, request_extended_authorization: Option<RequestExtendedAuthorizationBool>, }, RejectUpdate { @@ -1600,6 +1604,7 @@ impl PaymentAttemptUpdate { tax_amount, merchant_connector_id, routing_approach, + is_stored_credential, } => DieselPaymentAttemptUpdate::UpdateTrackers { payment_token, connector, @@ -1617,6 +1622,7 @@ impl PaymentAttemptUpdate { } _ => approach, }), + is_stored_credential, }, Self::AuthenticationTypeUpdate { authentication_type, @@ -1683,6 +1689,7 @@ impl PaymentAttemptUpdate { routing_approach, connector_request_reference_id, network_transaction_id, + is_stored_credential, request_extended_authorization, } => DieselPaymentAttemptUpdate::ConfirmUpdate { amount: net_amount.get_order_amount(), @@ -1728,6 +1735,7 @@ impl PaymentAttemptUpdate { }), connector_request_reference_id, network_transaction_id, + is_stored_credential, request_extended_authorization, }, Self::VoidUpdate { @@ -2178,6 +2186,7 @@ impl behaviour::Conversion for PaymentAttempt { network_transaction_id: self.network_transaction_id, is_overcapture_enabled: self.is_overcapture_enabled, network_details: self.network_details, + is_stored_credential: self.is_stored_credential, }) } @@ -2279,6 +2288,7 @@ impl behaviour::Conversion for PaymentAttempt { network_transaction_id: storage_model.network_transaction_id, is_overcapture_enabled: storage_model.is_overcapture_enabled, network_details: storage_model.network_details, + is_stored_credential: storage_model.is_stored_credential, }) } .await @@ -2371,6 +2381,7 @@ impl behaviour::Conversion for PaymentAttempt { connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, + is_stored_credential: self.is_stored_credential, }) } } @@ -2544,6 +2555,7 @@ impl behaviour::Conversion for PaymentAttempt { is_overcapture_enabled: None, network_details: None, attempts_group_id, + is_stored_credential: None, }) } @@ -2825,6 +2837,7 @@ impl behaviour::Conversion for PaymentAttempt { connector_request_reference_id, network_details: None, attempts_group_id, + is_stored_credential: None, }) } } diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index e21f875f25d..40e17aaaf92 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -88,6 +88,7 @@ pub struct PaymentsAuthorizeData { pub enable_partial_authorization: Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, + pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone)] @@ -343,6 +344,7 @@ impl TryFrom<SetupMandateRequestData> for PaymentsPreProcessingData { metadata: data.metadata, customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, + is_stored_credential: data.is_stored_credential, }) } } @@ -564,6 +566,7 @@ pub struct PaymentsPreProcessingData { pub setup_future_usage: Option<storage_enums::FutureUsage>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, + pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone)] @@ -601,6 +604,7 @@ impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData { metadata: data.metadata.map(Secret::new), customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, + is_stored_credential: data.is_stored_credential, }) } } @@ -750,6 +754,7 @@ impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData { metadata: data.connector_meta.map(Secret::new), customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, + is_stored_credential: data.is_stored_credential, }) } } @@ -818,6 +823,7 @@ pub struct CompleteAuthorizeData { pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>, + pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone)] @@ -1406,6 +1412,7 @@ pub struct SetupMandateRequestData { pub enable_partial_authorization: Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>, pub payment_channel: Option<storage_enums::PaymentChannel>, + pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ac225861b45..d91f1007232 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3043,6 +3043,7 @@ pub async fn list_payment_methods( surcharge_amount: None, tax_amount: None, routing_approach, + is_stored_credential: None, }; state diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 10d72baf282..9f8551e7702 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4804,6 +4804,7 @@ impl AttemptType { connector_request_reference_id: None, network_transaction_id: None, network_details: None, + is_stored_credential: old_payment_attempt.is_stored_credential, } } @@ -7843,3 +7844,20 @@ pub async fn get_merchant_connector_account_v2( .attach_printable("merchant_connector_id is not provided"), } } + +pub fn is_stored_credential( + recurring_details: &Option<RecurringDetails>, + payment_token: &Option<String>, + is_mandate: bool, + is_stored_credential_prev: Option<bool>, +) -> Option<bool> { + if is_stored_credential_prev == Some(true) + || recurring_details.is_some() + || payment_token.is_some() + || is_mandate + { + Some(true) + } else { + is_stored_credential_prev + } +} diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 2c867aa6085..6ce1aa8af7d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1934,7 +1934,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for }; let card_discovery = payment_data.get_card_discovery_for_card_payment_method(); - + let is_stored_credential = helpers::is_stored_credential( + &payment_data.recurring_details, + &payment_data.pm_token, + payment_data.mandate_id.is_some(), + payment_data.payment_attempt.is_stored_credential, + ); let payment_attempt_fut = tokio::spawn( async move { m_db.update_payment_attempt_with_attempt_id( @@ -1988,6 +1993,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for .payment_attempt .network_transaction_id .clone(), + is_stored_credential, request_extended_authorization: payment_data .payment_attempt .request_extended_authorization, @@ -2200,7 +2206,13 @@ impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentDat &request.payment_token, &request.mandate_id, )?; - + request.validate_stored_credential().change_context( + errors::ApiErrorResponse::InvalidRequestData { + message: + "is_stored_credential should be true when reusing stored payment method data" + .to_string(), + }, + )?; let payment_id = request .payment_id .clone() diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index e88a5d51ddd..55a868beec9 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -884,7 +884,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for .map(|surcharge_details| surcharge_details.tax_on_surcharge_amount); let routing_approach = payment_data.payment_attempt.routing_approach.clone(); - + let is_stored_credential = helpers::is_stored_credential( + &payment_data.recurring_details, + &payment_data.pm_token, + payment_data.mandate_id.is_some(), + payment_data.payment_attempt.is_stored_credential, + ); payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( @@ -902,6 +907,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for updated_by: storage_scheme.to_string(), merchant_connector_id, routing_approach, + is_stored_credential, }, storage_scheme, ) @@ -1023,6 +1029,14 @@ impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentDat &request.mandate_id, )?; + request.validate_stored_credential().change_context( + errors::ApiErrorResponse::InvalidRequestData { + message: + "is_stored_credential should be true when reusing stored payment method data" + .to_string(), + }, + )?; + helpers::validate_overcapture_request( &request.enable_overcapture, &request.capture_method, @@ -1313,6 +1327,12 @@ impl PaymentCreate { address_id => address_id, }; + let is_stored_credential = helpers::is_stored_credential( + &request.recurring_details, + &request.payment_token, + request.mandate_id.is_some(), + request.is_stored_credential, + ); Ok(( storage::PaymentAttemptNew { payment_id: payment_id.to_owned(), @@ -1395,6 +1415,7 @@ impl PaymentCreate { connector_request_reference_id: None, network_transaction_id:None, network_details:None, + is_stored_credential }, additional_pm_data, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 020b7c60280..cfd57346625 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -1062,7 +1062,6 @@ impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentDat &request.payment_token, &request.mandate_id, )?; - let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request .routing .clone() diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index e8b7a9914b6..d76d4df6b07 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -748,6 +748,7 @@ pub fn make_new_payment_attempt( connector_request_reference_id: Default::default(), network_transaction_id: old_payment_attempt.network_transaction_id, network_details: Default::default(), + is_stored_credential: old_payment_attempt.is_stored_credential, } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 711b05154b8..fd18e6dda98 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -436,6 +436,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( payment_channel: None, enable_partial_authorization: payment_data.payment_intent.enable_partial_authorization, enable_overcapture: None, + is_stored_credential: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt @@ -1491,6 +1492,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( payment_channel: None, enrolled_for_3ds: true, related_transaction_id: None, + is_stored_credential: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt @@ -3662,6 +3664,7 @@ where network_details: payment_attempt .network_details .map(NetworkDetails::foreign_from), + is_stored_credential: payment_attempt.is_stored_credential, request_extended_authorization: payment_attempt.request_extended_authorization, }; @@ -3963,6 +3966,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay enable_overcapture: pi.enable_overcapture, is_overcapture_enabled: pa.is_overcapture_enabled, network_details: pa.network_details.map(NetworkDetails::foreign_from), + is_stored_credential:pa.is_stored_credential, request_extended_authorization: pa.request_extended_authorization, } } @@ -4296,6 +4300,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz payment_channel: None, enable_partial_authorization: None, enable_overcapture: None, + is_stored_credential: None, }) } } @@ -4530,6 +4535,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz payment_channel: payment_data.payment_intent.payment_channel, enable_partial_authorization: payment_data.payment_intent.enable_partial_authorization, enable_overcapture: payment_data.payment_intent.enable_overcapture, + is_stored_credential: payment_data.payment_attempt.is_stored_credential, }) } } @@ -5505,6 +5511,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ payment_channel: payment_data.payment_intent.payment_channel, related_transaction_id: None, enrolled_for_3ds: true, + is_stored_credential: payment_data.payment_attempt.is_stored_credential, }) } } @@ -5648,6 +5655,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz merchant_account_id, merchant_config_currency, threeds_method_comp_ind: payment_data.threeds_method_comp_ind, + is_stored_credential: payment_data.payment_attempt.is_stored_credential, }) } } @@ -5758,6 +5766,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce metadata: payment_data.payment_intent.metadata.map(Secret::new), customer_acceptance: payment_data.customer_acceptance, setup_future_usage: payment_data.payment_intent.setup_future_usage, + is_stored_credential: payment_data.payment_attempt.is_stored_credential, }) } } diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index 0058c9fd566..c31b106dbfc 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -1411,6 +1411,7 @@ mod tests { is_overcapture_enabled: None, enable_overcapture: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }; let content = diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index a4f024eb81c..def5782d5d5 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -1242,6 +1242,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData { payment_channel: None, enable_partial_authorization: data.request.enable_partial_authorization, enable_overcapture: None, + is_stored_credential: data.request.is_stored_credential, } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index d20bcbfe64f..d233c0696c8 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -69,6 +69,7 @@ impl VerifyConnectorData { payment_channel: None, enable_partial_authorization: None, enable_overcapture: None, + is_stored_credential: None, } } diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index d8d3935e6f7..8332135b312 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -229,6 +229,7 @@ mod tests { connector_request_reference_id: Default::default(), network_transaction_id: Default::default(), network_details: Default::default(), + is_stored_credential: None, }; let store = state @@ -323,6 +324,7 @@ mod tests { connector_request_reference_id: Default::default(), network_transaction_id: Default::default(), network_details: Default::default(), + is_stored_credential: Default::default(), }; let store = state .stores @@ -430,6 +432,7 @@ mod tests { connector_request_reference_id: Default::default(), network_transaction_id: Default::default(), network_details: Default::default(), + is_stored_credential: Default::default(), }; let store = state .stores diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index a49e544097c..0fd23ee2123 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -394,6 +394,7 @@ pub async fn generate_sample_data( connector_request_reference_id: None, network_transaction_id: None, network_details: None, + is_stored_credential: None, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index b2582d7e3fe..34dc5735c91 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -1006,6 +1006,7 @@ impl Default for PaymentAuthorizeType { payment_channel: None, enable_partial_authorization: None, enable_overcapture: None, + is_stored_credential: None, }; Self(data) } diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 2010707067a..85801152bda 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -471,6 +471,7 @@ async fn payments_create_core() { is_overcapture_enabled: None, enable_overcapture: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }; let expected_response = @@ -756,6 +757,7 @@ async fn payments_create_core_adyen_no_redirect() { is_overcapture_enabled: None, enable_overcapture: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }, vec![], diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index ef7f4357640..1378fac9427 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -233,6 +233,7 @@ async fn payments_create_core() { is_overcapture_enabled: None, enable_overcapture: None, network_details: None, + is_stored_credential: None, request_extended_authorization: None, }; @@ -526,6 +527,7 @@ async fn payments_create_core_adyen_no_redirect() { is_overcapture_enabled: None, enable_overcapture: None, network_details: None, + is_stored_credential: None, request_extended_authorization: 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 609bb531a86..2bf5daac6b9 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -241,6 +241,7 @@ impl PaymentAttemptInterface for MockDb { network_transaction_id: payment_attempt.network_transaction_id, is_overcapture_enabled: None, network_details: payment_attempt.network_details, + is_stored_credential: payment_attempt.is_stored_credential, }; 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 6a739f0a6c5..1cfe605cd0e 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -695,6 +695,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { network_transaction_id: payment_attempt.network_transaction_id.clone(), is_overcapture_enabled: None, network_details: payment_attempt.network_details.clone(), + is_stored_credential: payment_attempt.is_stored_credential, }; let field = format!("pa_{}", created_attempt.attempt_id); @@ -1906,6 +1907,7 @@ impl DataModelExt for PaymentAttempt { network_transaction_id: self.network_transaction_id, is_overcapture_enabled: self.is_overcapture_enabled, network_details: self.network_details, + is_stored_credential: self.is_stored_credential, } } @@ -2002,6 +2004,7 @@ impl DataModelExt for PaymentAttempt { network_transaction_id: storage_model.network_transaction_id, is_overcapture_enabled: storage_model.is_overcapture_enabled, network_details: storage_model.network_details, + is_stored_credential: storage_model.is_stored_credential, } } } @@ -2095,6 +2098,7 @@ impl DataModelExt for PaymentAttemptNew { connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, + is_stored_credential: self.is_stored_credential, } } @@ -2181,6 +2185,7 @@ impl DataModelExt for PaymentAttemptNew { connector_request_reference_id: storage_model.connector_request_reference_id, network_transaction_id: storage_model.network_transaction_id, network_details: storage_model.network_details, + is_stored_credential: storage_model.is_stored_credential, } } } diff --git a/migrations/2025-09-22-084821_add_stored_credentials_payment_intent/down.sql b/migrations/2025-09-22-084821_add_stored_credentials_payment_intent/down.sql new file mode 100644 index 00000000000..8398e8ea1ee --- /dev/null +++ b/migrations/2025-09-22-084821_add_stored_credentials_payment_intent/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt DROP COLUMN is_stored_credential; diff --git a/migrations/2025-09-22-084821_add_stored_credentials_payment_intent/up.sql b/migrations/2025-09-22-084821_add_stored_credentials_payment_intent/up.sql new file mode 100644 index 00000000000..17762e006a8 --- /dev/null +++ b/migrations/2025-09-22-084821_add_stored_credentials_payment_intent/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS is_stored_credential BOOLEAN;
2025-09-23T11:35:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Connectors like Nuvei requires a field called as `storedCredentialMode` which represents if the merchant is using a card details which they previously used for same connector or any other PSP. This is used for risk lowering based on PSP's. - Make a `is_stored_credential` in payment request if the merchant knows this is stored_credential. ( in this case merchant stores the card in his server . No way hyperswitch knows if this is stored or not) - if `is_stored_credential` = false but using payment token or mandate or recurring flow : throw error. - if `is_stored_credential` = None but using payment token or mandate or recurring flow : make the is_stored_credential as true in core ### Test cases ## Request `is_stored_credential` = true ```json { "amount": 30000, "capture_method": "automatic", "currency": "USD", "confirm": true, "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" } }, "connector":["nuvei"], "customer_id": "nidthxxinn", "return_url": "https://www.google.com", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "[email protected]", "is_stored_credential":true, "payment_method_data": { "card": { "card_number": "4000000000009995", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } } } ``` ## Connector Request ```json { "timeStamp": "20250923113846", "sessionToken": "*** alloc::string::String ***", "merchantId": "*** alloc::string::String ***", "merchantSiteId": "*** alloc::string::String ***", "clientRequestId": "*** alloc::string::String ***", "amount": "300.00", "currency": "USD", "userTokenId": "nidthxxinn", "clientUniqueId": "", "transactionType": "Sale", "paymentOption": { "card": { "cardNumber": "400000**********", "cardHolderName": "*** alloc::string::String ***", "expirationMonth": "*** alloc::string::String ***", "expirationYear": "*** alloc::string::String ***", "CVV": "*** alloc::string::String ***", "storedCredentials": { "storedCredentialsMode": "1" // stored creds } } }, "deviceDetails": { "ipAddress": "192.**.**.**" }, "checksum": "*** alloc::string::String ***", "billingAddress": { "email": "*****@gmail.com", "firstName": "*** alloc::string::String ***", "lastName": "*** alloc::string::String ***", "country": "US", "city": "*** alloc::string::String ***", "address": "*** alloc::string::String ***", "zip": "*** alloc::string::String ***", "addressLine2": "*** alloc::string::String ***" }, "urlDetails": { "successUrl": "https://google.com", "failureUrl": "https://google.com", "pendingUrl": "https://google.com" }, "amountDetails": { "totalTax": null, "totalShipping": null, "totalHandling": null, "totalDiscount": null } } ``` ### hs response ```json { "payment_id": "pay_kaDCghnJynclrXvAZ3Hr", "merchant_id": "merchant_1758711570", "status": "succeeded", "amount": 4324, "net_amount": 4324, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_kaDCghnJynclrXvAZ3Hr_secret_yYbm6qHvrDNGSZixiLoo", "created": "2025-09-24T11:12:09.304Z", "currency": "EUR", "customer_id": "nidthhxxinn", "customer": { "id": "nidthhxxinn", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "0005", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "378282", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "50", "card_holder_name": "morino", "payment_checks": { "avs_result": "", "avs_description": null, "card_validation_result": "", "card_validation_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_AivOwxhMg1qSr4REuZA9", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nidthhxxinn", "created_at": 1758712329, "expires": 1758715929, "secret": "epk_20c56304f56d4bd093ccbc5e642138be" }, "manual_retry_allowed": null, "connector_transaction_id": "7110000000017350215", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "9126580111", "payment_link": null, "profile_id": "pro_Gs5O4gNYQYl12fxACtnf", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nnxyjSuMhV7SIzNRzEmD", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-24T11:27:09.304Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_r5onP5L210YtcIwJR97v", "network_transaction_id": "483299310332488", "payment_method_status": "active", "updated": "2025-09-24T11:12:15.875Z", "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": "2512601111", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null, "is_stored_credential": true //updated } ``` ## connector request when `is_stored_credential`=false ```json { "timeStamp": "20250923114107", "sessionToken": "*** alloc::string::String ***", "merchantId": "*** alloc::string::String ***", "merchantSiteId": "*** alloc::string::String ***", "clientRequestId": "*** alloc::string::String ***", "amount": "300.00", "currency": "USD", "userTokenId": "nidthxxinn", "clientUniqueId": "", "transactionType": "Sale", "paymentOption": { "card": { "cardNumber": "400000**********", "cardHolderName": "*** alloc::string::String ***", "expirationMonth": "*** alloc::string::String ***", "expirationYear": "*** alloc::string::String ***", "CVV": "*** alloc::string::String ***" } }, "deviceDetails": { "ipAddress": "192.**.**.**" }, "checksum": "*** alloc::string::String ***", "billingAddress": { "email": "*****@gmail.com", "firstName": "*** alloc::string::String ***", "lastName": "*** alloc::string::String ***", "country": "US", "city": "*** alloc::string::String ***", "address": "*** alloc::string::String ***", "zip": "*** alloc::string::String ***", "addressLine2": "*** alloc::string::String ***" }, "urlDetails": { "successUrl": "https://google.com", "failureUrl": "https://google.com", "pendingUrl": "https://google.com" }, "amountDetails": { "totalTax": null, "totalShipping": null, "totalHandling": null, "totalDiscount": null } } ``` ## Error msg when is_stored_credential = false but using payment token flow in HS - make CIT and get payment method token ```json { "amount": 333, "currency": "EUR", "customer_id": "nidthhxxinn", "confirm": true, "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "{{payment_method_id}}"//pass the payment method id here }, "is_stored_credential": false, // false should throw error "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } } ``` ```json { "error": { "type": "invalid_request", "message": "is_stored_credential should be true when reusing stored payment method data", "code": "IR_16" } } ```
5427b07afb1300d9a0ca2f7a7c05e533bd3eb515
juspay/hyperswitch
juspay__hyperswitch-9501
Bug: [FEATURE] add tokenization action handling to payment flow in v2 ### Feature Description This feature add connector-level tokenization to Hyperswitch V2, allowing secure storage of card data as tokens at payment connectors like Braintree. ### Possible Implementation For connector-level tokenization: 1.When a payment comes with raw card data and the connector supports tokenization, send the card details to the connector’s tokenization API. 2. Receive the tokenized payment method ID. 3. Use the token for the subsequent authorization or capture call. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 56db1b8d080..251d8dcc000 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -220,7 +220,7 @@ where let mut connector_http_status_code = None; let (payment_data, connector_response_data) = match connector { ConnectorCallType::PreDetermined(connector_data) => { - let (mca_type_details, updated_customer, router_data) = + let (mca_type_details, updated_customer, router_data, tokenization_action) = call_connector_service_prerequisites( state, req_state.clone(), @@ -260,6 +260,7 @@ where mca_type_details, router_data, updated_customer, + tokenization_action, ) .await?; @@ -300,7 +301,7 @@ where let mut connectors = connectors.clone().into_iter(); let connector_data = get_connector_data(&mut connectors)?; - let (mca_type_details, updated_customer, router_data) = + let (mca_type_details, updated_customer, router_data, tokenization_action) = call_connector_service_prerequisites( state, req_state.clone(), @@ -340,6 +341,7 @@ where mca_type_details, router_data, updated_customer, + tokenization_action, ) .await?; @@ -4387,6 +4389,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, updated_customer: Option<storage::CustomerUpdate>, + tokenization_action: TokenizationAction, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -4416,7 +4419,20 @@ where &mut router_data, &call_connector_action, ); - + let payment_method_token_response = router_data + .add_payment_method_token( + state, + &connector, + &tokenization_action, + should_continue_further, + ) + .await?; + let should_continue_further = tokenization::update_router_data_with_payment_method_token_result( + payment_method_token_response, + &mut router_data, + is_retry_payment, + should_continue_further, + ); let should_continue = match router_data .create_order_at_connector(state, &connector, should_continue_further) .await? @@ -4517,6 +4533,7 @@ pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>( domain::MerchantConnectorAccountTypeDetails, Option<storage::CustomerUpdate>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + TokenizationAction, )> where F: Send + Clone + Sync, @@ -4572,10 +4589,16 @@ where ) .await?; + let tokenization_action = operation + .to_domain()? + .get_connector_tokenization_action(state, payment_data) + .await?; + Ok(( merchant_connector_account_type_details, updated_customer, router_data, + tokenization_action, )) } @@ -4640,25 +4663,29 @@ where .await?, )); - let (merchant_connector_account_type_details, updated_customer, router_data) = - call_connector_service_prerequisites( - state, - req_state, - merchant_context, - connector, - operation, - payment_data, - customer, - call_connector_action, - schedule_time, - header_payload, - frm_suggestion, - business_profile, - is_retry_payment, - should_retry_with_pan, - all_keys_required, - ) - .await?; + let ( + merchant_connector_account_type_details, + updated_customer, + router_data, + _tokenization_action, + ) = call_connector_service_prerequisites( + state, + req_state, + merchant_context, + connector, + operation, + payment_data, + customer, + call_connector_action, + schedule_time, + header_payload, + frm_suggestion, + business_profile, + is_retry_payment, + should_retry_with_pan, + all_keys_required, + ) + .await?; Ok(( merchant_connector_account_type_details, external_vault_merchant_connector_account_type_details, @@ -4884,6 +4911,7 @@ pub async fn decide_unified_connector_service_call<F, RouterDReq, ApiRequest, D> merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, updated_customer: Option<storage::CustomerUpdate>, + tokenization_action: TokenizationAction, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -4975,6 +5003,7 @@ where merchant_connector_account_type_details, router_data, updated_customer, + tokenization_action, ) .await } @@ -6892,6 +6921,48 @@ where Ok(merchant_connector_account) } +#[cfg(feature = "v2")] +fn is_payment_method_tokenization_enabled_for_connector( + state: &SessionState, + connector_name: &str, + payment_method: storage::enums::PaymentMethod, + payment_method_type: Option<storage::enums::PaymentMethodType>, + mandate_flow_enabled: storage_enums::FutureUsage, +) -> RouterResult<bool> { + let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name); + + Ok(connector_tokenization_filter + .map(|connector_filter| { + connector_filter + .payment_method + .clone() + .contains(&payment_method) + && is_payment_method_type_allowed_for_connector( + payment_method_type, + connector_filter.payment_method_type.clone(), + ) + && is_payment_flow_allowed_for_connector( + mandate_flow_enabled, + connector_filter.flow.clone(), + ) + }) + .unwrap_or(false)) +} +// Determines connector tokenization eligibility: if no flow restriction, allow for one-off/CIT with raw cards; if flow = “mandates”, only allow MIT off-session with stored tokens. +#[cfg(feature = "v2")] +fn is_payment_flow_allowed_for_connector( + mandate_flow_enabled: storage_enums::FutureUsage, + payment_flow: Option<PaymentFlow>, +) -> bool { + if payment_flow.is_none() { + true + } else { + matches!(payment_flow, Some(PaymentFlow::Mandates)) + && matches!(mandate_flow_enabled, storage_enums::FutureUsage::OffSession) + } +} + +#[cfg(feature = "v1")] fn is_payment_method_tokenization_enabled_for_connector( state: &SessionState, connector_name: &str, @@ -6924,7 +6995,7 @@ fn is_payment_method_tokenization_enabled_for_connector( }) .unwrap_or(false)) } - +#[cfg(feature = "v1")] fn is_payment_flow_allowed_for_connector( mandate_flow_enabled: Option<storage_enums::FutureUsage>, payment_flow: Option<PaymentFlow>, @@ -7125,6 +7196,7 @@ fn is_payment_method_type_allowed_for_connector( } } +#[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn decide_payment_method_tokenize_action( state: &SessionState, @@ -7194,7 +7266,7 @@ pub struct GooglePayPaymentProcessingDetails { pub google_pay_root_signing_keys: Secret<String>, pub google_pay_recipient_id: Secret<String>, } - +#[cfg(feature = "v1")] #[derive(Clone, Debug)] pub enum TokenizationAction { TokenizeInRouter, @@ -7205,23 +7277,10 @@ pub enum TokenizationAction { } #[cfg(feature = "v2")] -#[allow(clippy::too_many_arguments)] -pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>( - _state: &SessionState, - _operation: &BoxedOperation<'_, F, Req, D>, - payment_data: &mut D, - _validate_result: &operations::ValidateResult, - _merchant_key_store: &domain::MerchantKeyStore, - _customer: &Option<domain::Customer>, - _business_profile: &domain::Profile, -) -> RouterResult<(D, TokenizationAction)> -where - F: Send + Clone, - D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, -{ - // TODO: Implement this function - let payment_data = payment_data.to_owned(); - Ok((payment_data, TokenizationAction::SkipConnectorTokenization)) +#[derive(Clone, Debug)] +pub enum TokenizationAction { + TokenizeInConnector, + SkipConnectorTokenization, } #[cfg(feature = "v1")] diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 2d8488ab6cc..9617910ed41 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -91,6 +91,8 @@ pub use self::{ payment_session_intent::PaymentSessionIntent, }; use super::{helpers, CustomerDetails, OperationSessionGetters, OperationSessionSetters}; +#[cfg(feature = "v2")] +use crate::core::payments; use crate::{ core::errors::{self, CustomResult, RouterResult}, routes::{app::ReqState, SessionState}, @@ -423,6 +425,16 @@ pub trait Domain<F: Clone, R, D>: Send + Sync { Ok(()) } + /// Get connector tokenization action + #[cfg(feature = "v2")] + async fn get_connector_tokenization_action<'a>( + &'a self, + _state: &SessionState, + _payment_data: &D, + ) -> RouterResult<(payments::TokenizationAction)> { + Ok(payments::TokenizationAction::SkipConnectorTokenization) + } + // #[cfg(feature = "v2")] // async fn call_connector<'a, RouterDataReq>( // &'a self, 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 ccbe540dfc5..9720cee1d9a 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -538,6 +538,60 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf .set_connector_in_payment_attempt(Some(connector_data.connector_name.to_string())); Ok(connector_data) } + + async fn get_connector_tokenization_action<'a>( + &'a self, + state: &SessionState, + payment_data: &PaymentConfirmData<F>, + ) -> RouterResult<payments::TokenizationAction> { + let connector = payment_data.payment_attempt.connector.to_owned(); + + let is_connector_mandate_flow = payment_data + .mandate_data + .as_ref() + .and_then(|mandate_details| mandate_details.mandate_reference_id.as_ref()) + .map(|mandate_reference| match mandate_reference { + api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true, + api_models::payments::MandateReferenceId::NetworkMandateId(_) + | api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_) => false, + }) + .unwrap_or(false); + + let tokenization_action = match connector { + Some(_) if is_connector_mandate_flow => { + payments::TokenizationAction::SkipConnectorTokenization + } + Some(connector) => { + let payment_method = payment_data + .payment_attempt + .get_payment_method() + .ok_or_else(|| errors::ApiErrorResponse::InternalServerError) + .attach_printable("Payment method not found")?; + let payment_method_type: Option<common_enums::PaymentMethodType> = + payment_data.payment_attempt.get_payment_method_type(); + + let mandate_flow_enabled = payment_data.payment_intent.setup_future_usage; + + let is_connector_tokenization_enabled = + payments::is_payment_method_tokenization_enabled_for_connector( + state, + &connector, + payment_method, + payment_method_type, + mandate_flow_enabled, + )?; + + if is_connector_tokenization_enabled { + payments::TokenizationAction::TokenizeInConnector + } else { + payments::TokenizationAction::SkipConnectorTokenization + } + } + None => payments::TokenizationAction::SkipConnectorTokenization, + }; + + Ok(tokenization_action) + } } #[async_trait]
2025-09-23T07:41:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This feature add connector-level tokenization to Hyperswitch V2, allowing secure storage of card data as tokens at payment connectors like Braintree. Additionally Tokenization in router is not implemented, because of temp locker mechanism which is still pending. For connector-level tokenization: 1.When a payment comes with raw card data and the connector supports tokenization, send the card details to the connector’s tokenization API. 2. Receive the tokenized payment method ID. 3. Use the token for the subsequent payment call. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- 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 #9501 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <details> <summary>▶ Create and Confirm Request</summary> **Request:** ```bash curl --location 'http://localhost:8080/v2/payments' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_pYmCUDflXtfYghJEbwig' \ --header 'Authorization: api-key=dev_NJmZgHkdmFD5DC5ldyvqUObC7LgVZAkuNSsUCxlcwTYfdMb2zxsvKZQyFJ5AdIwI' \ --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]" }, "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "01", "card_exp_year": "29", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` **Response:** ```json { "id": "12345_pay_0199758923487c2380efbcb7a0480045", "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": "braintree", "created": "2025-09-23T07:45:45.801Z", "modified_at": "2025-09-23T07:45:46.773Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "dHJhbnNhY3Rpb25fcWE0NGtmdHM", "connector_reference_id": null, "merchant_connector_id": "mca_15ue2HSPzmSPtuWvipkZ", "browser_info": null, "error": 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, "merchant_reference_id": null, "raw_connector_response": null, "feature_metadata": null, "metadata": null } ``` </details> --- <details> <summary>▶ Create Intent</summary> **Request:** ``` { "amount_details": { "order_amount": 10000, "currency": "USD" }, "capture_method":"automatic", "authentication_type": "no_three_ds", "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" }, "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" }, "email": "[email protected]" } } ``` **Response:** ```json { "id": "12345_pay_019975899d367c61ae62b88f1edde4e9", "status": "requires_payment_method", "amount_details": { "order_amount": 10000, "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_019975899d487c93a8bf823b41c05b44", "profile_id": "pro_pYmCUDflXtfYghJEbwig", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "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", "origin_zip": null }, "phone": null, "email": "[email protected]" }, "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", "origin_zip": null }, "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": "false", "split_txns_enabled": "skip", "expires_on": "2025-09-23T08:01:17.027Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip", "payment_type": "normal" } ``` </details> --- <details> <summary>▶ Confirm Intent</summary> **Request:** ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01997581b5657212a9e70f003b9d90b4/confirm-intent' \ --header 'x-profile-id: pro_k9nKKsBbyN4y6mOzfNe3' \ --header 'x-client-secret: cs_01997581b57e7683ae1c09b731afd73c' \ --header 'Authorization: api-key=dev_RDL3XpNVl4roIIGE1841URGxogUhALsFsxybasIi5yX62pvgFh4A3SNEWrKGvvBX' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_e02152d7d0c542dc934d95388df8a940' \ --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", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" } }' ``` **Response:** ```json { "id": "12345_pay_019975899d367c61ae62b88f1edde4e9", "status": "succeeded", "amount": { "order_amount": 10000, "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": 10000, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 10000 }, "customer_id": null, "connector": "braintree", "created": "2025-09-23T07:46:17.027Z", "modified_at": "2025-09-23T07:47:00.359Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "dHJhbnNhY3Rpb25fZnhxaDczNXY", "connector_reference_id": null, "merchant_connector_id": "mca_15ue2HSPzmSPtuWvipkZ", "browser_info": null, "error": 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, "merchant_reference_id": null, "raw_connector_response": null, "feature_metadata": null, "metadata": null } ``` </details> <img width="1728" height="428" alt="image" src="https://github.com/user-attachments/assets/84ef20bd-fbbd-43ab-8733-07ec7d693c5b" /> <img width="1727" height="452" alt="image" src="https://github.com/user-attachments/assets/fb66e5f9-95d8-4a1a-bc68-c90809f8b5e0" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ab00b083e963a5d5228af6b061b603a68d7efa17
juspay/hyperswitch
juspay__hyperswitch-9495
Bug: [FEATURE] add parent info based API for fetching permissions for user role add parent info based API for fetching permissions for user role so backend permissions and frontend permissions can remain consistent.
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index 0ab853273e7..b0cc9aa8554 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -36,13 +36,13 @@ pub struct RoleInfoWithGroupsResponse { #[derive(Debug, serde::Serialize)] pub struct RoleInfoWithParents { pub role_id: String, - pub parent_groups: Vec<ParentGroupInfo>, + pub parent_groups: Vec<ParentGroupDescription>, pub role_name: String, pub role_scope: RoleScope, } #[derive(Debug, serde::Serialize)] -pub struct ParentGroupInfo { +pub struct ParentGroupDescription { pub name: ParentGroup, pub description: String, pub scopes: Vec<PermissionScope>, @@ -74,7 +74,7 @@ pub struct RoleInfoResponseWithParentsGroup { pub role_id: String, pub role_name: String, pub entity_type: EntityType, - pub parent_groups: Vec<ParentGroupInfo>, + pub parent_groups: Vec<ParentGroupDescription>, pub role_scope: RoleScope, } @@ -117,3 +117,10 @@ pub enum ListRolesResponse { WithGroups(Vec<RoleInfoResponseNew>), WithParentGroups(Vec<RoleInfoResponseWithParentsGroup>), } + +#[derive(Debug, serde::Serialize)] +pub struct ParentGroupInfo { + pub name: ParentGroup, + pub resources: Vec<Resource>, + pub scopes: Vec<PermissionScope>, +} diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 1b4870f05ea..d6a55ffdbf1 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -90,7 +90,7 @@ pub async fn get_parent_group_info( state: SessionState, user_from_token: auth::UserFromToken, request: role_api::GetParentGroupsInfoQueryParams, -) -> UserResponse<Vec<role_api::ParentGroupInfo>> { +) -> UserResponse<Vec<role_api::ParentGroupDescription>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, @@ -119,17 +119,21 @@ pub async fn get_parent_group_info( ParentGroup::get_descriptions_for_groups(entity_type, PermissionGroup::iter().collect()) .unwrap_or_default() .into_iter() - .map(|(parent_group, description)| role_api::ParentGroupInfo { - name: parent_group.clone(), - description, - scopes: PermissionGroup::iter() - .filter_map(|group| (group.parent() == parent_group).then_some(group.scope())) - // TODO: Remove this hashset conversion when merchant access - // and organization access groups are removed - .collect::<HashSet<_>>() - .into_iter() - .collect(), - }) + .map( + |(parent_group, description)| role_api::ParentGroupDescription { + name: parent_group.clone(), + description, + scopes: PermissionGroup::iter() + .filter_map(|group| { + (group.parent() == parent_group).then_some(group.scope()) + }) + // TODO: Remove this hashset conversion when merchant access + // and organization access groups are removed + .collect::<HashSet<_>>() + .into_iter() + .collect(), + }, + ) .collect::<Vec<_>>(); Ok(ApplicationResponse::Json(parent_groups)) diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index cbd49a14391..e0f266c976a 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -58,6 +58,25 @@ pub async fn get_groups_and_resources_for_role_from_token( })) } +pub async fn get_parent_groups_info_for_role_from_token( + state: SessionState, + user_from_token: UserFromToken, +) -> UserResponse<Vec<role_api::ParentGroupInfo>> { + let role_info = user_from_token.get_role_info_from_db(&state).await?; + + let groups = role_info + .get_permission_groups() + .into_iter() + .collect::<Vec<_>>(); + + let parent_groups = utils::user_role::permission_groups_to_parent_group_info( + &groups, + role_info.get_entity_type(), + ); + + Ok(ApplicationResponse::Json(parent_groups)) +} + pub async fn create_role( state: SessionState, user_from_token: UserFromToken, @@ -248,16 +267,31 @@ pub async fn create_role_v2( .await .to_duplicate_response(UserErrors::RoleNameAlreadyExists)?; - let response_parent_groups = + let parent_group_details = utils::user_role::permission_groups_to_parent_group_info(&role.groups, role.entity_type); + let parent_group_descriptions: Vec<role_api::ParentGroupDescription> = parent_group_details + .into_iter() + .filter_map(|group_details| { + let description = utils::user_role::resources_to_description( + group_details.resources, + role.entity_type, + )?; + Some(role_api::ParentGroupDescription { + name: group_details.name, + description, + scopes: group_details.scopes, + }) + }) + .collect(); + Ok(ApplicationResponse::Json( role_api::RoleInfoResponseWithParentsGroup { role_id: role.role_id, role_name: role.role_name, role_scope: role.scope, entity_type: role.entity_type, - parent_groups: response_parent_groups, + parent_groups: parent_group_descriptions, }, )) } @@ -325,19 +359,21 @@ pub async fn get_parent_info_for_role( role.role_id ))? .into_iter() - .map(|(parent_group, description)| role_api::ParentGroupInfo { - name: parent_group.clone(), - description, - scopes: role_info - .get_permission_groups() - .iter() - .filter_map(|group| (group.parent() == parent_group).then_some(group.scope())) - // TODO: Remove this hashset conversion when merchant access - // and organization access groups are removed - .collect::<HashSet<_>>() - .into_iter() - .collect(), - }) + .map( + |(parent_group, description)| role_api::ParentGroupDescription { + name: parent_group.clone(), + description, + scopes: role_info + .get_permission_groups() + .iter() + .filter_map(|group| (group.parent() == parent_group).then_some(group.scope())) + // TODO: Remove this hashset conversion when merchant access + // and organization access groups are removed + .collect::<HashSet<_>>() + .into_iter() + .collect(), + }, + ) .collect(); Ok(ApplicationResponse::Json(role_api::RoleInfoWithParents { @@ -513,16 +549,33 @@ pub async fn list_roles_with_info( (is_lower_entity && request_filter).then_some({ let permission_groups = role_info.get_permission_groups(); - let parent_groups = utils::user_role::permission_groups_to_parent_group_info( - &permission_groups, - role_info.get_entity_type(), - ); + let parent_group_details = + utils::user_role::permission_groups_to_parent_group_info( + &permission_groups, + role_info.get_entity_type(), + ); + + let parent_group_descriptions: Vec<role_api::ParentGroupDescription> = + parent_group_details + .into_iter() + .filter_map(|group_details| { + let description = utils::user_role::resources_to_description( + group_details.resources, + role_info.get_entity_type(), + )?; + Some(role_api::ParentGroupDescription { + name: group_details.name, + description, + scopes: group_details.scopes, + }) + }) + .collect(); role_api::RoleInfoResponseWithParentsGroup { role_id: role_info.get_role_id().to_string(), role_name: role_info.get_role_name().to_string(), entity_type: role_info.get_entity_type(), - parent_groups, + parent_groups: parent_group_descriptions, role_scope: role_info.get_scope(), } }) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index ef3f8081b9a..f36a0bf4ba3 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2730,51 +2730,54 @@ impl User { } // Role information - route = route.service( - web::scope("/role") - .service( - web::resource("") - .route(web::get().to(user_role::get_role_from_token)) - // TODO: To be deprecated - .route(web::post().to(user_role::create_role)), - ) - .service( - web::resource("/v2") - .route(web::post().to(user_role::create_role_v2)) - .route( - web::get().to(user_role::get_groups_and_resources_for_role_from_token), - ), - ) - // TODO: To be deprecated - .service( - web::resource("/v2/list").route(web::get().to(user_role::list_roles_with_info)), - ) - .service( - web::scope("/list") - .service( - web::resource("").route(web::get().to(user_role::list_roles_with_info)), - ) - .service( - web::resource("/invite").route( - web::get().to(user_role::list_invitable_roles_at_entity_level), + route = + route.service( + web::scope("/role") + .service( + web::resource("") + .route(web::get().to(user_role::get_role_from_token)) + // TODO: To be deprecated + .route(web::post().to(user_role::create_role)), + ) + .service( + web::resource("/v2") + .route(web::post().to(user_role::create_role_v2)) + .route( + web::get() + .to(user_role::get_groups_and_resources_for_role_from_token), ), - ) - .service( - web::resource("/update").route( + ) + .service(web::resource("/v3").route( + web::get().to(user_role::get_parent_groups_info_for_role_from_token), + )) + // TODO: To be deprecated + .service( + web::resource("/v2/list") + .route(web::get().to(user_role::list_roles_with_info)), + ) + .service( + web::scope("/list") + .service( + web::resource("") + .route(web::get().to(user_role::list_roles_with_info)), + ) + .service(web::resource("/invite").route( + web::get().to(user_role::list_invitable_roles_at_entity_level), + )) + .service(web::resource("/update").route( web::get().to(user_role::list_updatable_roles_at_entity_level), - ), - ), - ) - .service( - web::resource("/{role_id}") - .route(web::get().to(user_role::get_role)) - .route(web::put().to(user_role::update_role)), - ) - .service( - web::resource("/{role_id}/v2") - .route(web::get().to(user_role::get_parent_info_for_role)), - ), - ); + )), + ) + .service( + web::resource("/{role_id}") + .route(web::get().to(user_role::get_role)) + .route(web::put().to(user_role::update_role)), + ) + .service( + web::resource("/{role_id}/v2") + .route(web::get().to(user_role::get_parent_info_for_role)), + ), + ); #[cfg(feature = "dummy_connector")] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 0c42909b457..04745ea15b0 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -324,6 +324,7 @@ impl From<Flow> for ApiIdentifier { | Flow::GetRoleV2 | Flow::GetRoleFromToken | Flow::GetRoleFromTokenV2 + | Flow::GetParentGroupsInfoForRoleFromToken | Flow::UpdateUserRole | Flow::GetAuthorizationInfo | Flow::GetRolesInfo diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 91cc92cb3e2..6247761d617 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -74,6 +74,27 @@ pub async fn get_groups_and_resources_for_role_from_token( )) .await } + +pub async fn get_parent_groups_info_for_role_from_token( + state: web::Data<AppState>, + req: HttpRequest, +) -> HttpResponse { + let flow = Flow::GetParentGroupsInfoForRoleFromToken; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user, _, _| async move { + role_core::get_parent_groups_info_for_role_from_token(state, user).await + }, + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + // TODO: To be deprecated pub async fn create_role( state: web::Data<AppState>, diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index 774368b18d6..6a2ce1c8397 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, ops::Not}; use common_enums::{EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource}; use strum::IntoEnumIterator; -use super::permissions::{self, ResourceExt}; +use super::permissions; pub trait PermissionGroupExt { fn scope(&self) -> PermissionScope; @@ -147,15 +147,8 @@ impl ParentGroupExt for ParentGroup { if !groups.iter().any(|group| group.parent() == parent) { return None; } - let filtered_resources: Vec<_> = parent - .resources() - .into_iter() - .filter(|res| res.entities().iter().any(|entity| entity <= &entity_type)) - .collect(); - - if filtered_resources.is_empty() { - return None; - } + let filtered_resources = + permissions::filter_resources_by_entity_type(parent.resources(), entity_type)?; let description = filtered_resources .iter() diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 3860d343b68..b890df41468 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -152,3 +152,15 @@ pub fn get_scope_name(scope: PermissionScope) -> &'static str { PermissionScope::Write => "View and Manage", } } + +pub fn filter_resources_by_entity_type( + resources: Vec<Resource>, + entity_type: EntityType, +) -> Option<Vec<Resource>> { + let filtered: Vec<Resource> = resources + .into_iter() + .filter(|res| res.entities().iter().any(|entity| entity <= &entity_type)) + .collect(); + + (!filtered.is_empty()).then_some(filtered) +} diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 67ed2127eab..bcaea767a22 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -27,7 +27,7 @@ use crate::{ services::authorization::{ self as authz, permission_groups::{ParentGroupExt, PermissionGroupExt}, - roles, + permissions, roles, }, types::domain, }; @@ -570,15 +570,33 @@ pub fn permission_groups_to_parent_group_info( .into_iter() .collect(); - let description = - ParentGroup::get_descriptions_for_groups(entity_type, permission_groups.to_vec()) - .and_then(|descriptions| descriptions.get(&name).cloned())?; + let filtered_resources = + permissions::filter_resources_by_entity_type(name.resources(), entity_type)?; Some(role_api::ParentGroupInfo { name, - description, + resources: filtered_resources, scopes: unique_scopes, }) }) .collect() } + +pub fn resources_to_description( + resources: Vec<common_enums::Resource>, + entity_type: EntityType, +) -> Option<String> { + if resources.is_empty() { + return None; + } + + let filtered_resources = permissions::filter_resources_by_entity_type(resources, entity_type)?; + + let description = filtered_resources + .iter() + .map(|res| permissions::get_resource_name(*res, entity_type)) + .collect::<Option<Vec<_>>>()? + .join(", "); + + Some(description) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ae5f34fd78f..33db02fbf0c 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -417,6 +417,8 @@ pub enum Flow { GetRoleFromToken, /// Get resources and groups for role from token GetRoleFromTokenV2, + /// Get parent groups info for role from token + GetParentGroupsInfoForRoleFromToken, /// Update user role UpdateUserRole, /// Create merchant account for user in a org
2025-09-22T11:49:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Adds a new API endpoint GET /user/role/v3 that returns user role permissions using parent group information with resource details. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context This PR adds a new API endpoint that provides structured parent group info with resources and scopes, enabling the frontend to implement proper resource + scope based permission checks. ## How did you test it? ``` curl --location 'http://localhost:9000/api/user/role/v3' \ --header 'Cookie: ******* ``` Response: ``` [ { "name": "ReconReports", "resources": [ "recon_token", "recon_and_settlement_analytics", "recon_reports", "account" ], "scopes": [ "write", "read" ] }, { "name": "Analytics", "resources": [ "analytics", "report", "account" ], "scopes": [ "read" ] }, { "name": "Theme", "resources": [ "theme" ], "scopes": [ "read", "write" ] }, { "name": "Operations", "resources": [ "payment", "refund", "mandate", "dispute", "customer", "payout", "report", "account" ], "scopes": [ "write", "read" ] }, { "name": "Connectors", "resources": [ "connector", "account" ], "scopes": [ "write", "read" ] }, { "name": "Users", "resources": [ "user", "account" ], "scopes": [ "read", "write" ] }, { "name": "Workflows", "resources": [ "routing", "three_ds_decision_manager", "surcharge_decision_manager", "account", "revenue_recovery" ], "scopes": [ "read", "write" ] }, { "name": "ReconOps", "resources": [ "recon_token", "recon_files", "recon_upload", "run_recon", "recon_config", "recon_and_settlement_analytics", "recon_reports", "account" ], "scopes": [ "write", "read" ] }, { "name": "Account", "resources": [ "account", "api_key", "webhook_event" ], "scopes": [ "write", "read" ] } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
juspay/hyperswitch
juspay__hyperswitch-9494
Bug: [FEATURE] add referer field to browser_info add referer field to browser_info
diff --git a/Cargo.lock b/Cargo.lock index 2304b8ab839..0e955b9f8d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3553,14 +3553,14 @@ dependencies = [ [[package]] name = "grpc-api-types" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=142cb5a23d302e5d39c4da8d280edababe0691fe#142cb5a23d302e5d39c4da8d280edababe0691fe" +source = "git+https://github.com/juspay/connector-service?rev=f719688943adf7bc17bb93dcb43f27485c17a96e#f719688943adf7bc17bb93dcb43f27485c17a96e" dependencies = [ "axum 0.8.4", "error-stack 0.5.0", "g2h", "heck 0.5.0", "http 1.3.1", - "masking 0.1.0 (git+https://github.com/juspay/hyperswitch?tag=v1.116.0)", + "masking 0.1.0 (git+https://github.com/juspay/hyperswitch?tag=2025.09.17.0)", "prost", "prost-build", "prost-types", @@ -4865,7 +4865,7 @@ dependencies = [ [[package]] name = "masking" version = "0.1.0" -source = "git+https://github.com/juspay/hyperswitch?tag=v1.116.0#672d749e20bec7800613878e36a0ab3885177326" +source = "git+https://github.com/juspay/hyperswitch?tag=2025.09.17.0#15406557c11041bab6358f2b4b916d7333fc0a0f" dependencies = [ "bytes 1.10.1", "diesel", @@ -6988,7 +6988,7 @@ dependencies = [ [[package]] name = "rust-grpc-client" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=142cb5a23d302e5d39c4da8d280edababe0691fe#142cb5a23d302e5d39c4da8d280edababe0691fe" +source = "git+https://github.com/juspay/connector-service?rev=f719688943adf7bc17bb93dcb43f27485c17a96e#f719688943adf7bc17bb93dcb43f27485c17a96e" dependencies = [ "grpc-api-types", ] @@ -9395,11 +9395,11 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "ucs_cards" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=142cb5a23d302e5d39c4da8d280edababe0691fe#142cb5a23d302e5d39c4da8d280edababe0691fe" +source = "git+https://github.com/juspay/connector-service?rev=f719688943adf7bc17bb93dcb43f27485c17a96e#f719688943adf7bc17bb93dcb43f27485c17a96e" dependencies = [ "bytes 1.10.1", "error-stack 0.4.1", - "masking 0.1.0 (git+https://github.com/juspay/hyperswitch?tag=v1.116.0)", + "masking 0.1.0 (git+https://github.com/juspay/hyperswitch?tag=2025.09.17.0)", "prost", "regex", "serde", @@ -9411,7 +9411,7 @@ dependencies = [ [[package]] name = "ucs_common_enums" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=142cb5a23d302e5d39c4da8d280edababe0691fe#142cb5a23d302e5d39c4da8d280edababe0691fe" +source = "git+https://github.com/juspay/connector-service?rev=f719688943adf7bc17bb93dcb43f27485c17a96e#f719688943adf7bc17bb93dcb43f27485c17a96e" dependencies = [ "serde", "strum 0.26.3", @@ -9422,7 +9422,7 @@ dependencies = [ [[package]] name = "ucs_common_utils" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=142cb5a23d302e5d39c4da8d280edababe0691fe#142cb5a23d302e5d39c4da8d280edababe0691fe" +source = "git+https://github.com/juspay/connector-service?rev=f719688943adf7bc17bb93dcb43f27485c17a96e#f719688943adf7bc17bb93dcb43f27485c17a96e" dependencies = [ "anyhow", "blake3", @@ -9431,7 +9431,7 @@ dependencies = [ "error-stack 0.4.1", "hex", "http 1.3.1", - "masking 0.1.0 (git+https://github.com/juspay/hyperswitch?tag=v1.116.0)", + "masking 0.1.0 (git+https://github.com/juspay/hyperswitch?tag=2025.09.17.0)", "md5", "nanoid", "once_cell", diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index cb7f61ca7a6..70109c59722 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1232,6 +1232,9 @@ pub struct BrowserInformation { /// Accept-language of the browser pub accept_language: Option<String>, + + /// Identifier of the source that initiated the request. + pub referer: Option<String>, } #[cfg(feature = "v2")] diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index eb9fcd61d92..288b9d91414 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -68,7 +68,7 @@ reqwest = { version = "0.11.27", features = ["rustls-tls"] } http = "0.2.12" url = { version = "2.5.4", features = ["serde"] } quick-xml = { version = "0.31.0", features = ["serialize"] } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "142cb5a23d302e5d39c4da8d280edababe0691fe", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "f719688943adf7bc17bb93dcb43f27485c17a96e", package = "rust-grpc-client" } # First party crates diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs index d75fabe1c63..3fda5a2460d 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs @@ -529,6 +529,7 @@ impl TryFrom<&TrustpayRouterData<&PaymentsAuthorizeRouterData>> for TrustpayPaym os_version: None, device_model: None, accept_language: Some(browser_info.accept_language.unwrap_or("en".to_string())), + referer: None, }; let params = get_mandatory_fields(item.router_data)?; let amount = item.amount.to_owned(); diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 3753b0a0d6a..3f9d4f333c2 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -906,6 +906,7 @@ pub struct BrowserInformation { pub os_version: Option<String>, pub device_model: Option<String>, pub accept_language: Option<String>, + pub referer: Option<String>, } #[cfg(feature = "v2")] @@ -926,6 +927,7 @@ impl From<common_utils::types::BrowserInformation> for BrowserInformation { os_version: value.os_version, device_model: value.device_model, accept_language: value.accept_language, + referer: value.referer, } } } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 2190ebae52d..9c52f1d709b 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -89,8 +89,8 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "mult ring = "0.17.14" rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] } rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "142cb5a23d302e5d39c4da8d280edababe0691fe", package = "rust-grpc-client" } -unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", rev = "142cb5a23d302e5d39c4da8d280edababe0691fe", package = "ucs_cards" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "f719688943adf7bc17bb93dcb43f27485c17a96e", package = "rust-grpc-client" } +unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", rev = "f719688943adf7bc17bb93dcb43f27485c17a96e", package = "ucs_cards" } rustc-hash = "1.1.0" rustls = "0.22" rustls-pemfile = "2" diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index b7dc46788c5..f783c09a6c8 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -76,6 +76,9 @@ impl ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>> Ok(Self { transaction_id: connector_transaction_id.or(encoded_data), request_ref_id: connector_ref_id, + access_token: None, + capture_method: None, + handle_response: None, }) } } @@ -507,6 +510,7 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon browser_info, test_mode: None, payment_method_type: None, + access_token: None, }) } } @@ -1016,6 +1020,7 @@ impl ForeignTryFrom<hyperswitch_domain_models::router_request_types::BrowserInfo device_model: browser_info.device_model, accept_language: browser_info.accept_language, time_zone_offset_minutes: browser_info.time_zone, + referer: browser_info.referer, }) } } @@ -1281,6 +1286,7 @@ pub fn build_webhook_transform_request( }), request_details: Some(request_details_grpc), webhook_secrets, + access_token: None, }) } diff --git a/crates/router/src/routes/payments/helpers.rs b/crates/router/src/routes/payments/helpers.rs index 39a836a8385..1185b20d17d 100644 --- a/crates/router/src/routes/payments/helpers.rs +++ b/crates/router/src/routes/payments/helpers.rs @@ -36,6 +36,7 @@ pub fn populate_browser_info( os_version: None, device_model: None, accept_language: None, + referer: None, }); let ip_address = req diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 0fd012e9f7a..bc3f41a9f77 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -164,6 +164,9 @@ where Some(unified_connector_service_client::payments::webhook_response_content::Content::DisputesResponse(_)) => { Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains dispute response but payment processing was expected".to_string().into())).into()) }, + Some(unified_connector_service_client::payments::webhook_response_content::Content::IncompleteTransformation(_)) => { + Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains incomplete transformation but payment processing was expected".to_string().into())).into()) + }, None => { Err(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("UCS webhook content missing payments_response") diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs index a5eb08c67e6..bb635996ad4 100644 --- a/crates/router/tests/connectors/trustpay.rs +++ b/crates/router/tests/connectors/trustpay.rs @@ -53,6 +53,7 @@ fn get_default_browser_info() -> BrowserInformation { os_version: None, device_model: None, accept_language: Some("en".to_string()), + referer: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 9394752fb90..d8f5f1a3a3b 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -1048,6 +1048,7 @@ impl Default for BrowserInfoType { os_type: Some("IOS or ANDROID".to_string()), os_version: Some("IOS 14.5".to_string()), accept_language: Some("en".to_string()), + referer: None, }; Self(data) }
2025-09-22T10:12:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds a referer field to the BrowserInformation struct to capture the HTTP Referer header value from client requests. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Enable UCS ``` curl --location 'http://localhost:8080/v2/configs/' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'x-tenant-id: public' \ --header 'Content-Type: application/json' \ --data '{ "key": "ucs_rollout_config_cloth_seller_Zoo9KadtslxR8ICC7dB6_razorpay_upi_Authorize", "value": "1.0" }' ``` Create payment ``` curl --location 'http://localhost:8080/v2/payments' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_zjXchnTKtjXfUfQ9FJEL' \ --header 'X-Merchant-Id: cloth_seller_Zoo9KadtslxR8ICC7dB6' \ --header 'x-tenant-id: public' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "INR" }, "merchant_connector_details": { "connector_name": "razorpay", "merchant_connector_creds": { "auth_type": "BodyKey", "api_key": "_", "key1": "_" } }, "return_url": "https://api-ns2.juspay.in/v2/pay/response/irctc", "merchant_reference_id": "razorpayirctc1758535732", "capture_method":"automatic", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "success@razorpay" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" } }, "browser_info": { "user_agent": "Dalvik/2.1.0", "referer": "abcd.com", "ip_address": "157.51.3.204" }, "payment_method_subtype": "upi_collect", "payment_method_type": "upi", "return_raw_connector_response": true }' ``` Verify UCS call to connector <img width="1286" height="196" alt="image" src="https://github.com/user-attachments/assets/97c7a7ad-7a6d-4a89-8b99-ba3dc52c2eff" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
juspay/hyperswitch
juspay__hyperswitch-9489
Bug: Add invoice_id type and autogeneration util
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index dc8f6e333a4..b1f1883257d 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -86,6 +86,7 @@ pub enum ApiEventsType { }, Routing, Subscription, + Invoice, ResourceListAPI, #[cfg(feature = "v1")] PaymentRedirectionResponse { diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 237ca661c10..d1ab0106688 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -7,6 +7,7 @@ mod client_secret; mod customer; #[cfg(feature = "v2")] mod global_id; +mod invoice; mod merchant; mod merchant_connector_account; mod organization; @@ -47,6 +48,7 @@ pub use self::{ authentication::AuthenticationId, client_secret::ClientSecretId, customer::CustomerId, + invoice::InvoiceId, merchant::MerchantId, merchant_connector_account::MerchantConnectorAccountId, organization::OrganizationId, diff --git a/crates/common_utils/src/id_type/invoice.rs b/crates/common_utils/src/id_type/invoice.rs new file mode 100644 index 00000000000..9cf0289e2ee --- /dev/null +++ b/crates/common_utils/src/id_type/invoice.rs @@ -0,0 +1,21 @@ +crate::id_type!( + InvoiceId, + " A type for invoice_id that can be used for invoice ids" +); + +crate::impl_id_type_methods!(InvoiceId, "invoice_id"); + +// This is to display the `InvoiceId` as InvoiceId(subs) +crate::impl_debug_id_type!(InvoiceId); +crate::impl_try_from_cow_str_id_type!(InvoiceId, "invoice_id"); + +crate::impl_generate_id_id_type!(InvoiceId, "invoice"); +crate::impl_serializable_secret_id_type!(InvoiceId); +crate::impl_queryable_id_type!(InvoiceId); +crate::impl_to_sql_from_sql_id_type!(InvoiceId); + +impl crate::events::ApiEventMetric for InvoiceId { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::Invoice) + } +} diff --git a/crates/diesel_models/src/invoice.rs b/crates/diesel_models/src/invoice.rs index 24534629307..57024d0730a 100644 --- a/crates/diesel_models/src/invoice.rs +++ b/crates/diesel_models/src/invoice.rs @@ -1,5 +1,5 @@ use common_enums::connector_enums::{Connector, InvoiceStatus}; -use common_utils::{pii::SecretSerdeValue, types::MinorUnit}; +use common_utils::{id_type::GenerateId, pii::SecretSerdeValue, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; @@ -8,8 +8,8 @@ use crate::schema::invoice; #[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = invoice, check_for_backend(diesel::pg::Pg))] pub struct InvoiceNew { - pub id: String, - pub subscription_id: String, + pub id: common_utils::id_type::InvoiceId, + pub subscription_id: common_utils::id_type::SubscriptionId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, @@ -34,8 +34,8 @@ pub struct InvoiceNew { check_for_backend(diesel::pg::Pg) )] pub struct Invoice { - id: String, - subscription_id: String, + id: common_utils::id_type::InvoiceId, + subscription_id: common_utils::id_type::SubscriptionId, merchant_id: common_utils::id_type::MerchantId, profile_id: common_utils::id_type::ProfileId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, @@ -62,8 +62,7 @@ pub struct InvoiceUpdate { impl InvoiceNew { #[allow(clippy::too_many_arguments)] pub fn new( - id: String, - subscription_id: String, + subscription_id: common_utils::id_type::SubscriptionId, merchant_id: common_utils::id_type::MerchantId, profile_id: common_utils::id_type::ProfileId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, @@ -76,6 +75,7 @@ impl InvoiceNew { provider_name: Connector, metadata: Option<SecretSerdeValue>, ) -> Self { + let id = common_utils::id_type::InvoiceId::generate(); let now = common_utils::date_time::now(); Self { id,
2025-09-22T12:01:36Z
This pull request introduces a new strongly-typed `InvoiceId` identifier and integrates it throughout the codebase to improve type safety and consistency for invoice-related operations. The changes affect both the common utilities and the invoice models, updating struct fields and constructors to use the new type instead of raw strings. **Invoice ID type integration:** * Added a new `InvoiceId` type in `common_utils::id_type` and made it available for use throughout the codebase. [[1]](diffhunk://#diff-d949a6c528436f8ab1a851147e7467d525cba63b395b253d1dec17101a971fa1R10) [[2]](diffhunk://#diff-d949a6c528436f8ab1a851147e7467d525cba63b395b253d1dec17101a971fa1R51) * Updated the `InvoiceNew` and `Invoice` structs in `crates/diesel_models/src/invoice.rs` to use `InvoiceId` and `SubscriptionId` types for their respective fields, replacing previous usage of `String`. [[1]](diffhunk://#diff-cc8ce5ad039d65f1b8644286fe6abb6e8fae401fdb8e5f43f3984efdf2803696L11-R12) [[2]](diffhunk://#diff-cc8ce5ad039d65f1b8644286fe6abb6e8fae401fdb8e5f43f3984efdf2803696L37-R38) * Modified the `InvoiceNew::new` constructor to automatically generate an `InvoiceId` using the new type, removing the need to pass an ID as a string argument. [[1]](diffhunk://#diff-cc8ce5ad039d65f1b8644286fe6abb6e8fae401fdb8e5f43f3984efdf2803696L65-R65) [[2]](diffhunk://#diff-cc8ce5ad039d65f1b8644286fe6abb6e8fae401fdb8e5f43f3984efdf2803696R78) **Event type extension:** * Added a new `Invoice` variant to the `ApiEventsType` enum to support invoice-related events. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This can't be tested as it adds id type for invoice for which there is no external facing api. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
85da1b2bc80d4befd392cf7a9d2060d1e2f5cbe9
juspay/hyperswitch
juspay__hyperswitch-9498
Bug: [REFACTOR]: [PAYSAFE] populate error code and message for 200 populate error code and message for 200
diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index 94d31a73787..7a6e361ea76 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -122,14 +122,14 @@ pub struct CoBadgedCardNetworks(pub Vec<CoBadgedCardNetworksInfo>); impl CoBadgedCardNetworks { pub fn get_card_networks(&self) -> Vec<common_enums::CardNetwork> { - self.0.iter().map(|info| info.network.clone()).collect() + self.0.iter().map(|info| info.network).collect() } pub fn get_signature_network(&self) -> Option<common_enums::CardNetwork> { self.0 .iter() .find(|info| info.network.is_signature_network()) - .map(|info| info.network.clone()) + .map(|info| info.network) } } diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 75c5f27df57..ae6555ad94c 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -408,7 +408,7 @@ impl PaymentMethodCreate { card_holder_name: payment_method_migrate_card.card_holder_name.clone(), nick_name: payment_method_migrate_card.nick_name.clone(), card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), - card_network: payment_method_migrate_card.card_network.clone(), + card_network: payment_method_migrate_card.card_network, card_issuer: payment_method_migrate_card.card_issuer.clone(), card_type: payment_method_migrate_card.card_type.clone(), }); diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 8c8052b14d0..c6f4b2db738 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2251,10 +2251,7 @@ impl Card { .card_issuer .clone() .or(additional_card_info.card_issuer), - card_network: self - .card_network - .clone() - .or(additional_card_info.card_network.clone()), + card_network: self.card_network.or(additional_card_info.card_network), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country diff --git a/crates/api_models/src/profile_acquirer.rs b/crates/api_models/src/profile_acquirer.rs index 9689be7d995..5c6a3b3b333 100644 --- a/crates/api_models/src/profile_acquirer.rs +++ b/crates/api_models/src/profile_acquirer.rs @@ -76,7 +76,7 @@ impl profile_id: profile_id.clone(), acquirer_assigned_merchant_id: acquirer_config.acquirer_assigned_merchant_id.clone(), merchant_name: acquirer_config.merchant_name.clone(), - network: acquirer_config.network.clone(), + network: acquirer_config.network, acquirer_bin: acquirer_config.acquirer_bin.clone(), acquirer_ica: acquirer_config.acquirer_ica.clone(), acquirer_fraud_rate: acquirer_config.acquirer_fraud_rate, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 581858a85de..5b0d1d3d9cc 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2504,6 +2504,7 @@ pub enum MandateStatus { /// Indicates the card network. #[derive( Clone, + Copy, Debug, Eq, Hash, diff --git a/crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs b/crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs index 877de2bc77b..aa6b3c4908c 100644 --- a/crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs +++ b/crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs @@ -79,10 +79,9 @@ impl RecoveryDeciderClientConfig { .base_url .parse::<tonic::transport::Uri>() .map_err(Report::from) - .change_context(RecoveryDeciderError::ConfigError(format!( - "Invalid URI: {}", - self.base_url - )))?; + .change_context_lazy(|| { + RecoveryDeciderError::ConfigError(format!("Invalid URI: {}", self.base_url)) + })?; let service_client = DeciderClient::with_origin(hyper_client, uri); diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 200f6b400c3..679de5cdd1b 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -2222,7 +2222,7 @@ impl TryFrom<(&Card, Option<Secret<String>>)> for AdyenPaymentMethod<'_> { expiry_year: card.get_expiry_year_4_digit(), cvc: Some(card.card_cvc.clone()), holder_name: card_holder_name, - brand: card.card_network.clone().and_then(get_adyen_card_network), + brand: card.card_network.and_then(get_adyen_card_network), network_payment_reference: None, }; Ok(AdyenPaymentMethod::AdyenCard(Box::new(adyen_card))) @@ -2386,7 +2386,7 @@ impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMethod .billing_address .name .or(item.get_optional_billing_full_name()), - brand: Some(paze_decrypted_data.payment_card_network.clone()) + brand: Some(paze_decrypted_data.payment_card_network) .and_then(get_adyen_card_network), network_payment_reference: None, }; @@ -2886,7 +2886,6 @@ impl ) => { let brand = match card_details_for_network_transaction_id .card_network - .clone() .and_then(get_adyen_card_network) { Some(card_network) => card_network, diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs index 30454d3aaee..2b146d1e262 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs @@ -2579,7 +2579,7 @@ impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentI fn try_from( ccard: &hyperswitch_domain_models::payment_method_data::Card, ) -> Result<Self, Self::Error> { - let card_type = match ccard.card_network.clone().and_then(get_boa_card_type) { + let card_type = match ccard.card_network.and_then(get_boa_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs index b14d6c7409b..4970f4e7b3c 100644 --- a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs @@ -2874,11 +2874,7 @@ impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentI fn try_from( ccard: &hyperswitch_domain_models::payment_method_data::Card, ) -> Result<Self, Self::Error> { - let card_type = match ccard - .card_network - .clone() - .and_then(get_barclaycard_card_type) - { + let card_type = match ccard.card_network.and_then(get_barclaycard_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index cbd97ccf845..f393095b3a4 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -171,11 +171,7 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { let (payment_information, solution) = match item.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { - let card_type = match ccard - .card_network - .clone() - .and_then(get_cybersource_card_type) - { + let card_type = match ccard.card_network.and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; @@ -1404,9 +1400,9 @@ impl }) .ok(); - let raw_card_type = ccard.card_network.clone().or(additional_card_network); + let raw_card_type = ccard.card_network.or(additional_card_network); - let card_type = match raw_card_type.clone().and_then(get_cybersource_card_type) { + let card_type = match raw_card_type.and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; @@ -1891,11 +1887,7 @@ impl let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); - let card_type = match ccard - .card_network - .clone() - .and_then(get_cybersource_card_type) - { + let card_type = match ccard.card_network.and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; @@ -2175,10 +2167,11 @@ impl })?, }, })); + let card_network = google_pay_data.info.card_network.clone(); let processing_information = ProcessingInformation::try_from(( item, Some(PaymentSolution::GooglePay), - Some(google_pay_data.info.card_network.clone()), + Some(card_network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item @@ -2188,11 +2181,10 @@ impl .clone() .map(convert_metadata_to_merchant_defined_info); - let ucaf_collection_indicator = - match google_pay_data.info.card_network.to_lowercase().as_str() { - "mastercard" => Some("2".to_string()), - _ => None, - }; + let ucaf_collection_indicator = match card_network.to_lowercase().as_str() { + "mastercard" => Some("2".to_string()), + _ => None, + }; Ok(Self { processing_information, @@ -2638,11 +2630,7 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { - let card_type = match ccard - .card_network - .clone() - .and_then(get_cybersource_card_type) - { + let card_type = match ccard.card_network.and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; @@ -3401,11 +3389,7 @@ impl TryFrom<&CybersourceRouterData<&PaymentsPreProcessingRouterData>> )?; let payment_information = match payment_method_data { PaymentMethodData::Card(ccard) => { - let card_type = match ccard - .card_network - .clone() - .and_then(get_cybersource_card_type) - { + let card_type = match ccard.card_network.and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs index e8f1e8ffc64..ce231f7e2ac 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs @@ -393,7 +393,6 @@ impl TryFrom<&NetceteraRouterData<&PreAuthNRouterData>> for NetceteraPreAuthenti .request .card .card_network - .clone() .map(|card_network| { is_cobadged_card().map(|is_cobadged_card| { is_cobadged_card @@ -516,7 +515,6 @@ impl TryFrom<&NetceteraRouterData<&ConnectorAuthenticationRouterData>> acct_number: card.card_number, scheme_id: card .card_network - .clone() .and_then(|card_network| { is_cobadged_card.then_some(netcetera_types::SchemeId::try_from(card_network)) }) diff --git a/crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs index 61a4d8e157a..ecaed0d31ff 100644 --- a/crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs +++ b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs @@ -269,7 +269,7 @@ impl TryFrom<&RiskifiedRouterData<&FrmCheckoutRouterData>> for RiskifiedPayments .clone() .map(|last_four| format!("XXXX-XXXX-XXXX-{last_four}")) .map(Secret::new), - credit_card_company: card_info.card_network.clone(), + credit_card_company: card_info.card_network, }), Some(_) | None => None, }, diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index c7b728db21f..930cc3f23af 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -1567,7 +1567,6 @@ impl payment_method_auth_type: Some(payment_method_auth_type), payment_method_data_card_preferred_network: card .card_network - .clone() .and_then(get_stripe_card_network), request_incremental_authorization: if request_incremental_authorization { Some(StripeRequestIncrementalAuthorization::IfAvailable) @@ -1930,7 +1929,6 @@ impl TryFrom<(&PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentRequest payment_method_data_card_preferred_network: card_details_for_network_transaction_id .card_network - .clone() .and_then(get_stripe_card_network), request_incremental_authorization: None, request_extended_authorization: None, diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs index 98761cb8cc9..b1350a708b1 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs @@ -3900,7 +3900,7 @@ fn get_vantiv_card_data( > { match payment_method_data { PaymentMethodData::Card(card) => { - let card_type = match card.card_network.clone() { + let card_type = match card.card_network { Some(card_type) => WorldpayvativCardType::try_from(card_type)?, None => WorldpayvativCardType::try_from(&card.get_card_issuer()?)?, }; @@ -3918,7 +3918,7 @@ fn get_vantiv_card_data( )) } PaymentMethodData::CardDetailsForNetworkTransactionId(card_data) => { - let card_type = match card_data.card_network.clone() { + let card_type = match card_data.card_network { Some(card_type) => WorldpayvativCardType::try_from(card_type)?, None => WorldpayvativCardType::try_from(&card_data.get_card_issuer()?)?, }; diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 85051693105..bfbbe05cae1 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -2034,7 +2034,6 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { match &self.additional_payment_method_data { Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(card_data .card_network - .clone() .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "card_network", })?), diff --git a/crates/hyperswitch_domain_models/src/bulk_tokenization.rs b/crates/hyperswitch_domain_models/src/bulk_tokenization.rs index ccefd3e34e1..2f0dfe2de52 100644 --- a/crates/hyperswitch_domain_models/src/bulk_tokenization.rs +++ b/crates/hyperswitch_domain_models/src/bulk_tokenization.rs @@ -201,7 +201,7 @@ impl ForeignFrom<&TokenizeCardRequest> for payment_methods_api::MigrateCardDetai card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), - card_network: card.card_network.clone(), + card_network: card.card_network, card_issuer: card.card_issuer.clone(), card_type: card .card_type diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 59202837dc2..fdda9e865a3 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -2391,7 +2391,7 @@ impl CardDetailsPaymentMethod { card_number: None, card_holder_name: self.card_holder_name.clone(), card_issuer: self.card_issuer.clone(), - card_network: self.card_network.clone(), + card_network: self.card_network, card_type: self.card_type.clone(), issuer_country: self.clone().get_issuer_country_alpha2(), last4_digits: self.last4_digits, @@ -2536,7 +2536,7 @@ impl From<Card> for payment_methods::CardDetail { card_holder_name: None, nick_name: None, card_issuing_country: None, - card_network: card_data.card_network.clone(), + card_network: card_data.card_network, card_issuer: None, card_type: None, } @@ -2553,7 +2553,7 @@ impl From<NetworkTokenData> for payment_methods::CardDetail { card_holder_name: None, nick_name: None, card_issuing_country: None, - card_network: network_token_data.card_network.clone(), + card_network: network_token_data.card_network, card_issuer: None, card_type: None, } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 370bafd2a90..d1b1a155ec0 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -1083,7 +1083,7 @@ where let billing_connector_payment_method_details = Some( diesel_models::types::BillingConnectorPaymentMethodDetails::Card( diesel_models::types::BillingConnectorAdditionalCardInfo { - card_network: self.revenue_recovery_data.card_network.clone(), + card_network: self.revenue_recovery_data.card_network, card_issuer: self.revenue_recovery_data.card_issuer.clone(), }, ), diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index b33fdde3099..eddde1e8709 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -852,10 +852,10 @@ fn compile_config_graph( )); } (kgraph_types::PaymentMethodFilterKey::CardNetwork(cn), filter) => { - let dir_val_cn = cn.clone().into_dir_value()?; + let dir_val_cn = cn.into_dir_value()?; pmt_enabled.push(dir_val_cn); let cn_node = builder.make_value_node( - cn.clone().into_dir_value().map(Into::into)?, + cn.into_dir_value().map(Into::into)?, Some("CardNetwork"), None::<()>, ); diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs index 494e1987e21..d400e79f407 100644 --- a/crates/payment_methods/src/core/migration/payment_methods.rs +++ b/crates/payment_methods/src/core/migration/payment_methods.rs @@ -60,7 +60,7 @@ pub async fn migrate_payment_method( req.card = Some(api_models::payment_methods::MigrateCardDetail { card_issuing_country: card_bin_details.issuer_country.clone(), - card_network: card_bin_details.card_network.clone(), + card_network: card_bin_details.card_network, card_issuer: card_bin_details.card_issuer.clone(), card_type: card_bin_details.card_type.clone(), ..card_details.clone() @@ -72,7 +72,7 @@ pub async fn migrate_payment_method( merchant_context.get_merchant_key_store(), connector_mandate_details, merchant_id, - card_bin_details.card_network.clone(), + card_bin_details.card_network, ) .await?; }; @@ -248,8 +248,7 @@ impl Ok(Self { scheme: card_details .card_network - .clone() - .or(card_bin_info.card_network.clone()) + .or(card_bin_info.card_network) .map(|card_network| card_network.to_string()), last4_digits: Some(last4_digits.clone()), issuer_country: card_details @@ -268,10 +267,7 @@ impl .card_issuer .clone() .or(card_bin_info.card_issuer), - card_network: card_details - .card_network - .clone() - .or(card_bin_info.card_network), + card_network: card_details.card_network.or(card_bin_info.card_network), card_type: card_details.card_type.clone().or(card_bin_info.card_type), saved_to_locker: false, }) @@ -279,7 +275,6 @@ impl Ok(Self { scheme: card_details .card_network - .clone() .map(|card_network| card_network.to_string()), last4_digits: Some(last4_digits.clone()), issuer_country: card_details.card_issuing_country.clone(), @@ -292,7 +287,7 @@ impl nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details.card_issuer.clone(), - card_network: card_details.card_network.clone(), + card_network: card_details.card_network, card_type: card_details.card_type.clone(), saved_to_locker: false, }) @@ -347,10 +342,7 @@ impl .card_issuer .clone() .or(card_bin_info.card_issuer), - card_network: card_details - .card_network - .clone() - .or(card_bin_info.card_network), + card_network: card_details.card_network.or(card_bin_info.card_network), card_type: card_details.card_type.clone().or(card_bin_info.card_type), saved_to_locker: false, }) @@ -372,7 +364,7 @@ impl nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details.card_issuer.clone(), - card_network: card_details.card_network.clone(), + card_network: card_details.card_network, card_type: card_details.card_type.clone(), saved_to_locker: false, }) diff --git a/crates/payment_methods/src/helpers.rs b/crates/payment_methods/src/helpers.rs index b3450c4aed0..a3ade983ace 100644 --- a/crates/payment_methods/src/helpers.rs +++ b/crates/payment_methods/src/helpers.rs @@ -19,7 +19,7 @@ pub async fn populate_bin_details_for_payment_method_create( { api::CardDetail { card_issuer: card_details.card_issuer.to_owned(), - card_network: card_details.card_network.clone(), + card_network: card_details.card_network, card_type: card_details.card_type.to_owned(), card_issuing_country: card_details.card_issuing_country.to_owned(), card_exp_month: card_details.card_exp_month.clone(), @@ -41,7 +41,7 @@ pub async fn populate_bin_details_for_payment_method_create( .flatten() .map(|card_info| api::CardDetail { card_issuer: card_info.card_issuer, - card_network: card_info.card_network.clone(), + card_network: card_info.card_network, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, card_exp_month: card_details.card_exp_month.clone(), diff --git a/crates/router/src/core/cards_info.rs b/crates/router/src/core/cards_info.rs index 9b9982df654..3e993709abe 100644 --- a/crates/router/src/core/cards_info.rs +++ b/crates/router/src/core/cards_info.rs @@ -212,7 +212,7 @@ impl<'a> CardInfoMigrateExecutor<'a> { self.record.card_iin.clone(), card_info_models::UpdateCardInfo { card_issuer: self.record.card_issuer.clone(), - card_network: self.record.card_network.clone(), + card_network: self.record.card_network, card_type: self.record.card_type.clone(), card_subtype: self.record.card_subtype.clone(), card_issuing_country: self.record.card_issuing_country.clone(), diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rs index a09fc2ab1f5..1ce8ca3d39e 100644 --- a/crates/router/src/core/debit_routing.rs +++ b/crates/router/src/core/debit_routing.rs @@ -734,7 +734,7 @@ fn find_matching_networks( api::ConnectorRoutingData { connector_data: connector_routing_data.connector_data.clone(), - network: Some(network.clone()), + network: Some(*network), action_type: connector_routing_data.action_type.clone(), } }) diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 06622842281..2279188d789 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -724,7 +724,7 @@ pub(crate) fn get_payment_method_create_request( .transpose() .ok() .flatten(), - card_network: card.card_network.clone(), + card_network: card.card_network, card_issuer: card.card_issuer.clone(), card_type: card .card_type @@ -771,7 +771,7 @@ pub(crate) async fn get_payment_method_create_request( Some(payment_method) => match pm_data { domain::PaymentMethodData::Card(card) => { let card_network = get_card_network_with_us_local_debit_network_override( - card.card_network.clone(), + card.card_network, card.co_badged_card_data.as_ref(), ); @@ -782,7 +782,7 @@ pub(crate) async fn get_payment_method_create_request( card_holder_name: billing_name, nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), - card_network: card_network.clone(), + card_network, card_issuer: card.card_issuer.clone(), card_type: card.card_type.clone(), }; @@ -1312,7 +1312,7 @@ pub async fn populate_bin_details_for_payment_method( .ok() .flatten() }), - card_network: card_info.as_ref().and_then(|val| val.card_network.clone()), + card_network: card_info.as_ref().and_then(|val| val.card_network), card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()), card_type: card_info.as_ref().and_then(|val| { val.card_type @@ -1380,7 +1380,7 @@ impl PaymentMethodExt for domain::PaymentMethodVaultingData { .ok() .flatten() }), - card_network: card_info.as_ref().and_then(|val| val.card_network.clone()), + card_network: card_info.as_ref().and_then(|val| val.card_network), card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()), card_type: card_info.as_ref().and_then(|val| { val.card_type diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 322557129d4..68f945b51ba 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -366,7 +366,7 @@ impl PaymentMethodsController for PmCards<'_> { card_holder_name: network_token_data.card_holder_name.clone(), nick_name: network_token_data.nick_name.clone(), card_issuing_country: network_token_data.card_issuing_country.clone(), - card_network: network_token_data.card_network.clone(), + card_network: network_token_data.card_network, card_issuer: network_token_data.card_issuer.clone(), card_type: network_token_data.card_type.clone(), }; @@ -1539,7 +1539,7 @@ pub async fn add_payment_method_data( expiry_year: Some(card.card_exp_year), nick_name: card.nick_name, card_holder_name: card.card_holder_name, - card_network: card_info.as_ref().and_then(|ci| ci.card_network.clone()), + card_network: card_info.as_ref().and_then(|ci| ci.card_network), card_isin: Some(card_isin), card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()), card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()), @@ -3311,7 +3311,7 @@ pub async fn list_payment_methods( let mut card_network_types = vec![]; for card_network_type in payment_method_types_hm.1 { card_network_types.push(CardNetworkTypes { - card_network: card_network_type.0.clone(), + card_network: *card_network_type.0, eligible_connectors: card_network_type.1.clone(), surcharge_details: None, }) diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs index 6c448dfa62a..1b626296877 100644 --- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs +++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs @@ -178,7 +178,7 @@ pub async fn perform_surcharge_decision_management_for_payment_method_list( if let Some(card_network_list) = &mut payment_method_type_response.card_networks { for card_network_type in card_network_list.iter_mut() { backend_input.payment_method.card_network = - Some(card_network_type.card_network.clone()); + Some(card_network_type.card_network); let surcharge_details = surcharge_source .generate_surcharge_details_and_populate_surcharge_metadata( &backend_input, @@ -188,7 +188,7 @@ pub async fn perform_surcharge_decision_management_for_payment_method_list( types::SurchargeKey::PaymentMethodData( payment_methods_enabled.payment_method, payment_method_type_response.payment_method_type, - Some(card_network_type.card_network.clone()), + Some(card_network_type.card_network), ), ), )?; @@ -414,7 +414,7 @@ pub async fn perform_surcharge_decision_management_for_saved_cards( // let card_network = match customer_payment_method.payment_method_data.as_ref() { // Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => { -// card.card_network.clone() +// card.card_network // } // _ => None, // }; diff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rs index f0eaea45d98..f689289d724 100644 --- a/crates/router/src/core/payment_methods/tokenize.rs +++ b/crates/router/src/core/payment_methods/tokenize.rs @@ -269,7 +269,7 @@ where card_holder_name: card_details.card_holder_name.clone(), issuer_country: card_details.card_issuing_country.clone(), card_issuer: card_details.card_issuer.clone(), - card_network: card_details.card_network.clone(), + card_network: card_details.card_network, card_type: card_details.card_type.clone(), saved_to_locker, co_badged_card_data: card_details @@ -299,7 +299,7 @@ where card_holder_name: card_details.card_holder_name.clone(), issuer_country: card_details.card_issuing_country.clone(), card_issuer: card_details.card_issuer.clone(), - card_network: card_details.card_network.clone(), + card_network: card_details.card_network, card_type: card_details.card_type.clone(), saved_to_locker, co_badged_card_data: None, diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rs index 905d2d3a126..eab9c423fa4 100644 --- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs @@ -117,9 +117,7 @@ impl<'a> NetworkTokenizationBuilder<'a, CardRequestValidated> { }), card_network: optional_card_info .as_ref() - .map_or(card_req.card_network.clone(), |card_info| { - card_info.card_network.clone() - }), + .map_or(card_req.card_network, |card_info| card_info.card_network), card_type: optional_card_info.as_ref().map_or( card_req .card_type @@ -255,7 +253,7 @@ impl<'a> NetworkTokenizationBuilder<'a, CardTokenStored> { card_holder_name: card.card_holder_name.clone(), card_fingerprint: None, nick_name: card.nick_name.clone(), - card_network: card.card_network.clone(), + card_network: card.card_network, card_isin: Some(card.card_number.clone().get_card_isin()), card_issuer: card.card_issuer.clone(), card_type: card.card_type.clone(), @@ -554,7 +552,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> { card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_issuing_country: card_details.card_issuing_country.clone(), - card_network: card_details.card_network.clone(), + card_network: card_details.card_network, card_issuer: card_details.card_issuer.clone(), card_type: card_details.card_type.clone(), }), diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs index ca9c2d9d140..d71b32a3dab 100644 --- a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs @@ -144,7 +144,7 @@ impl<'a> NetworkTokenizationBuilder<'a, PmValidated> { .and_then(|card_info| card_info.card_issuer.clone()), card_network: optional_card_info .as_ref() - .and_then(|card_info| card_info.card_network.clone()), + .and_then(|card_info| card_info.card_network), card_type: optional_card_info .as_ref() .and_then(|card_info| card_info.card_type.clone()), diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 53c07650507..247a1ead546 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -458,7 +458,6 @@ pub fn mk_add_card_response_hs( let card = api::CardDetailFromLocker { scheme: card .card_network - .clone() .map(|card_network| card_network.to_string()), last4_digits: Some(last4_digits), issuer_country: card.card_issuing_country, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 37703cd1bec..6c4e6696d2e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4939,7 +4939,7 @@ pub async fn get_additional_payment_data( logger::debug!("Co-badged card data found"); ( - card_data.card_network.clone(), + card_data.card_network, co_badged_data .co_badged_card_networks_info .get_signature_network(), @@ -4949,7 +4949,7 @@ pub async fn get_additional_payment_data( .or_else(|| { is_cobadged_based_on_regex.then(|| { logger::debug!("Card network is cobadged (regex-based detection)"); - (card_data.card_network.clone(), None, None) + (card_data.card_network, None, None) }) }) .unwrap_or_else(|| { @@ -4981,7 +4981,7 @@ pub async fn get_additional_payment_data( payment_checks: None, authentication_data: None, is_regulated, - signature_network: signature_network.clone(), + signature_network, }), ))) } else { @@ -4999,7 +4999,7 @@ pub async fn get_additional_payment_data( api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: card_info.card_issuer, - card_network: card_network.clone().or(card_info.card_network), + card_network: card_network.or(card_info.card_network), bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, @@ -5013,7 +5013,7 @@ pub async fn get_additional_payment_data( payment_checks: None, authentication_data: None, is_regulated, - signature_network: signature_network.clone(), + signature_network, }, )) }); @@ -5035,7 +5035,7 @@ pub async fn get_additional_payment_data( payment_checks: None, authentication_data: None, is_regulated, - signature_network: signature_network.clone(), + signature_network, }, )) }))) @@ -5254,7 +5254,7 @@ pub async fn get_additional_payment_data( .attach_printable( "Card cobadge check failed due to an invalid card network regex", )? { - true => card_data.card_network.clone(), + true => card_data.card_network, false => None, }; @@ -5300,7 +5300,7 @@ pub async fn get_additional_payment_data( api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: card_info.card_issuer, - card_network: card_network.clone().or(card_info.card_network), + card_network: card_network.or(card_info.card_network), bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, @@ -6499,7 +6499,7 @@ pub fn get_key_params_for_surcharge_details( Some(( common_enums::PaymentMethod::Card, common_enums::PaymentMethodType::Credit, - card.card_network.clone(), + card.card_network, )) } domain::PaymentMethodData::CardRedirect(card_redirect_data) => Some(( @@ -7337,7 +7337,7 @@ pub async fn validate_merchant_connector_ids_in_connector_mandate_details( let payments_map = payment_mandate_reference.0.clone(); for (migrating_merchant_connector_id, migrating_connector_mandate_details) in payments_map { match ( - card_network.clone(), + card_network, merchant_connector_account_details_hash_map.get(&migrating_merchant_connector_id), ) { (Some(enums::CardNetwork::Discover), Some(merchant_connector_account_details)) => { diff --git a/crates/router/src/core/payments/operations/payment_attempt_record.rs b/crates/router/src/core/payments/operations/payment_attempt_record.rs index 9f630c8424b..6aaece02dc0 100644 --- a/crates/router/src/core/payments/operations/payment_attempt_record.rs +++ b/crates/router/src/core/payments/operations/payment_attempt_record.rs @@ -202,7 +202,7 @@ impl<F: Send + Clone + Sync> retry_count: request.retry_count, invoice_next_billing_time: request.invoice_next_billing_time, triggered_by: request.triggered_by, - card_network: request.card_network.clone(), + card_network: request.card_network, card_issuer: request.card_issuer.clone(), }; let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index cbfdd05362c..341350ac765 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1156,7 +1156,6 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for let acquirer_config = additional_card_info.as_ref().and_then(|card_info| { card_info .card_network - .clone() .and_then(|network| business_profile.get_acquirer_details_from_network(network)) }); let country = business_profile @@ -1186,7 +1185,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for api_models::three_ds_decision_rule::PaymentMethodMetaData { card_network: additional_card_info .as_ref() - .and_then(|info| info.card_network.clone()), + .and_then(|info| info.card_network), }, ), issuer: Some(api_models::three_ds_decision_rule::IssuerData { diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 5e0f0eb1b81..e1c07763fe4 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -278,7 +278,7 @@ pub fn make_dsl_input( .payment_method_data .as_ref() .and_then(|pm_data| match pm_data { - domain::PaymentMethodData::Card(card) => card.card_network.clone(), + domain::PaymentMethodData::Card(card) => card.card_network, _ => None, }), @@ -390,7 +390,7 @@ pub fn make_dsl_input( .payment_method_data .as_ref() .and_then(|pm_data| match pm_data { - domain::PaymentMethodData::Card(card) => card.card_network.clone(), + domain::PaymentMethodData::Card(card) => card.card_network, _ => None, }), diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 759db4ef963..c625e3fcf08 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -610,7 +610,6 @@ where // scheme should be updated in case of co-badged cards let card_scheme = card .card_network - .clone() .map(|card_network| card_network.to_string()) .or(existing_pm_data.scheme.clone()); @@ -983,7 +982,7 @@ async fn skip_saving_card_in_locker( nick_name: None, card_isin: card_isin.clone(), card_issuer: card.card_issuer.clone(), - card_network: card.card_network.clone(), + card_network: card.card_network, card_type: card.card_type.clone(), saved_to_locker: false, }; @@ -1185,7 +1184,7 @@ pub async fn save_network_token_in_locker( card_holder_name: None, nick_name: None, card_issuing_country: None, - card_network: Some(token_response.card_brand.clone()), + card_network: Some(token_response.card_brand), card_issuer: None, card_type: None, }; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 51a315bee8b..a9cc9437cb4 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -5687,7 +5687,7 @@ impl ForeignFrom<&diesel_models::types::BillingConnectorPaymentMethodDetails> diesel_models::types::BillingConnectorPaymentMethodDetails::Card(card_details) => { Self::Card(api_models::payments::BillingConnectorAdditionalCardInfo { card_issuer: card_details.card_issuer.clone(), - card_network: card_details.card_network.clone(), + card_network: card_details.card_network, }) } } diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index c80a089e5d4..c10651207a3 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -524,8 +524,7 @@ pub async fn save_payout_data_to_locker( payment_method .payment_method_issuer .clone_from(&card_info.card_issuer); - payment_method.card_network = - card_info.card_network.clone().map(|cn| cn.to_string()); + payment_method.card_network = card_info.card_network.map(|cn| cn.to_string()); api::payment_methods::PaymentMethodsData::Card( api::payment_methods::CardDetailsPaymentMethod { last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()), @@ -1491,7 +1490,7 @@ pub async fn get_additional_payout_data( payout_additional::AdditionalPayoutMethodData::Card(Box::new( payout_additional::CardAdditionalData { card_issuer: card_info.card_issuer, - card_network: card_info.card_network.clone(), + card_network: card_info.card_network, bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, diff --git a/crates/router/src/core/profile_acquirer.rs b/crates/router/src/core/profile_acquirer.rs index dbe0beb54b0..5956c5aa134 100644 --- a/crates/router/src/core/profile_acquirer.rs +++ b/crates/router/src/core/profile_acquirer.rs @@ -34,7 +34,7 @@ pub async fn create_profile_acquirer( let incoming_acquirer_config = common_types::domain::AcquirerConfig { acquirer_assigned_merchant_id: request.acquirer_assigned_merchant_id.clone(), merchant_name: request.merchant_name.clone(), - network: request.network.clone(), + network: request.network, acquirer_bin: request.acquirer_bin.clone(), acquirer_ica: request.acquirer_ica.clone(), acquirer_fraud_rate: request.acquirer_fraud_rate, diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index f9662a745dd..cc85afb7d79 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -459,7 +459,7 @@ pub async fn perform_payments_sync( profile, merchant_context, new_revenue_recovery_payment_data, - payment_attempt, + &payment_attempt, &mut revenue_recovery_metadata, ), ) diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 3bdc822859f..216f8bcd45f 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -18,7 +18,8 @@ use diesel_models::{ use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ api::ApplicationResponse, - business_profile, merchant_connector_account, + business_profile, + merchant_connector_account::MerchantConnectorAccount, merchant_context::{Context, MerchantContext}, payments::{ self as domain_payments, payment_attempt::PaymentAttempt, PaymentConfirmData, @@ -128,7 +129,7 @@ impl RevenueRecoveryPaymentsAttemptStatus { let recovery_payment_attempt = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( - &payment_attempt, + payment_attempt, ); let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( @@ -151,7 +152,7 @@ impl RevenueRecoveryPaymentsAttemptStatus { // finish psync task as the payment was a success db.as_scheduler() .finish_process_with_business_status( - process_tracker, + process_tracker.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await?; @@ -214,7 +215,7 @@ impl RevenueRecoveryPaymentsAttemptStatus { // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( state, - &payment_attempt, + payment_attempt, payment_intent, &revenue_recovery_payment_data.billing_mca, ) @@ -294,7 +295,7 @@ impl RevenueRecoveryPaymentsAttemptStatus { Box::pin(action.psync_response_handler( state, payment_intent, - &process_tracker, + process_tracker, revenue_recovery_metadata, revenue_recovery_payment_data, )) @@ -322,7 +323,7 @@ impl Decision { intent_status: enums::IntentStatus, called_connector: enums::PaymentConnectorTransmission, active_attempt_id: Option<id_type::GlobalAttemptId>, - revenue_recovery_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, + revenue_recovery_data: &RevenueRecoveryPaymentData, payment_id: &id_type::GlobalPaymentId, ) -> RecoveryResult<Self> { logger::info!("Entering get_decision_based_on_params"); @@ -688,7 +689,7 @@ impl Action { state: &SessionState, payment_intent: &PaymentIntent, execute_task_process: &storage::ProcessTracker, - revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, + revenue_recovery_payment_data: &RevenueRecoveryPaymentData, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, ) -> Result<(), errors::ProcessTrackerError> { logger::info!("Entering execute_payment_task_response_handler"); @@ -822,7 +823,7 @@ impl Action { pub async fn payment_sync_call( state: &SessionState, - revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, + revenue_recovery_payment_data: &RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, process: &storage::ProcessTracker, profile: &domain::Profile, @@ -914,7 +915,7 @@ impl Action { } RevenueRecoveryPaymentsAttemptStatus::Processing => { - Ok(Self::SyncPayment(payment_attempt)) + Ok(Self::SyncPayment(payment_attempt.clone())) } RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => { logger::info!(?action, "Invalid Payment Status For PCR PSync Payment"); @@ -935,7 +936,7 @@ impl Action { payment_intent: &PaymentIntent, psync_task_process: &storage::ProcessTracker, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, - revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, + revenue_recovery_payment_data: &RevenueRecoveryPaymentData, ) -> Result<(), errors::ProcessTrackerError> { logger::info!("Entering psync_response_handler"); @@ -1071,8 +1072,8 @@ impl Action { pub(crate) async fn decide_retry_failure_action( state: &SessionState, merchant_id: &id_type::MerchantId, - pt: storage::ProcessTracker, - revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, + pt: &storage::ProcessTracker, + revenue_recovery_payment_data: &RevenueRecoveryPaymentData, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> RecoveryResult<Self> { @@ -1305,7 +1306,7 @@ async fn record_back_to_billing_connector( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, - billing_mca: &merchant_connector_account::MerchantConnectorAccount, + billing_mca: &MerchantConnectorAccount, ) -> RecoveryResult<()> { logger::info!("Entering record_back_to_billing_connector"); @@ -1357,7 +1358,7 @@ async fn record_back_to_billing_connector( pub fn construct_invoice_record_back_router_data( state: &SessionState, - billing_mca: &merchant_connector_account::MerchantConnectorAccount, + billing_mca: &MerchantConnectorAccount, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> RecoveryResult<hyperswitch_domain_models::types::InvoiceRecordBackRouterData> { diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 98b71748b35..f760ef23b12 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -365,7 +365,7 @@ impl DebitRoutingDecisionData { F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { - payment_data.set_card_network(self.card_network.clone()); + payment_data.set_card_network(self.card_network); self.debit_routing_result .as_ref() .map(|data| payment_data.set_co_badged_card_data(data)); diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 32953cd5eaf..1683ff6bc44 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -282,7 +282,6 @@ pub fn build_unified_connector_service_payment_method( let card_network = card .card_network - .clone() .map(payments_grpc::CardNetwork::foreign_try_from) .transpose()?; diff --git a/crates/router/src/core/webhooks/network_tokenization_incoming.rs b/crates/router/src/core/webhooks/network_tokenization_incoming.rs index a49ec40cbaa..90fb4037d42 100644 --- a/crates/router/src/core/webhooks/network_tokenization_incoming.rs +++ b/crates/router/src/core/webhooks/network_tokenization_incoming.rs @@ -392,7 +392,6 @@ impl From<(&api::payment_methods::CardDetail, &domain::PaymentMethod)> card: Some(data.clone()), card_network: data .card_network - .clone() .map(|card_network| card_network.to_string()), bank_transfer: None, wallet: None, diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index b56477cdac2..1b099988297 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -214,7 +214,11 @@ async fn handle_monitoring_threshold( ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { let db = &*state.store; let key_manager_state = &(state).into(); - let monitoring_threshold_config = state.conf.revenue_recovery.monitoring_threshold_in_seconds; + let monitoring_threshold_config = state + .conf + .revenue_recovery + .monitoring_threshold_in_seconds + .into(); let retry_algorithm_type = state.conf.revenue_recovery.retry_algorithm_type; let revenue_recovery_retry_algorithm = business_profile .revenue_recovery_retry_algorithm_data diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index 9afb697e14e..57afe3a8431 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -141,7 +141,7 @@ impl<'a> KafkaPaymentAttempt<'a> { debit_routing_savings: attempt.debit_routing_savings, signature_network: card_payment_method_data .as_ref() - .and_then(|data| data.signature_network.clone()), + .and_then(|data| data.signature_network), is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated), } } diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index 46a05d6fcf1..6df58860b4f 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -142,7 +142,7 @@ impl<'a> KafkaPaymentAttemptEvent<'a> { debit_routing_savings: attempt.debit_routing_savings, signature_network: card_payment_method_data .as_ref() - .and_then(|data| data.signature_network.clone()), + .and_then(|data| data.signature_network), is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated), } } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index c54241e6b5f..a2172f8b518 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -224,7 +224,7 @@ impl SessionSurchargeDetails { .get_surcharge_details(payments_types::SurchargeKey::PaymentMethodData( payment_method, payment_method_type, - card_network.cloned(), + card_network.copied(), )) .cloned(), Self::PreDetermined(surcharge_details) => Some(surcharge_details.clone()), diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index 4cde3bd99f8..09d7dfdb5bd 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -69,7 +69,7 @@ impl RevenueRecoveryPaymentData { #[derive(Debug, serde::Deserialize, Clone, Default)] pub struct RevenueRecoverySettings { - pub monitoring_threshold_in_seconds: i64, + pub monitoring_threshold_in_seconds: u32, pub retry_algorithm_type: enums::RevenueRecoveryAlgorithmType, pub recovery_timestamp: RecoveryTimestamp, pub card_config: RetryLimitsConfig, diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index e87b26e4c15..a2ac2b02185 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -368,7 +368,7 @@ pub(crate) async fn get_schedule_time_for_smart_retry( let decider_request = InternalDeciderRequest { first_error_message, billing_state, - card_funding: card_funding_str, + card_funding: payment_method_subtype_str, card_network: card_network_str, card_issuer: card_issuer_str, invoice_start_time: Some(start_time_proto),
2025-08-17T10:23:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0b263179af1b9dc3186c09c53b700b6a1f754d0e
juspay/hyperswitch
juspay__hyperswitch-9479
Bug: [BUG] [SHIFT4] 3DS payments not working ### Bug Description 3ds payments not working for shift4 ### Expected Behavior 3ds payments should work for shift4 ### Actual Behavior 3ds payments not working for connector shift4 ### 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/shift4.rs b/crates/hyperswitch_connectors/src/connectors/shift4.rs index 3af15de507f..01b23f61e56 100644 --- a/crates/hyperswitch_connectors/src/connectors/shift4.rs +++ b/crates/hyperswitch_connectors/src/connectors/shift4.rs @@ -2,6 +2,7 @@ pub mod transformers; use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; +use base64::Engine; use common_enums::enums; use common_utils::{ errors::CustomResult, @@ -46,7 +47,7 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; -use masking::Mask; +use masking::{Mask, PeekInterface}; use transformers::{self as shift4, Shift4PaymentsRequest, Shift4RefundRequest}; use crate::{ @@ -111,9 +112,13 @@ impl ConnectorCommon for Shift4 { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = shift4::Shift4AuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let api_key = format!( + "Basic {}", + common_utils::consts::BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek())) + ); Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.into_masked(), + api_key.into_masked(), )]) } @@ -277,7 +282,19 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Shift4 {} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Shift4 { + fn build_request( + &self, + _req: &hyperswitch_domain_models::types::PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::NotSupported { + message: "Void".to_string(), + connector: "Shift4", + } + .into()) + } +} impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Shift4 { fn get_headers( @@ -373,6 +390,12 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { + if req.request.amount_to_capture != req.request.payment_amount { + Err(errors::ConnectorError::NotSupported { + message: "Partial Capture".to_string(), + connector: "Shift4", + })? + } Ok(Some( RequestBuilder::new() .method(Method::Post) @@ -488,7 +511,7 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp )?; let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?; let connector_req = Shift4PaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request(
2025-09-22T11:02:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Fixed 3DS payments for Shift4. - Updated shift4 authentication to use the direct secret key from shift4 dashboard, removing the need for manual Base64 encoding. - Updated error messages for unsupported flows like Void and Partial Captures. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/9479 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Cypress: <img width="555" height="883" alt="image" src="https://github.com/user-attachments/assets/7dca5ff2-2ce7-4b7f-84cb-11a50c639508" /> Note: All card test cases are working as expected. Only 1 sofort test case is failing during redirection(which is unrelated to this PR) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
juspay/hyperswitch
juspay__hyperswitch-9472
Bug: [BUG] 3ds error mapping on 3ds failed authentication [NUVEI] No Error mapped when failed 3ds authenticaiton happens ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs index 9c906abeefc..77165ba9035 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs @@ -1153,7 +1153,7 @@ impl ConnectorRedirectResponse for Nuvei { Ok(CallConnectorAction::StatusUpdate { status: enums::AttemptStatus::AuthenticationFailed, error_code: None, - error_message: None, + error_message: Some("3ds Authentication failed".to_string()), }) } _ => Ok(CallConnectorAction::Trigger),
2025-09-22T08:23:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Show Error Message during 3ds un-sussessful error redirection ### request ```json { "amount": 15100, "currency": "EUR", "confirm": true, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, // "order_tax_amount": 100, "setup_future_usage": "off_session", // "payment_type":"setup_mandate", "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "[email protected]", "payment_method_data": { "card": { "card_number": "2221008123677736", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "CL-BRW2", "card_cvc": "100" } } } ``` ### Response ```json { "payment_id": "pay_fwQ1e408So9yev8f0rfZ", "merchant_id": "merchant_1758526798", "status": "requires_customer_action", "amount": 15100, "net_amount": 15100, "shipping_cost": null, "amount_capturable": 15100, "amount_received": null, "connector": "nuvei", "client_secret": "pay_fwQ1e408So9yev8f0rfZ_secret_kgOB1urvHoS4RJMA2uUU", "created": "2025-09-22T07:40:07.679Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "7736", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "222100", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "CL-BRW2", "payment_checks": { "avs_result": "", "avs_description": null, "card_validation_result": "", "card_validation_description": null }, "authentication_data": { "cReq": "eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjhjY2NkYWQwLWIyYzgtNDQyYy05NTkxLTkxM2M4ZWVlZDZmNyIsImFjc1RyYW5zSUQiOiJjMzRlMmJkZS0wODYwLTRmZWItOWQ5ZS1mYmY2Y2YxZDY4ZjIiLCJjaGFsbGVuZ2VXaW5kb3dTaXplIjoiMDUiLCJtZXNzYWdlVHlwZSI6IkNSZXEiLCJtZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0", "flow": "challenge", "acsUrl": "https://3dsn.sandbox.safecharge.com/ThreeDSACSEmulatorChallenge/api/ThreeDSACSChallengeController/ChallengePage?eyJub3RpZmljYXRpb25VUkwiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcGF5bWVudHMvcGF5X2Z3UTFlNDA4U285eWV2OGYwcmZaL21lcmNoYW50XzE3NTg1MjY3OTgvcmVkaXJlY3QvY29tcGxldGUvbnV2ZWkiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjhjY2NkYWQwLWIyYzgtNDQyYy05NTkxLTkxM2M4ZWVlZDZmNyIsImFjc1RyYW5zSUQiOiJjMzRlMmJkZS0wODYwLTRmZWItOWQ5ZS1mYmY2Y2YxZDY4ZjIiLCJkc1RyYW5zSUQiOiIyN2QzYTdmZC01MWQ2LTQyMzUtYjUxYS1iNDM1MWI1YzhkNTUiLCJkYXRhIjpudWxsLCJNZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0=", "version": "2.2.0", "threeDFlow": "1", "decisionReason": "NoPreference", "threeDReasonId": "", "acquirerDecision": "ExemptionRequest", "challengePreferenceReason": "12", "isExemptionRequestInAuthentication": "0" } }, "billing": null }, "payment_token": "token_bf3xxZIcLphaWc1zN4EK", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://www.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_fwQ1e408So9yev8f0rfZ/merchant_1758526798/pay_fwQ1e408So9yev8f0rfZ_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": "nithxxinn", "created_at": 1758526807, "expires": 1758530407, "secret": "epk_232dee5832244f6eaf70dc9ce96dac85" }, "manual_retry_allowed": null, "connector_transaction_id": "8110000000014692337", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "9043552111", "payment_link": null, "profile_id": "pro_CHQ1GcBL3YipP8sGVO3B", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_9jUvWoUndSfvW4nY9kay", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-22T07:55:07.679Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_ihTRKltv5SDVRSK4mK2v", "network_transaction_id": "", "payment_method_status": "inactive", "updated": "2025-09-22T07:40:12.797Z", "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": "2090421111", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` <img width="1717" height="1117" alt="Screenshot 2025-09-22 at 1 09 05 PM" src="https://github.com/user-attachments/assets/55f8815e-88d5-4ada-b053-c23a73afc413" /> ### Psync ```json { "payment_id": "pay_fwQ1e408So9yev8f0rfZ", "merchant_id": "merchant_1758526798", "status": "failed", "amount": 15100, "net_amount": 15100, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_fwQ1e408So9yev8f0rfZ_secret_kgOB1urvHoS4RJMA2uUU", "created": "2025-09-22T07:40:07.679Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "7736", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "222100", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "CL-BRW2", "payment_checks": { "avs_result": "", "avs_description": null, "card_validation_result": "", "card_validation_description": null }, "authentication_data": { "cReq": "eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjhjY2NkYWQwLWIyYzgtNDQyYy05NTkxLTkxM2M4ZWVlZDZmNyIsImFjc1RyYW5zSUQiOiJjMzRlMmJkZS0wODYwLTRmZWItOWQ5ZS1mYmY2Y2YxZDY4ZjIiLCJjaGFsbGVuZ2VXaW5kb3dTaXplIjoiMDUiLCJtZXNzYWdlVHlwZSI6IkNSZXEiLCJtZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0", "flow": "challenge", "acsUrl": "https://3dsn.sandbox.safecharge.com/ThreeDSACSEmulatorChallenge/api/ThreeDSACSChallengeController/ChallengePage?eyJub3RpZmljYXRpb25VUkwiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcGF5bWVudHMvcGF5X2Z3UTFlNDA4U285eWV2OGYwcmZaL21lcmNoYW50XzE3NTg1MjY3OTgvcmVkaXJlY3QvY29tcGxldGUvbnV2ZWkiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjhjY2NkYWQwLWIyYzgtNDQyYy05NTkxLTkxM2M4ZWVlZDZmNyIsImFjc1RyYW5zSUQiOiJjMzRlMmJkZS0wODYwLTRmZWItOWQ5ZS1mYmY2Y2YxZDY4ZjIiLCJkc1RyYW5zSUQiOiIyN2QzYTdmZC01MWQ2LTQyMzUtYjUxYS1iNDM1MWI1YzhkNTUiLCJkYXRhIjpudWxsLCJNZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0=", "version": "2.2.0", "threeDFlow": "1", "decisionReason": "NoPreference", "threeDReasonId": "", "acquirerDecision": "ExemptionRequest", "challengePreferenceReason": "12", "isExemptionRequestInAuthentication": "0" } }, "billing": null }, "payment_token": "token_bf3xxZIcLphaWc1zN4EK", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://www.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": "3ds Authentication failed", // error msg "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": null, "connector_transaction_id": "8110000000014692337", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "9043552111", "payment_link": null, "profile_id": "pro_CHQ1GcBL3YipP8sGVO3B", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_9jUvWoUndSfvW4nY9kay", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-22T07:55:07.679Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_ihTRKltv5SDVRSK4mK2v", "network_transaction_id": "", "payment_method_status": "inactive", "updated": "2025-09-22T07:40:25.329Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": { "network_advice_code": null } } ```
740f3af64304469f9a6d781de349cf762a311c6f
juspay/hyperswitch
juspay__hyperswitch-9477
Bug: [FEATURE]: add client_auth auth type for list_blocked_payment_methods
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs index 2afeb2db4f6..9fb537b226f 100644 --- a/crates/api_models/src/blocklist.rs +++ b/crates/api_models/src/blocklist.rs @@ -53,6 +53,7 @@ pub struct ListBlocklistQuery { pub limit: u16, #[serde(default)] pub offset: u16, + pub client_secret: Option<String>, } fn default_list_limit() -> u16 { diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs index 9e6a7eca30a..be4e81afc3f 100644 --- a/crates/router/src/routes/blocklist.rs +++ b/crates/router/src/routes/blocklist.rs @@ -1,5 +1,6 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::blocklist as api_blocklist; +use error_stack::report; use router_env::Flow; use crate::{ @@ -117,11 +118,24 @@ pub async fn list_blocked_payment_methods( query_payload: web::Query<api_blocklist::ListBlocklistQuery>, ) -> HttpResponse { let flow = Flow::ListBlocklist; + let payload = query_payload.into_inner(); + + let api_auth = auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }; + + let (auth_type, _) = + match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(report!(err)), + }; + Box::pin(api::server_wrap( flow, state, &req, - query_payload.into_inner(), + payload, |state, auth: auth::AuthenticationData, query, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), @@ -129,10 +143,7 @@ pub async fn list_blocked_payment_methods( blocklist::list_blocklist_entries(state, merchant_context, query) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth { - is_connected_allowed: false, - is_platform_allowed: false, - }), + &*auth_type, &auth::JWTAuth { permission: Permission::MerchantAccountRead, }, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 1e48e9e52b1..851c2cf21b9 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -4161,6 +4161,13 @@ impl ClientSecretFetch for payments::PaymentsRequest { } } +#[cfg(feature = "v1")] +impl ClientSecretFetch for api_models::blocklist::ListBlocklistQuery { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref() + } +} + #[cfg(feature = "v1")] impl ClientSecretFetch for payments::PaymentsRetrieveRequest { fn get_client_secret(&self) -> Option<&String> {
2025-09-22T10:16:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description add client_secret auth auth type for list_blocked_payment_methods ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? 1. create a blocklist ``` curl --location 'http://localhost:8080/blocklist' \ --header 'Content-Type: application/json' \ --header 'api-key: ______' \ --data '{ "type": "card_bin", "data": "424242" }' ``` Response ``` { "fingerprint_id": "424242", "data_kind": "card_bin", "created_at": "2025-09-22T11:25:25.775Z" } ``` 2. List using client secret ``` curl --location 'http://localhost:8080/blocklist?data_kind=card_bin&client_secret=______' \ --header 'api-key: ____' ``` Response ``` [ { "fingerprint_id": "424242", "data_kind": "card_bin", "created_at": "2025-09-22T11:25:25.775Z" } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
juspay/hyperswitch
juspay__hyperswitch-9467
Bug: confirm-intent API contract changes for split payments (v2) In v2, we need to support receiving multiple payment methods in the confirm-intent request. Add a new field to support this use case
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 8c8052b14d0..1a035fd291e 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2659,6 +2659,16 @@ pub struct PaymentMethodDataRequest { pub billing: Option<Address>, } +#[cfg(feature = "v2")] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct SplitPaymentMethodDataRequest { + pub payment_method_data: PaymentMethodData, + #[schema(value_type = PaymentMethod)] + pub payment_method_type: api_enums::PaymentMethod, + #[schema(value_type = PaymentMethodType)] + pub payment_method_subtype: api_enums::PaymentMethodType, +} + /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct RecordAttemptPaymentMethodDataRequest { @@ -5762,6 +5772,9 @@ pub struct PaymentsConfirmIntentRequest { /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, + /// The payment instrument data to be used for the payment in case of split payments + pub split_payment_method_data: Option<Vec<SplitPaymentMethodDataRequest>>, + /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, @@ -6083,6 +6096,7 @@ impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { payment_token: None, merchant_connector_details: request.merchant_connector_details.clone(), return_raw_connector_response: request.return_raw_connector_response, + split_payment_method_data: None, } } } diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index eb172cf0cf5..6ea50cb85fa 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -435,6 +435,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PhoneDetails, api_models::payments::PaymentMethodData, api_models::payments::PaymentMethodDataRequest, + api_models::payments::SplitPaymentMethodDataRequest, api_models::payments::MandateType, api_models::payments::MandateAmountData, api_models::payments::Card,
2025-09-22T07:31:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Added `split_payment_method_data` field to `confirm-intent` call to accept a `Vec` of payment methods <img width="502" height="763" alt="image" src="https://github.com/user-attachments/assets/69ae3cc4-3d06-4980-b2d9-52b489aa98ad" /> ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #9467 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Note: Currently the `split_payment_method_data` field is not used. This PR just adds it to the API contract. There are no behaviour changes. The field will be used in a future PR. Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_019975b06d2d77b0beff1a83df9a3377/confirm-intent' \ --header 'x-profile-id: pro_JSAAWLeyardnZ5iQDB4o' \ --header 'x-client-secret: cs_019975b06d407b738bb37971ce338246' \ --header 'Authorization: publishable-key=pk_dev_e098d9545be8466a9e52bfd7db41ec77,client-secret=cs_019975b06d407b738bb37971ce338246' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_e098d9545be8466a9e52bfd7db41ec77' \ --data '{ "payment_method_data": { "card": { "card_cvc": "737", "card_exp_month": "03", "card_exp_year": "30", "card_number": "4000620000000007", "card_holder_name": "joseph Doe" } }, "payment_method_type": "card", "payment_method_subtype": "card", "split_payment_method_data": [ { "payment_method_data": { "gift_card": { "givex": { "number": "6036280000000000000", "cvc": "123" } } }, "payment_method_type": "gift_card", "payment_method_subtype": "givex" } ], "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" } }' ``` Response: ``` { "id": "12345_pay_019975b06d2d77b0beff1a83df9a3377", "status": "succeeded", "amount": { "order_amount": 1000, "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": 1000, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 1000 }, "customer_id": "12345_cus_019975b064727f82a64abdb387d8fd72", "connector": "adyen", "created": "2025-09-23T08:28:40.634Z", "modified_at": "2025-09-23T08:29:32.736Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "card", "connector_transaction_id": "GRFLWGK5NVTV7VV5", "connector_reference_id": "12345_att_019975b12e2176c2bfa32a42a67b8891", "merchant_connector_id": "mca_yON0ejlCVv7kJuPN8wRs", "browser_info": null, "error": 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": "three_ds", "authentication_type_applied": "three_ds", "is_iframe_redirection_enabled": null, "merchant_reference_id": null, "raw_connector_response": null, "feature_metadata": null, "metadata": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2553780051e3a2fe54fcb99384e4bd8021d52048
juspay/hyperswitch
juspay__hyperswitch-9500
Bug: [FEATURE] Add external vault support in v1 Add external vault support in v1 payments flow. Currently we only save card in hs-card-vault Added new support to save card in external vault based merchant-profile configuration.
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index b0b656a1ede..e0483b19503 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2203,6 +2203,13 @@ pub struct ProfileCreate { /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + + /// Indicates if external vault is enabled or not. + #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] + pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, + + /// External Vault Connector Details + pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[nutype::nutype( @@ -2553,6 +2560,13 @@ pub struct ProfileResponse { /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + + /// Indicates if external vault is enabled or not. + #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] + pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, + + /// External Vault Connector Details + pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[cfg(feature = "v2")] @@ -2906,6 +2920,13 @@ pub struct ProfileUpdate { /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + + /// Indicates if external vault is enabled or not. + #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] + pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, + + /// External Vault Connector Details + pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[cfg(feature = "v2")] diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 75c5f27df57..591932c5deb 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1413,6 +1413,34 @@ impl From<CardDetail> for CardDetailFromLocker { } } +#[cfg(feature = "v1")] +impl From<CardDetail> for CardDetailFromLocker { + fn from(item: CardDetail) -> Self { + // scheme should be updated in case of co-badged cards + let card_scheme = item + .card_network + .clone() + .map(|card_network| card_network.to_string()); + Self { + issuer_country: item.card_issuing_country, + last4_digits: Some(item.card_number.get_last4()), + card_number: Some(item.card_number), + 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, + card_fingerprint: None, + scheme: card_scheme, + card_token: None, + } + } +} + #[cfg(feature = "v2")] impl From<CardDetail> for CardDetailsPaymentMethod { fn from(item: CardDetail) -> Self { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 581858a85de..df7cb93114f 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -9491,3 +9491,50 @@ impl RoutingApproach { pub enum CallbackMapperIdType { NetworkTokenRequestorReferenceID, } + +/// Payment Method Status +#[derive( + Clone, + Copy, + Debug, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum VaultType { + /// Indicates that the payment method is stored in internal vault. + Internal, + /// Indicates that the payment method is stored in external vault. + External, +} + +#[derive( + Clone, + Debug, + Copy, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum ExternalVaultEnabled { + Enable, + #[default] + Skip, +} diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index a1e13b1f40c..17641cee59b 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -80,6 +80,8 @@ pub struct Profile { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub is_external_vault_enabled: Option<bool>, + pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[cfg(feature = "v1")] @@ -139,6 +141,8 @@ pub struct ProfileNew { pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, + pub is_external_vault_enabled: Option<bool>, + pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[cfg(feature = "v1")] @@ -199,6 +203,8 @@ pub struct ProfileUpdateInternal { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub is_external_vault_enabled: Option<bool>, + pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[cfg(feature = "v1")] @@ -256,6 +262,8 @@ impl ProfileUpdateInternal { dispute_polling_interval, is_manual_retry_enabled, always_enable_overcapture, + is_external_vault_enabled, + external_vault_connector_details, } = self; Profile { profile_id: source.profile_id, @@ -345,6 +353,10 @@ impl ProfileUpdateInternal { is_manual_retry_enabled: is_manual_retry_enabled.or(source.is_manual_retry_enabled), always_enable_overcapture: always_enable_overcapture .or(source.always_enable_overcapture), + is_external_vault_enabled: is_external_vault_enabled + .or(source.is_external_vault_enabled), + external_vault_connector_details: external_vault_connector_details + .or(source.external_vault_connector_details), } } } @@ -411,6 +423,8 @@ pub struct Profile { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub is_external_vault_enabled: Option<bool>, + pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, @@ -422,8 +436,6 @@ pub struct Profile { Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, - pub is_external_vault_enabled: Option<bool>, - pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 34fff64e7d9..747c6fdbd39 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -60,6 +60,8 @@ pub struct PaymentMethod { pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, + pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub vault_type: Option<storage_enums::VaultType>, } #[cfg(feature = "v2")] @@ -84,11 +86,12 @@ pub struct PaymentMethod { pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, + pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub vault_type: Option<storage_enums::VaultType>, pub locker_fingerprint_id: Option<String>, pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: common_utils::id_type::GlobalPaymentMethodId, - pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub external_vault_token_data: Option<Encryption>, } @@ -144,6 +147,8 @@ pub struct PaymentMethodNew { pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, + pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub vault_type: Option<storage_enums::VaultType>, } #[cfg(feature = "v2")] @@ -173,6 +178,7 @@ pub struct PaymentMethodNew { pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: common_utils::id_type::GlobalPaymentMethodId, + pub vault_type: Option<storage_enums::VaultType>, } impl PaymentMethodNew { @@ -372,6 +378,7 @@ impl PaymentMethodUpdateInternal { .or(source.network_token_payment_method_data), external_vault_source: external_vault_source.or(source.external_vault_source), external_vault_token_data: source.external_vault_token_data, + vault_type: source.vault_type, } } } @@ -458,6 +465,8 @@ impl PaymentMethodUpdateInternal { network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id), network_token_payment_method_data: network_token_payment_method_data .or(source.network_token_payment_method_data), + external_vault_source: source.external_vault_source, + vault_type: source.vault_type, } } } @@ -899,6 +908,8 @@ impl From<&PaymentMethodNew> for PaymentMethod { network_token_payment_method_data: payment_method_new .network_token_payment_method_data .clone(), + external_vault_source: payment_method_new.external_vault_source.clone(), + vault_type: payment_method_new.vault_type, } } } @@ -937,6 +948,7 @@ impl From<&PaymentMethodNew> for PaymentMethod { .clone(), external_vault_source: None, external_vault_token_data: payment_method_new.external_vault_token_data.clone(), + vault_type: payment_method_new.vault_type, } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 36345ef7570..9316c470d99 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -257,6 +257,8 @@ diesel::table! { dispute_polling_interval -> Nullable<Int4>, is_manual_retry_enabled -> Nullable<Bool>, always_enable_overcapture -> Nullable<Bool>, + is_external_vault_enabled -> Nullable<Bool>, + external_vault_connector_details -> Nullable<Jsonb>, } } @@ -1240,6 +1242,10 @@ diesel::table! { #[max_length = 64] network_token_locker_id -> Nullable<Varchar>, network_token_payment_method_data -> Nullable<Bytea>, + #[max_length = 64] + external_vault_source -> Nullable<Varchar>, + #[max_length = 64] + vault_type -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index f05b4e460c3..5433c9ca5ad 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -252,6 +252,8 @@ diesel::table! { dispute_polling_interval -> Nullable<Int4>, is_manual_retry_enabled -> Nullable<Bool>, always_enable_overcapture -> Nullable<Bool>, + is_external_vault_enabled -> Nullable<Bool>, + external_vault_connector_details -> Nullable<Jsonb>, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, order_fulfillment_time -> Nullable<Int8>, @@ -265,8 +267,6 @@ diesel::table! { should_collect_cvv_during_payment -> Nullable<Bool>, revenue_recovery_retry_algorithm_type -> Nullable<RevenueRecoveryAlgorithmType>, revenue_recovery_retry_algorithm_data -> Nullable<Jsonb>, - is_external_vault_enabled -> Nullable<Bool>, - external_vault_connector_details -> Nullable<Jsonb>, #[max_length = 16] split_txns_enabled -> Nullable<Varchar>, } @@ -1172,6 +1172,10 @@ diesel::table! { network_token_locker_id -> Nullable<Varchar>, network_token_payment_method_data -> Nullable<Bytea>, #[max_length = 64] + external_vault_source -> Nullable<Varchar>, + #[max_length = 64] + vault_type -> Nullable<Varchar>, + #[max_length = 64] locker_fingerprint_id -> Nullable<Varchar>, #[max_length = 64] payment_method_type_v2 -> Nullable<Varchar>, @@ -1179,8 +1183,6 @@ diesel::table! { payment_method_subtype -> Nullable<Varchar>, #[max_length = 64] id -> Varchar, - #[max_length = 64] - external_vault_source -> Nullable<Varchar>, external_vault_token_data -> Nullable<Bytea>, } } diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index efb9fc5979d..3672db0dd16 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -11,13 +11,11 @@ use common_utils::{ pii, type_name, types::keymanager, }; -use diesel_models::business_profile::{ - AuthenticationConnectorDetails, BusinessPaymentLinkConfig, BusinessPayoutLinkConfig, - CardTestingGuardConfig, ProfileUpdateInternal, WebhookDetails, -}; #[cfg(feature = "v2")] +use diesel_models::business_profile::RevenueRecoveryAlgorithmData; use diesel_models::business_profile::{ - ExternalVaultConnectorDetails, RevenueRecoveryAlgorithmData, + AuthenticationConnectorDetails, BusinessPaymentLinkConfig, BusinessPayoutLinkConfig, + CardTestingGuardConfig, ExternalVaultConnectorDetails, ProfileUpdateInternal, WebhookDetails, }; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -86,6 +84,104 @@ pub struct Profile { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub external_vault_details: ExternalVaultDetails, +} + +#[cfg(feature = "v1")] +#[derive(Clone, Debug)] +pub enum ExternalVaultDetails { + ExternalVaultEnabled(ExternalVaultConnectorDetails), + Skip, +} + +#[cfg(feature = "v1")] +impl ExternalVaultDetails { + pub fn is_external_vault_enabled(&self) -> bool { + match self { + Self::ExternalVaultEnabled(_) => true, + Self::Skip => false, + } + } +} + +#[cfg(feature = "v1")] +impl + TryFrom<( + Option<common_enums::ExternalVaultEnabled>, + Option<ExternalVaultConnectorDetails>, + )> for ExternalVaultDetails +{ + type Error = error_stack::Report<ValidationError>; + fn try_from( + item: ( + Option<common_enums::ExternalVaultEnabled>, + Option<ExternalVaultConnectorDetails>, + ), + ) -> Result<Self, Self::Error> { + match item { + (is_external_vault_enabled, external_vault_connector_details) + if is_external_vault_enabled + .unwrap_or(common_enums::ExternalVaultEnabled::Skip) + == common_enums::ExternalVaultEnabled::Enable => + { + Ok(Self::ExternalVaultEnabled( + external_vault_connector_details + .get_required_value("ExternalVaultConnectorDetails")?, + )) + } + _ => Ok(Self::Skip), + } + } +} + +#[cfg(feature = "v1")] +impl TryFrom<(Option<bool>, Option<ExternalVaultConnectorDetails>)> for ExternalVaultDetails { + type Error = error_stack::Report<ValidationError>; + fn try_from( + item: (Option<bool>, Option<ExternalVaultConnectorDetails>), + ) -> Result<Self, Self::Error> { + match item { + (is_external_vault_enabled, external_vault_connector_details) + if is_external_vault_enabled.unwrap_or(false) => + { + Ok(Self::ExternalVaultEnabled( + external_vault_connector_details + .get_required_value("ExternalVaultConnectorDetails")?, + )) + } + _ => Ok(Self::Skip), + } + } +} + +#[cfg(feature = "v1")] +impl From<ExternalVaultDetails> + for ( + Option<common_enums::ExternalVaultEnabled>, + Option<ExternalVaultConnectorDetails>, + ) +{ + fn from(external_vault_details: ExternalVaultDetails) -> Self { + match external_vault_details { + ExternalVaultDetails::ExternalVaultEnabled(connector_details) => ( + Some(common_enums::ExternalVaultEnabled::Enable), + Some(connector_details), + ), + ExternalVaultDetails::Skip => (Some(common_enums::ExternalVaultEnabled::Skip), None), + } + } +} + +#[cfg(feature = "v1")] +impl From<ExternalVaultDetails> for (Option<bool>, Option<ExternalVaultConnectorDetails>) { + fn from(external_vault_details: ExternalVaultDetails) -> Self { + match external_vault_details { + ExternalVaultDetails::ExternalVaultEnabled(connector_details) => { + (Some(true), Some(connector_details)) + } + ExternalVaultDetails::Skip => (Some(false), None), + } + } } #[cfg(feature = "v1")] @@ -144,6 +240,7 @@ pub struct ProfileSetter { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub external_vault_details: ExternalVaultDetails, } #[cfg(feature = "v1")] @@ -209,6 +306,7 @@ impl From<ProfileSetter> for Profile { dispute_polling_interval: value.dispute_polling_interval, is_manual_retry_enabled: value.is_manual_retry_enabled, always_enable_overcapture: value.always_enable_overcapture, + external_vault_details: value.external_vault_details, } } } @@ -276,6 +374,8 @@ pub struct ProfileGeneralUpdate { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, + pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[cfg(feature = "v1")] @@ -361,8 +461,18 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_request_extended_authorization, is_manual_retry_enabled, always_enable_overcapture, + is_external_vault_enabled, + external_vault_connector_details, } = *update; + let is_external_vault_enabled = match is_external_vault_enabled { + Some(external_vault_mode) => match external_vault_mode { + common_enums::ExternalVaultEnabled::Enable => Some(true), + common_enums::ExternalVaultEnabled::Skip => Some(false), + }, + None => Some(false), + }; + Self { profile_name, modified_at: now, @@ -416,6 +526,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { dispute_polling_interval, is_manual_retry_enabled, always_enable_overcapture, + is_external_vault_enabled, + external_vault_connector_details, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -474,6 +586,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, + is_external_vault_enabled: None, + external_vault_connector_details: None, }, ProfileUpdate::DynamicRoutingAlgorithmUpdate { dynamic_routing_algorithm, @@ -529,6 +643,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, + is_external_vault_enabled: None, + external_vault_connector_details: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -584,6 +700,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, + is_external_vault_enabled: None, + external_vault_connector_details: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -639,6 +757,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, + is_external_vault_enabled: None, + external_vault_connector_details: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -694,6 +814,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, + is_external_vault_enabled: None, + external_vault_connector_details: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -749,6 +871,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, + is_external_vault_enabled: None, + external_vault_connector_details: None, }, ProfileUpdate::AcquirerConfigMapUpdate { acquirer_config_map, @@ -804,6 +928,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, + is_external_vault_enabled: None, + external_vault_connector_details: None, }, } } @@ -816,6 +942,9 @@ impl super::behaviour::Conversion for Profile { type NewDstType = diesel_models::business_profile::ProfileNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + let (is_external_vault_enabled, external_vault_connector_details) = + self.external_vault_details.into(); + Ok(diesel_models::business_profile::Profile { profile_id: self.profile_id.clone(), id: Some(self.profile_id), @@ -879,6 +1008,8 @@ impl super::behaviour::Conversion for Profile { dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, always_enable_overcapture: self.always_enable_overcapture, + is_external_vault_enabled, + external_vault_connector_details, }) } @@ -891,104 +1022,124 @@ impl super::behaviour::Conversion for Profile { where Self: Sized, { - async { - Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - profile_id: item.profile_id, - merchant_id: item.merchant_id, - profile_name: item.profile_name, - created_at: item.created_at, - modified_at: item.modified_at, - return_url: item.return_url, - enable_payment_response_hash: item.enable_payment_response_hash, - payment_response_hash_key: item.payment_response_hash_key, - redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, - webhook_details: item.webhook_details, - metadata: item.metadata, - routing_algorithm: item.routing_algorithm, - intent_fulfillment_time: item.intent_fulfillment_time, - frm_routing_algorithm: item.frm_routing_algorithm, - payout_routing_algorithm: item.payout_routing_algorithm, - is_recon_enabled: item.is_recon_enabled, - applepay_verified_domains: item.applepay_verified_domains, - payment_link_config: item.payment_link_config, - session_expiry: item.session_expiry, - authentication_connector_details: item.authentication_connector_details, - payout_link_config: item.payout_link_config, - is_extended_card_info_enabled: item.is_extended_card_info_enabled, - extended_card_info_config: item.extended_card_info_config, - is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, - use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, - collect_shipping_details_from_wallet_connector: item - .collect_shipping_details_from_wallet_connector, - collect_billing_details_from_wallet_connector: item - .collect_billing_details_from_wallet_connector, - always_collect_billing_details_from_wallet_connector: item - .always_collect_billing_details_from_wallet_connector, - always_collect_shipping_details_from_wallet_connector: item - .always_collect_shipping_details_from_wallet_connector, - outgoing_webhook_custom_http_headers: item - .outgoing_webhook_custom_http_headers - .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?, - tax_connector_id: item.tax_connector_id, - is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false), - version: item.version, - dynamic_routing_algorithm: item.dynamic_routing_algorithm, - is_network_tokenization_enabled: item.is_network_tokenization_enabled, - is_auto_retries_enabled: item.is_auto_retries_enabled.unwrap_or(false), - max_auto_retries_enabled: item.max_auto_retries_enabled, - always_request_extended_authorization: item.always_request_extended_authorization, - is_click_to_pay_enabled: item.is_click_to_pay_enabled, - authentication_product_ids: item.authentication_product_ids, - 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?, - is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, - force_3ds_challenge: item.force_3ds_challenge.unwrap_or_default(), - is_debit_routing_enabled: item.is_debit_routing_enabled, - merchant_business_country: item.merchant_business_country, - is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, - is_pre_network_tokenization_enabled: item - .is_pre_network_tokenization_enabled - .unwrap_or(false), - three_ds_decision_rule_algorithm: item.three_ds_decision_rule_algorithm, - acquirer_config_map: item.acquirer_config_map, - merchant_category_code: item.merchant_category_code, - merchant_country_code: item.merchant_country_code, - dispute_polling_interval: item.dispute_polling_interval, - is_manual_retry_enabled: item.is_manual_retry_enabled, - always_enable_overcapture: item.always_enable_overcapture, - }) + // Decrypt encrypted fields first + let (outgoing_webhook_custom_http_headers, card_testing_secret_key) = async { + let outgoing_webhook_custom_http_headers = item + .outgoing_webhook_custom_http_headers + .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?; + + let 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?; + + Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>(( + outgoing_webhook_custom_http_headers, + card_testing_secret_key, + )) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), + })?; + + let external_vault_details = ExternalVaultDetails::try_from(( + item.is_external_vault_enabled, + item.external_vault_connector_details, + ))?; + + // Construct the domain type + Ok(Self { + profile_id: item.profile_id, + merchant_id: item.merchant_id, + profile_name: item.profile_name, + created_at: item.created_at, + modified_at: item.modified_at, + return_url: item.return_url, + enable_payment_response_hash: item.enable_payment_response_hash, + payment_response_hash_key: item.payment_response_hash_key, + redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, + webhook_details: item.webhook_details, + metadata: item.metadata, + routing_algorithm: item.routing_algorithm, + intent_fulfillment_time: item.intent_fulfillment_time, + frm_routing_algorithm: item.frm_routing_algorithm, + payout_routing_algorithm: item.payout_routing_algorithm, + is_recon_enabled: item.is_recon_enabled, + applepay_verified_domains: item.applepay_verified_domains, + payment_link_config: item.payment_link_config, + session_expiry: item.session_expiry, + authentication_connector_details: item.authentication_connector_details, + payout_link_config: item.payout_link_config, + is_extended_card_info_enabled: item.is_extended_card_info_enabled, + extended_card_info_config: item.extended_card_info_config, + is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: item + .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: item + .collect_billing_details_from_wallet_connector, + always_collect_billing_details_from_wallet_connector: item + .always_collect_billing_details_from_wallet_connector, + always_collect_shipping_details_from_wallet_connector: item + .always_collect_shipping_details_from_wallet_connector, + outgoing_webhook_custom_http_headers, + tax_connector_id: item.tax_connector_id, + is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false), + version: item.version, + dynamic_routing_algorithm: item.dynamic_routing_algorithm, + is_network_tokenization_enabled: item.is_network_tokenization_enabled, + is_auto_retries_enabled: item.is_auto_retries_enabled.unwrap_or(false), + max_auto_retries_enabled: item.max_auto_retries_enabled, + always_request_extended_authorization: item.always_request_extended_authorization, + is_click_to_pay_enabled: item.is_click_to_pay_enabled, + authentication_product_ids: item.authentication_product_ids, + card_testing_guard_config: item.card_testing_guard_config, + card_testing_secret_key, + is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, + force_3ds_challenge: item.force_3ds_challenge.unwrap_or_default(), + is_debit_routing_enabled: item.is_debit_routing_enabled, + merchant_business_country: item.merchant_business_country, + is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled: item + .is_pre_network_tokenization_enabled + .unwrap_or(false), + three_ds_decision_rule_algorithm: item.three_ds_decision_rule_algorithm, + acquirer_config_map: item.acquirer_config_map, + merchant_category_code: item.merchant_category_code, + merchant_country_code: item.merchant_country_code, + dispute_polling_interval: item.dispute_polling_interval, + is_manual_retry_enabled: item.is_manual_retry_enabled, + always_enable_overcapture: item.always_enable_overcapture, + external_vault_details, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + let (is_external_vault_enabled, external_vault_connector_details) = + self.external_vault_details.into(); + Ok(diesel_models::business_profile::ProfileNew { profile_id: self.profile_id.clone(), id: Some(self.profile_id), @@ -1047,6 +1198,8 @@ impl super::behaviour::Conversion for Profile { merchant_country_code: self.merchant_country_code, dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, + is_external_vault_enabled, + external_vault_connector_details, }) } } diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs index 5ba75893787..d6600d674fc 100644 --- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs @@ -173,6 +173,17 @@ impl MerchantConnectorAccountTypeDetails { } } + pub fn get_connector_name_as_string(&self) -> String { + match self { + Self::MerchantConnectorAccount(merchant_connector_account) => { + merchant_connector_account.connector_name.to_string() + } + Self::MerchantConnectorDetails(merchant_connector_details) => { + merchant_connector_details.connector_name.to_string() + } + } + } + pub fn get_inner_db_merchant_connector_account(&self) -> Option<&MerchantConnectorAccount> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { @@ -257,6 +268,11 @@ impl MerchantConnectorAccount { self.connector_name.clone().to_string() } + #[cfg(feature = "v2")] + pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector { + self.connector_name + } + pub fn get_payment_merchant_connector_account_id_using_account_reference_id( &self, account_reference_id: String, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 59202837dc2..932244a986d 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -2559,3 +2559,70 @@ impl From<NetworkTokenData> for payment_methods::CardDetail { } } } + +#[cfg(feature = "v1")] +impl + From<( + payment_methods::CardDetail, + Option<&CardToken>, + Option<payment_methods::CoBadgedCardData>, + )> for Card +{ + fn from( + value: ( + payment_methods::CardDetail, + Option<&CardToken>, + Option<payment_methods::CoBadgedCardData>, + ), + ) -> Self { + let ( + payment_methods::CardDetail { + card_number, + card_exp_month, + card_exp_year, + card_holder_name, + nick_name, + card_network, + card_issuer, + card_issuing_country, + card_type, + }, + card_token_data, + co_badged_card_data, + ) = value; + + // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked + let name_on_card = if let Some(name) = card_holder_name.clone() { + use masking::ExposeInterface; + + if name.clone().expose().is_empty() { + card_token_data + .and_then(|token_data| token_data.card_holder_name.clone()) + .or(Some(name)) + } else { + card_holder_name + } + } else { + card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) + }; + + Self { + card_number, + card_exp_month, + card_exp_year, + card_holder_name: name_on_card, + card_cvc: card_token_data + .cloned() + .unwrap_or_default() + .card_cvc + .unwrap_or_default(), + card_issuer, + card_network, + card_type, + card_issuing_country, + bank_code: None, + nick_name, + co_badged_card_data, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index 003998d9ccc..e9ce9057692 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -37,11 +37,9 @@ use crate::{ type_encryption::{crypto_operation, CryptoOperation}, }; -#[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct VaultId(String); -#[cfg(any(feature = "v2", feature = "tokenization_v2"))] impl VaultId { pub fn get_string_repr(&self) -> &String { &self.0 @@ -88,7 +86,9 @@ pub struct PaymentMethod { pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: OptionalEncryptableValue, + pub vault_source_details: PaymentMethodVaultSourceDetails, } + #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct PaymentMethod { @@ -128,6 +128,7 @@ pub struct PaymentMethod { #[encrypt(ty = Value)] pub external_vault_token_data: Option<Encryptable<api_models::payment_methods::ExternalVaultTokenData>>, + pub vault_type: Option<storage_enums::VaultType>, } impl PaymentMethod { @@ -259,6 +260,7 @@ impl super::behaviour::Conversion for PaymentMethod { type DstType = diesel_models::payment_method::PaymentMethod; type NewDstType = diesel_models::payment_method::PaymentMethodNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + let (vault_type, external_vault_source) = self.vault_source_details.into(); Ok(Self::DstType { customer_id: self.customer_id, merchant_id: self.merchant_id, @@ -298,6 +300,8 @@ impl super::behaviour::Conversion for PaymentMethod { network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), + external_vault_source, + vault_type, }) } @@ -310,90 +314,115 @@ impl super::behaviour::Conversion for PaymentMethod { where Self: Sized, { - async { - Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - customer_id: item.customer_id, - merchant_id: item.merchant_id, - payment_method_id: item.payment_method_id, - accepted_currency: item.accepted_currency, - scheme: item.scheme, - token: item.token, - cardholder_name: item.cardholder_name, - issuer_name: item.issuer_name, - issuer_country: item.issuer_country, - payer_country: item.payer_country, - is_stored: item.is_stored, - swift_code: item.swift_code, - direct_debit_token: item.direct_debit_token, - created_at: item.created_at, - last_modified: item.last_modified, - payment_method: item.payment_method, - payment_method_type: item.payment_method_type, - payment_method_issuer: item.payment_method_issuer, - payment_method_issuer_code: item.payment_method_issuer_code, - metadata: item.metadata, - payment_method_data: item - .payment_method_data - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await?, - locker_id: item.locker_id, - last_used_at: item.last_used_at, - connector_mandate_details: item.connector_mandate_details, - customer_acceptance: item.customer_acceptance, - status: item.status, - network_transaction_id: item.network_transaction_id, - client_secret: item.client_secret, - payment_method_billing_address: item - .payment_method_billing_address - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await?, - updated_by: item.updated_by, - version: item.version, - network_token_requestor_reference_id: item.network_token_requestor_reference_id, - network_token_locker_id: item.network_token_locker_id, - network_token_payment_method_data: item - .network_token_payment_method_data - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await?, - }) + // Decrypt encrypted fields first + let ( + payment_method_data, + payment_method_billing_address, + network_token_payment_method_data, + ) = async { + let payment_method_data = item + .payment_method_data + .async_lift(|inner| async { + crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::DecryptOptional(inner), + key_manager_identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_optionaloperation()) + }) + .await?; + + let payment_method_billing_address = item + .payment_method_billing_address + .async_lift(|inner| async { + crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::DecryptOptional(inner), + key_manager_identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_optionaloperation()) + }) + .await?; + + let network_token_payment_method_data = item + .network_token_payment_method_data + .async_lift(|inner| async { + crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::DecryptOptional(inner), + key_manager_identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_optionaloperation()) + }) + .await?; + + Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>(( + payment_method_data, + payment_method_billing_address, + network_token_payment_method_data, + )) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment method data".to_string(), + })?; + + let vault_source_details = PaymentMethodVaultSourceDetails::try_from(( + item.vault_type, + item.external_vault_source, + ))?; + + // Construct the domain type + Ok(Self { + customer_id: item.customer_id, + merchant_id: item.merchant_id, + payment_method_id: item.payment_method_id, + accepted_currency: item.accepted_currency, + scheme: item.scheme, + token: item.token, + cardholder_name: item.cardholder_name, + issuer_name: item.issuer_name, + issuer_country: item.issuer_country, + payer_country: item.payer_country, + is_stored: item.is_stored, + swift_code: item.swift_code, + direct_debit_token: item.direct_debit_token, + created_at: item.created_at, + last_modified: item.last_modified, + payment_method: item.payment_method, + payment_method_type: item.payment_method_type, + payment_method_issuer: item.payment_method_issuer, + payment_method_issuer_code: item.payment_method_issuer_code, + metadata: item.metadata, + payment_method_data, + locker_id: item.locker_id, + last_used_at: item.last_used_at, + connector_mandate_details: item.connector_mandate_details, + customer_acceptance: item.customer_acceptance, + status: item.status, + network_transaction_id: item.network_transaction_id, + client_secret: item.client_secret, + payment_method_billing_address, + updated_by: item.updated_by, + version: item.version, + network_token_requestor_reference_id: item.network_token_requestor_reference_id, + network_token_locker_id: item.network_token_locker_id, + network_token_payment_method_data, + vault_source_details, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + let (vault_type, external_vault_source) = self.vault_source_details.into(); Ok(Self::NewDstType { customer_id: self.customer_id, merchant_id: self.merchant_id, @@ -433,6 +462,8 @@ impl super::behaviour::Conversion for PaymentMethod { network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), + external_vault_source, + vault_type, }) } } @@ -472,6 +503,7 @@ impl super::behaviour::Conversion for PaymentMethod { .map(|val| val.into()), external_vault_source: self.external_vault_source, external_vault_token_data: self.external_vault_token_data.map(|val| val.into()), + vault_type: self.vault_type, }) } @@ -577,6 +609,7 @@ impl super::behaviour::Conversion for PaymentMethod { network_token_payment_method_data, external_vault_source: storage_model.external_vault_source, external_vault_token_data, + vault_type: storage_model.vault_type, }) } .await @@ -614,6 +647,7 @@ impl super::behaviour::Conversion for PaymentMethod { .network_token_payment_method_data .map(|val| val.into()), external_vault_token_data: self.external_vault_token_data.map(|val| val.into()), + vault_type: self.vault_type, }) } } @@ -1081,6 +1115,68 @@ impl ForeignTryFrom<(&[payment_methods::PaymentMethodRecord], id_type::MerchantI } } +#[cfg(feature = "v1")] +#[derive(Clone, Debug, Default)] +pub enum PaymentMethodVaultSourceDetails { + ExternalVault { + external_vault_source: id_type::MerchantConnectorAccountId, + }, + #[default] + InternalVault, +} + +#[cfg(feature = "v1")] +impl + TryFrom<( + Option<storage_enums::VaultType>, + Option<id_type::MerchantConnectorAccountId>, + )> for PaymentMethodVaultSourceDetails +{ + type Error = error_stack::Report<ValidationError>; + fn try_from( + value: ( + Option<storage_enums::VaultType>, + Option<id_type::MerchantConnectorAccountId>, + ), + ) -> Result<Self, Self::Error> { + match value { + (Some(storage_enums::VaultType::External), Some(external_vault_source)) => { + Ok(Self::ExternalVault { + external_vault_source, + }) + } + (Some(storage_enums::VaultType::External), None) => { + Err(ValidationError::MissingRequiredField { + field_name: "external vault mca id".to_string(), + } + .into()) + } + (Some(storage_enums::VaultType::Internal), _) | (None, _) => Ok(Self::InternalVault), // defaulting to internal vault if vault type is none + } + } +} +#[cfg(feature = "v1")] +impl From<PaymentMethodVaultSourceDetails> + for ( + Option<storage_enums::VaultType>, + Option<id_type::MerchantConnectorAccountId>, + ) +{ + fn from(value: PaymentMethodVaultSourceDetails) -> Self { + match value { + PaymentMethodVaultSourceDetails::ExternalVault { + external_vault_source, + } => ( + Some(storage_enums::VaultType::External), + Some(external_vault_source), + ), + PaymentMethodVaultSourceDetails::InternalVault => { + (Some(storage_enums::VaultType::Internal), None) + } + } + } +} + #[cfg(feature = "v1")] #[cfg(test)] mod tests { @@ -1127,6 +1223,7 @@ mod tests { network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, + vault_source_details: Default::default(), }; payment_method.clone() } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 8b2a3300a3b..e52daa7fedb 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -381,6 +381,9 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::PaymentLinkSdkLabelType, api_models::enums::OrganizationType, api_models::enums::PaymentLinkShowSdkTerms, + api_models::enums::ExternalVaultEnabled, + api_models::enums::VaultSdk, + api_models::admin::ExternalVaultConnectorDetails, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, api_models::admin::ConnectorWalletDetails, diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rs index 095788fa368..47a91f84633 100644 --- a/crates/payment_methods/src/controller.rs +++ b/crates/payment_methods/src/controller.rs @@ -9,6 +9,8 @@ use common_enums::enums as common_enums; use common_utils::encryption; use common_utils::{crypto, ext_traits, id_type, type_name, types::keymanager}; use error_stack::ResultExt; +#[cfg(feature = "v1")] +use hyperswitch_domain_models::payment_methods::PaymentMethodVaultSourceDetails; use hyperswitch_domain_models::{merchant_key_store, payment_methods, type_encryption}; use masking::{PeekInterface, Secret}; #[cfg(feature = "v1")] @@ -54,6 +56,7 @@ pub trait PaymentMethodsController { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, + vault_source_details: Option<PaymentMethodVaultSourceDetails>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v1")] @@ -74,6 +77,7 @@ pub trait PaymentMethodsController { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, + vault_source_details: Option<PaymentMethodVaultSourceDetails>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v2")] diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs index 494e1987e21..086dccbc2fe 100644 --- a/crates/payment_methods/src/core/migration/payment_methods.rs +++ b/crates/payment_methods/src/core/migration/payment_methods.rs @@ -448,6 +448,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration( None, None, None, + Default::default(), ) .await?; migration_status.connector_mandate_details_migrated( @@ -615,6 +616,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, + vault_source_details: Default::default(), }, merchant_context.get_merchant_account().storage_scheme, ) diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 7047164f0c7..caa47dfea09 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3478,6 +3478,13 @@ impl ProfileCreateBridge for api::ProfileCreate { dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, always_enable_overcapture: self.always_enable_overcapture, + external_vault_details: domain::ExternalVaultDetails::try_from(( + self.is_external_vault_enabled, + self.external_vault_connector_details + .map(ForeignFrom::foreign_from), + )) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error while generating external vault details")?, })) } @@ -3966,7 +3973,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { .map(ForeignInto::foreign_into), card_testing_secret_key, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, - force_3ds_challenge: self.force_3ds_challenge, // + force_3ds_challenge: self.force_3ds_challenge, is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, @@ -3976,6 +3983,10 @@ impl ProfileUpdateBridge for api::ProfileUpdate { dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, always_enable_overcapture: self.always_enable_overcapture, + is_external_vault_enabled: self.is_external_vault_enabled, + external_vault_connector_details: self + .external_vault_connector_details + .map(ForeignInto::foreign_into), }, ))) } diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index 69b219f4ae0..1f94b9bd998 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -90,7 +90,6 @@ pub trait ConnectorErrorExt<T> { #[cfg(feature = "payouts")] #[track_caller] fn to_payout_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>; - #[cfg(feature = "v2")] #[track_caller] fn to_vault_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>; @@ -521,7 +520,6 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> }) } - #[cfg(feature = "v2")] fn to_vault_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> { self.map_err(|err| { let error = match err.current_context() { diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 06622842281..b07b89e1328 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -39,15 +39,13 @@ use error_stack::{report, ResultExt}; use futures::TryStreamExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; -use hyperswitch_domain_models::payments::{ - payment_attempt::PaymentAttempt, PaymentIntent, VaultData, -}; -#[cfg(feature = "v2")] use hyperswitch_domain_models::{ - payment_method_data, payment_methods as domain_payment_methods, + payments::{payment_attempt::PaymentAttempt, PaymentIntent, VaultData}, router_data_v2::flow_common_types::VaultConnectorFlowData, - router_flow_types::ExternalVaultInsertFlow, types::VaultRouterData, + router_flow_types::ExternalVaultInsertFlow, + types::VaultRouterData, }; +use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion; use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; use time::Duration; @@ -61,19 +59,13 @@ use super::{ #[cfg(feature = "v2")] use crate::{ configs::settings, - core::{ - payment_methods::transformers as pm_transforms, payments as payments_core, - tokenization as tokenization_core, utils as core_utils, - }, - db::errors::ConnectorErrorExt, - headers, logger, + core::{payment_methods::transformers as pm_transforms, tokenization as tokenization_core}, + headers, routes::{self, payment_methods as pm_routes}, - services::{connector_integration_interface::RouterDataConversion, encryption}, + services::encryption, types::{ - self, - api::{self, payment_methods::PaymentMethodCreateExt}, + api::PaymentMethodCreateExt, domain::types as domain_types, - payment_methods as pm_types, storage::{ephemeral_key, PaymentMethodListContext}, transformers::{ForeignFrom, ForeignTryFrom}, Tokenizable, @@ -84,13 +76,15 @@ use crate::{ consts, core::{ errors::{ProcessTrackerError, RouterResult}, - payments::helpers as payment_helpers, + payments::{self as payments_core, helpers as payment_helpers}, + utils as core_utils, }, - errors, + db::errors::ConnectorErrorExt, + errors, logger, routes::{app::StorageInterface, SessionState}, services, types::{ - domain, + self, api, domain, payment_methods as pm_types, storage::{self, enums as storage_enums}, }, }; @@ -1116,6 +1110,8 @@ pub async fn create_payment_method_proxy_card_core( Encryptable<hyperswitch_domain_models::address::Address>, >, ) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> { + use crate::core::payment_methods::vault::Vault; + let key_manager_state = &(state).into(); let external_vault_source = profile @@ -1171,6 +1167,10 @@ pub async fn create_payment_method_proxy_card_core( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse External vault token data")?; + let vault_type = external_vault_source + .is_some() + .then_some(common_enums::VaultType::External); + let payment_method = create_payment_method_for_confirm( state, customer_id, @@ -1184,6 +1184,7 @@ pub async fn create_payment_method_proxy_card_core( payment_method_billing_address, encrypted_payment_method_data, encrypted_external_vault_token_data, + vault_type, ) .await?; @@ -1699,7 +1700,7 @@ pub async fn generate_token_data_response( state: &SessionState, request: payment_methods::GetTokenDataRequest, profile: domain::Profile, - payment_method: &domain_payment_methods::PaymentMethod, + payment_method: &domain::PaymentMethod, ) -> RouterResult<api::TokenDataResponse> { let token_details = match request.token_type { common_enums::TokenDataType::NetworkToken => { @@ -1924,6 +1925,8 @@ pub async fn create_payment_method_for_intent( Encryptable<hyperswitch_domain_models::address::Address>, >, ) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { + use josekit::jwe::zip::deflate::DeflateJweCompression::Def; + let db = &*state.store; let current_time = common_utils::date_time::now(); @@ -1957,6 +1960,7 @@ pub async fn create_payment_method_for_intent( network_token_requestor_reference_id: None, external_vault_source: None, external_vault_token_data: None, + vault_type: None, }, storage_scheme, ) @@ -1987,6 +1991,7 @@ pub async fn create_payment_method_for_confirm( encrypted_external_vault_token_data: Option< Encryptable<payment_methods::ExternalVaultTokenData>, >, + vault_type: Option<common_enums::VaultType>, ) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*state.store; let key_manager_state = &state.into(); @@ -2021,6 +2026,7 @@ pub async fn create_payment_method_for_confirm( network_token_requestor_reference_id: None, external_vault_source, external_vault_token_data: encrypted_external_vault_token_data, + vault_type, }, storage_scheme, ) @@ -2039,9 +2045,9 @@ pub async fn get_external_vault_token( key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, payment_token: String, - vault_token: payment_method_data::VaultToken, + vault_token: domain::VaultToken, payment_method_type: &storage_enums::PaymentMethod, -) -> CustomResult<payment_method_data::ExternalVaultPaymentMethodData, errors::ApiErrorResponse> { +) -> CustomResult<domain::ExternalVaultPaymentMethodData, errors::ApiErrorResponse> { let db = &*state.store; let pm_token_data = @@ -2099,12 +2105,12 @@ pub async fn get_external_vault_token( fn convert_from_saved_payment_method_data( vault_additional_data: payment_methods::PaymentMethodsData, external_vault_token_data: payment_methods::ExternalVaultTokenData, - vault_token: payment_method_data::VaultToken, -) -> RouterResult<payment_method_data::ExternalVaultPaymentMethodData> { + vault_token: domain::VaultToken, +) -> RouterResult<domain::ExternalVaultPaymentMethodData> { match vault_additional_data { payment_methods::PaymentMethodsData::Card(card_details) => { - Ok(payment_method_data::ExternalVaultPaymentMethodData::Card( - Box::new(domain::ExternalVaultCard { + Ok(domain::ExternalVaultPaymentMethodData::Card(Box::new( + domain::ExternalVaultCard { card_number: external_vault_token_data.tokenized_card_number, card_exp_month: card_details.expiry_month.ok_or( errors::ApiErrorResponse::MissingRequiredField { @@ -2127,8 +2133,8 @@ fn convert_from_saved_payment_method_data( card_cvc: vault_token.card_cvc, co_badged_card_data: None, // Co-badged data is not supported in external vault bank_code: None, // Bank code is not stored in external vault - }), - )) + }, + ))) } payment_methods::PaymentMethodsData::BankDetails(_) | payment_methods::PaymentMethodsData::WalletDetails(_) => { @@ -2197,16 +2203,12 @@ pub async fn create_pm_additional_data_update( let encrypted_payment_method_data = pmd .map( |payment_method_vaulting_data| match payment_method_vaulting_data { - domain::PaymentMethodVaultingData::Card(card) => { - payment_method_data::PaymentMethodsData::Card( - payment_method_data::CardDetailsPaymentMethod::from(card.clone()), - ) - } + domain::PaymentMethodVaultingData::Card(card) => domain::PaymentMethodsData::Card( + domain::CardDetailsPaymentMethod::from(card.clone()), + ), domain::PaymentMethodVaultingData::NetworkToken(network_token) => { - payment_method_data::PaymentMethodsData::NetworkToken( - payment_method_data::NetworkTokenDetailsPaymentMethod::from( - network_token.clone(), - ), + domain::PaymentMethodsData::NetworkToken( + domain::NetworkTokenDetailsPaymentMethod::from(network_token.clone()), ) } }, @@ -2311,10 +2313,20 @@ pub async fn vault_payment_method_external( merchant_account: &domain::MerchantAccount, merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, ) -> RouterResult<pm_types::AddVaultResponse> { + let merchant_connector_account = match &merchant_connector_account { + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { + Ok(mca.as_ref()) + } + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("MerchantConnectorDetails not supported for vault operations")) + } + }?; + let router_data = core_utils::construct_vault_router_data( state, - merchant_account, - &merchant_connector_account, + merchant_account.get_id(), + merchant_connector_account, Some(pmd.clone()), None, None, @@ -2327,16 +2339,68 @@ pub async fn vault_payment_method_external( "Cannot construct router data for making the external vault insert api call", )?; - let connector_name = merchant_connector_account - .get_connector_name() - .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call + let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, - &connector_name, + connector_name, api::GetToken::Connector, - merchant_connector_account.get_mca_id(), + Some(merchant_connector_account.get_id()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get the connector data")?; + + let connector_integration: services::BoxedVaultConnectorIntegrationInterface< + ExternalVaultInsertFlow, + types::VaultRequestData, + types::VaultResponseData, + > = connector_data.connector.get_connector_integration(); + + let router_data_resp = services::execute_connector_processing_step( + state, + connector_integration, + &old_router_data, + payments_core::CallConnectorAction::Trigger, + None, + None, + ) + .await + .to_vault_failed_response()?; + + get_vault_response_for_insert_payment_method_data(router_data_resp) +} + +#[cfg(feature = "v1")] +#[instrument(skip_all)] +pub async fn vault_payment_method_external_v1( + state: &SessionState, + pmd: &hyperswitch_domain_models::vault::PaymentMethodVaultingData, + merchant_account: &domain::MerchantAccount, + merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, +) -> RouterResult<pm_types::AddVaultResponse> { + let router_data = core_utils::construct_vault_router_data( + state, + merchant_account.get_id(), + &merchant_connector_account, + Some(pmd.clone()), + None, + None, + ) + .await?; + + let old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Cannot construct router data for making the external vault insert api call", + )?; + + let connector_name = merchant_connector_account.get_connector_name_as_string(); + + let connector_data = api::ConnectorData::get_external_vault_connector_by_name( + &state.conf.connectors, + connector_name, + api::GetToken::Connector, + Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; @@ -2361,7 +2425,6 @@ pub async fn vault_payment_method_external( get_vault_response_for_insert_payment_method_data(router_data_resp) } -#[cfg(feature = "v2")] pub fn get_vault_response_for_insert_payment_method_data<F>( router_data: VaultRouterData<F>, ) -> RouterResult<pm_types::AddVaultResponse> { @@ -2370,11 +2433,18 @@ pub fn get_vault_response_for_insert_payment_method_data<F>( types::VaultResponseData::ExternalVaultInsertResponse { connector_vault_id, fingerprint_id, - } => Ok(pm_types::AddVaultResponse { - vault_id: domain::VaultId::generate(connector_vault_id), - fingerprint_id: Some(fingerprint_id), - entity_id: None, - }), + } => { + #[cfg(feature = "v2")] + let vault_id = domain::VaultId::generate(connector_vault_id); + #[cfg(not(feature = "v2"))] + let vault_id = connector_vault_id; + + Ok(pm_types::AddVaultResponse { + vault_id, + fingerprint_id: Some(fingerprint_id), + entity_id: None, + }) + } types::VaultResponseData::ExternalVaultRetrieveResponse { .. } | types::VaultResponseData::ExternalVaultDeleteResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { @@ -2701,7 +2771,7 @@ pub async fn retrieve_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()), + domain::SingleUseTokenKey::store_key(&pm_id.clone()), ) .await .unwrap_or_default(); @@ -3686,7 +3756,7 @@ async fn create_single_use_tokenization_flow( .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_data: domain::PaymentMethodData::try_from( payment_method_create_request.payment_method_data.clone(), ) .change_context(errors::ApiErrorResponse::MissingRequiredField { @@ -3793,12 +3863,12 @@ async fn create_single_use_tokenization_flow( } })?; - let value = payment_method_data::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token( - token_response.clone().into(), - connector_id.clone() - ); + let value = domain::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); + let key = domain::SingleUseTokenKey::store_key(&payment_method.id); add_single_use_token_to_store(&state, key, value) .await @@ -3811,8 +3881,8 @@ async fn create_single_use_tokenization_flow( #[cfg(feature = "v2")] async fn add_single_use_token_to_store( state: &SessionState, - key: payment_method_data::SingleUseTokenKey, - value: payment_method_data::SingleUsePaymentMethodToken, + key: domain::SingleUseTokenKey, + value: domain::SingleUsePaymentMethodToken, ) -> CustomResult<(), errors::StorageError> { let redis_connection = state .store @@ -3821,7 +3891,7 @@ async fn add_single_use_token_to_store( redis_connection .serialize_and_set_key_with_expiry( - &payment_method_data::SingleUseTokenKey::get_store_key(&key).into(), + &domain::SingleUseTokenKey::get_store_key(&key).into(), value, consts::DEFAULT_PAYMENT_METHOD_STORE_TTL, ) @@ -3834,16 +3904,16 @@ async fn add_single_use_token_to_store( #[cfg(feature = "v2")] async fn get_single_use_token_from_store( state: &SessionState, - key: payment_method_data::SingleUseTokenKey, -) -> CustomResult<Option<payment_method_data::SingleUsePaymentMethodToken>, errors::StorageError> { + key: domain::SingleUseTokenKey, +) -> CustomResult<Option<domain::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(), + .get_and_deserialize_key::<Option<domain::SingleUsePaymentMethodToken>>( + &domain::SingleUseTokenKey::get_store_key(&key).into(), "SingleUsePaymentMethodToken", ) .await diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 322557129d4..ac225861b45 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -131,6 +131,7 @@ impl PaymentMethodsController for PmCards<'_> { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, + vault_source_details: Option<domain::PaymentMethodVaultSourceDetails>, ) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*self.state.store; let customer = db @@ -190,6 +191,8 @@ impl PaymentMethodsController for PmCards<'_> { network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, + vault_source_details: vault_source_details + .unwrap_or(domain::PaymentMethodVaultSourceDetails::InternalVault), }, self.merchant_context.get_merchant_account().storage_scheme, ) @@ -320,6 +323,7 @@ impl PaymentMethodsController for PmCards<'_> { None, None, None, + Default::default(), ) .await } else { @@ -464,6 +468,7 @@ impl PaymentMethodsController for PmCards<'_> { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, + vault_source_details: Option<domain::PaymentMethodVaultSourceDetails>, ) -> errors::RouterResult<domain::PaymentMethod> { let pm_card_details = resp.card.clone().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) @@ -497,6 +502,7 @@ impl PaymentMethodsController for PmCards<'_> { network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, + vault_source_details, ) .await } @@ -1298,6 +1304,7 @@ impl PaymentMethodsController for PmCards<'_> { None, None, None, + Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault source and type ) .await?; @@ -1372,6 +1379,7 @@ pub async fn get_client_secret_or_add_payment_method( None, None, None, + Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault type ) .await?; diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rs index 905d2d3a126..8b405947af9 100644 --- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs @@ -596,6 +596,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> { network_token_details.1.clone(), Some(stored_locker_resp.store_token_resp.card_reference.clone()), Some(enc_token_data), + Default::default(), // this method is used only for card bulk tokenization, and currently external vault is not supported for this hence passing Default i.e. InternalVault ) .await } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 7e2c5876ac8..771df3d97c7 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -9,10 +9,11 @@ use common_utils::{ }; use error_stack::{report, ResultExt}; #[cfg(feature = "v2")] +use hyperswitch_domain_models::router_flow_types::{ + ExternalVaultDeleteFlow, ExternalVaultRetrieveFlow, +}; use hyperswitch_domain_models::{ - router_data_v2::flow_common_types::VaultConnectorFlowData, - router_flow_types::{ExternalVaultDeleteFlow, ExternalVaultRetrieveFlow}, - types::VaultRouterData, + router_data_v2::flow_common_types::VaultConnectorFlowData, types::VaultRouterData, }; use masking::PeekInterface; use router_env::{instrument, tracing}; @@ -22,11 +23,15 @@ use scheduler::{types::process_data, utils as process_tracker_utils}; use crate::types::api::payouts; use crate::{ consts, - core::errors::{self, CustomResult, RouterResult}, + core::{ + errors::{self, ConnectorErrorExt, CustomResult, RouterResult}, + payments, utils as core_utils, + }, db, logger, routes::{self, metrics}, + services::{self, connector_integration_interface::RouterDataConversion}, types::{ - api, domain, + self, api, domain, storage::{self, enums}, }, utils::StringExt, @@ -34,16 +39,12 @@ use crate::{ #[cfg(feature = "v2")] use crate::{ core::{ - errors::ConnectorErrorExt, errors::StorageErrorExt, payment_methods::{transformers as pm_transforms, utils}, payments::{self as payments_core, helpers as payment_helpers}, - utils as core_utils, }, - headers, - services::{self, connector_integration_interface::RouterDataConversion}, - settings, - types::{self, payment_methods as pm_types}, + headers, settings, + types::payment_methods as pm_types, utils::{ext_traits::OptionExt, ConnectorResponseExt}, }; @@ -1396,10 +1397,20 @@ pub async fn retrieve_payment_method_from_vault_external( .clone() .map(|id| id.get_string_repr().to_owned()); + let merchant_connector_account = match &merchant_connector_account { + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { + Ok(mca.as_ref()) + } + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("MerchantConnectorDetails not supported for vault operations")) + } + }?; + let router_data = core_utils::construct_vault_router_data( state, - merchant_account, - &merchant_connector_account, + merchant_account.get_id(), + merchant_connector_account, None, connector_vault_id, None, @@ -1412,16 +1423,13 @@ pub async fn retrieve_payment_method_from_vault_external( "Cannot construct router data for making the external vault retrieve api call", )?; - let connector_name = merchant_connector_account - .get_connector_name() - .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call + let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, - &connector_name, + connector_name, api::GetToken::Connector, - merchant_connector_account.get_mca_id(), + Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; @@ -1744,10 +1752,21 @@ pub async fn delete_payment_method_data_from_vault_external( ) -> RouterResult<pm_types::VaultDeleteResponse> { let connector_vault_id = vault_id.get_string_repr().to_owned(); + // Extract MerchantConnectorAccount from the enum + let merchant_connector_account = match &merchant_connector_account { + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { + Ok(mca.as_ref()) + } + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("MerchantConnectorDetails not supported for vault operations")) + } + }?; + let router_data = core_utils::construct_vault_router_data( state, - merchant_account, - &merchant_connector_account, + merchant_account.get_id(), + merchant_connector_account, None, Some(connector_vault_id), None, @@ -1760,16 +1779,13 @@ pub async fn delete_payment_method_data_from_vault_external( "Cannot construct router data for making the external vault delete api call", )?; - let connector_name = merchant_connector_account - .get_connector_name() - .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call + let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, - &connector_name, + connector_name, api::GetToken::Connector, - merchant_connector_account.get_mca_id(), + Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; @@ -1875,6 +1891,86 @@ pub async fn delete_payment_method_data_from_vault( } } +#[cfg(feature = "v1")] +#[instrument(skip_all)] +pub async fn retrieve_payment_method_from_vault_external_v1( + state: &routes::SessionState, + merchant_id: &id_type::MerchantId, + pm: &domain::PaymentMethod, + merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, +) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> { + let connector_vault_id = pm.locker_id.clone().map(|id| id.to_string()); + + let router_data = core_utils::construct_vault_router_data( + state, + merchant_id, + &merchant_connector_account, + None, + connector_vault_id, + None, + ) + .await?; + + let old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Cannot construct router data for making the external vault retrieve api call", + )?; + + let connector_name = merchant_connector_account.get_connector_name_as_string(); + + let connector_data = api::ConnectorData::get_external_vault_connector_by_name( + &state.conf.connectors, + connector_name, + api::GetToken::Connector, + Some(merchant_connector_account.get_id()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get the connector data")?; + + let connector_integration: services::BoxedVaultConnectorIntegrationInterface< + hyperswitch_domain_models::router_flow_types::ExternalVaultRetrieveFlow, + types::VaultRequestData, + types::VaultResponseData, + > = connector_data.connector.get_connector_integration(); + + let router_data_resp = services::execute_connector_processing_step( + state, + connector_integration, + &old_router_data, + payments::CallConnectorAction::Trigger, + None, + None, + ) + .await + .to_vault_failed_response()?; + + get_vault_response_for_retrieve_payment_method_data_v1(router_data_resp) +} + +pub fn get_vault_response_for_retrieve_payment_method_data_v1<F>( + router_data: VaultRouterData<F>, +) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> { + match router_data.response { + Ok(response) => match response { + types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => { + Ok(vault_data) + } + types::VaultResponseData::ExternalVaultInsertResponse { .. } + | types::VaultResponseData::ExternalVaultDeleteResponse { .. } + | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid Vault Response")) + } + }, + Err(err) => { + logger::error!("Failed to retrieve payment method: {:?}", err); + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve payment method")) + } + } +} + // ********************************************** PROCESS TRACKER ********************************************** pub async fn add_delete_tokenized_data_task( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 37703cd1bec..044466523d4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2196,7 +2196,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token( _payment_method_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&domain::CardToken>, - _merchant_key_store: &domain::MerchantKeyStore, + merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, mandate_id: Option<api_models::payments::MandateIds>, payment_method_info: domain::PaymentMethod, @@ -2250,14 +2250,16 @@ pub async fn retrieve_payment_method_data_with_permanent_token( .and_then(|vault_data| vault_data.get_card_vault_data()) .map(Ok) .async_unwrap_or_else(|| async { - fetch_card_details_from_locker( + Box::pin(fetch_card_details_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, card_token_data, co_badged_card_data, - ) + payment_method_info, + merchant_key_store, + )) .await }) .await?; @@ -2301,14 +2303,16 @@ pub async fn retrieve_payment_method_data_with_permanent_token( .and_then(|vault_data| vault_data.get_card_vault_data()) .map(Ok) .async_unwrap_or_else(|| async { - fetch_card_details_from_locker( + Box::pin(fetch_card_details_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, card_token_data, co_badged_card_data, - ) + payment_method_info, + merchant_key_store, + )) .await }) .await?, @@ -2363,7 +2367,7 @@ pub async fn retrieve_card_with_permanent_token_for_external_authentication( message: "no customer id provided for the payment".to_string(), })?; Ok(domain::PaymentMethodData::Card( - fetch_card_details_from_locker( + fetch_card_details_from_internal_locker( state, customer_id, &payment_intent.merchant_id, @@ -2378,6 +2382,7 @@ pub async fn retrieve_card_with_permanent_token_for_external_authentication( } #[cfg(feature = "v1")] +#[allow(clippy::too_many_arguments)] pub async fn fetch_card_details_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, @@ -2385,6 +2390,46 @@ pub async fn fetch_card_details_from_locker( locker_id: &str, card_token_data: Option<&domain::CardToken>, co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, + payment_method_info: domain::PaymentMethod, + merchant_key_store: &domain::MerchantKeyStore, +) -> RouterResult<domain::Card> { + match &payment_method_info.vault_source_details.clone() { + domain::PaymentMethodVaultSourceDetails::ExternalVault { + ref external_vault_source, + } => { + fetch_card_details_from_external_vault( + state, + merchant_id, + card_token_data, + co_badged_card_data, + payment_method_info, + merchant_key_store, + external_vault_source, + ) + .await + } + domain::PaymentMethodVaultSourceDetails::InternalVault => { + fetch_card_details_from_internal_locker( + state, + customer_id, + merchant_id, + locker_id, + card_token_data, + co_badged_card_data, + ) + .await + } + } +} + +#[cfg(feature = "v1")] +pub async fn fetch_card_details_from_internal_locker( + state: &SessionState, + customer_id: &id_type::CustomerId, + merchant_id: &id_type::MerchantId, + locker_id: &str, + card_token_data: Option<&domain::CardToken>, + co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, ) -> RouterResult<domain::Card> { logger::debug!("Fetching card details from locker"); let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) @@ -2434,6 +2479,45 @@ pub async fn fetch_card_details_from_locker( Ok(domain::Card::from((api_card, co_badged_card_data))) } +#[cfg(feature = "v1")] +pub async fn fetch_card_details_from_external_vault( + state: &SessionState, + merchant_id: &id_type::MerchantId, + card_token_data: Option<&domain::CardToken>, + co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, + payment_method_info: domain::PaymentMethod, + merchant_key_store: &domain::MerchantKeyStore, + external_vault_mca_id: &id_type::MerchantConnectorAccountId, +) -> RouterResult<domain::Card> { + let key_manager_state = &state.into(); + + let merchant_connector_account_details = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, + merchant_id, + external_vault_mca_id, + merchant_key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: external_vault_mca_id.get_string_repr().to_string(), + })?; + + let vault_resp = vault::retrieve_payment_method_from_vault_external_v1( + state, + merchant_id, + &payment_method_info, + merchant_connector_account_details, + ) + .await?; + + match vault_resp { + hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card) => Ok( + domain::Card::from((card, card_token_data, co_badged_card_data)), + ), + } +} #[cfg(feature = "v1")] pub async fn fetch_network_token_details_from_locker( state: &SessionState, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 759db4ef963..3ee7e0a1d53 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -15,6 +15,7 @@ use common_utils::{ metrics::utils::record_operation_time, pii, }; +use diesel_models::business_profile::ExternalVaultConnectorDetails; use error_stack::{report, ResultExt}; #[cfg(feature = "v1")] use hyperswitch_domain_models::{ @@ -26,6 +27,8 @@ use masking::{ExposeInterface, Secret}; use router_env::{instrument, tracing}; use super::helpers; +#[cfg(feature = "v1")] +use crate::core::payment_methods::vault_payment_method_external_v1; use crate::{ consts, core::{ @@ -50,6 +53,38 @@ use crate::{ utils::{generate_id, OptionExt}, }; +#[cfg(feature = "v1")] +async fn save_in_locker( + state: &SessionState, + merchant_context: &domain::MerchantContext, + payment_method_request: api::PaymentMethodCreate, + card_detail: Option<api::CardDetail>, + business_profile: &domain::Profile, +) -> RouterResult<( + api_models::payment_methods::PaymentMethodResponse, + Option<payment_methods::transformers::DataDuplicationCheck>, +)> { + match &business_profile.external_vault_details { + domain::ExternalVaultDetails::ExternalVaultEnabled(external_vault_details) => { + logger::info!("External vault is enabled, using vault_payment_method_external_v1"); + + Box::pin(save_in_locker_external( + state, + merchant_context, + payment_method_request, + card_detail, + external_vault_details, + )) + .await + } + domain::ExternalVaultDetails::Skip => { + // Use internal vault (locker) + save_in_locker_internal(state, merchant_context, payment_method_request, card_detail) + .await + } + } +} + pub struct SavePaymentMethodData<Req> { request: Req, response: Result<types::PaymentsResponseData, types::ErrorResponse>, @@ -241,6 +276,7 @@ where merchant_context, payment_method_create_request.clone(), is_network_tokenization_enabled, + business_profile, ) .await? }; @@ -333,6 +369,21 @@ where let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; + let (external_vault_details, vault_type) = match &business_profile.external_vault_details{ + hyperswitch_domain_models::business_profile::ExternalVaultDetails::ExternalVaultEnabled(external_vault_connector_details) => { + (Some(external_vault_connector_details), Some(common_enums::VaultType::External)) + }, + hyperswitch_domain_models::business_profile::ExternalVaultDetails::Skip => (None, Some(common_enums::VaultType::Internal)), + }; + let external_vault_mca_id = external_vault_details + .map(|connector_details| connector_details.vault_connector_id.clone()); + + let vault_source_details = domain::PaymentMethodVaultSourceDetails::try_from(( + vault_type, + external_vault_mca_id, + )) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create vault source details")?; match duplication_check { Some(duplication_check) => match duplication_check { @@ -425,6 +476,7 @@ where network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, + Some(vault_source_details), ) .await } else { @@ -544,6 +596,7 @@ where network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, + Some(vault_source_details), ) .await } else { @@ -765,6 +818,7 @@ where network_token_requestor_ref_id.clone(), network_token_locker_id, pm_network_token_data_encrypted, + Some(vault_source_details), ) .await?; @@ -1043,7 +1097,7 @@ async fn skip_saving_card_in_locker( } #[cfg(feature = "v1")] -pub async fn save_in_locker( +pub async fn save_in_locker_internal( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, @@ -1093,8 +1147,100 @@ pub async fn save_in_locker( } } +#[cfg(feature = "v1")] +pub async fn save_in_locker_external( + state: &SessionState, + merchant_context: &domain::MerchantContext, + payment_method_request: api::PaymentMethodCreate, + card_detail: Option<api::CardDetail>, + external_vault_connector_details: &ExternalVaultConnectorDetails, +) -> RouterResult<( + api_models::payment_methods::PaymentMethodResponse, + Option<payment_methods::transformers::DataDuplicationCheck>, +)> { + let customer_id = payment_method_request + .customer_id + .clone() + .get_required_value("customer_id")?; + // For external vault, we need to convert the card data to PaymentMethodVaultingData + if let Some(card) = card_detail { + let payment_method_vaulting_data = + hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card.clone()); + + let external_vault_mca_id = external_vault_connector_details.vault_connector_id.clone(); + + let key_manager_state = &state.into(); + + let merchant_connector_account_details = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, + merchant_context.get_merchant_account().get_id(), + &external_vault_mca_id, + merchant_context.get_merchant_key_store(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: external_vault_mca_id.get_string_repr().to_string(), + })?; + + // Call vault_payment_method_external_v1 + let vault_response = vault_payment_method_external_v1( + state, + &payment_method_vaulting_data, + merchant_context.get_merchant_account(), + merchant_connector_account_details, + ) + .await?; + + let payment_method_id = vault_response.vault_id.to_string().to_owned(); + let card_detail = CardDetailFromLocker::from(card); + + let pm_resp = api::PaymentMethodResponse { + merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), + customer_id: Some(customer_id), + payment_method_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: Some(card_detail), + recurring_enabled: Some(false), + installment_payment_enabled: Some(false), + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + metadata: None, + created: Some(common_utils::date_time::now()), + #[cfg(feature = "payouts")] + bank_transfer: None, + last_used_at: Some(common_utils::date_time::now()), + client_secret: None, + }; + + Ok((pm_resp, None)) + } else { + //Similar implementation is done for save in locker internal + let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); + let payment_method_response = api::PaymentMethodResponse { + merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), + customer_id: Some(customer_id), + payment_method_id: pm_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + #[cfg(feature = "payouts")] + bank_transfer: None, + card: None, + metadata: None, + created: Some(common_utils::date_time::now()), + recurring_enabled: Some(false), + installment_payment_enabled: Some(false), + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] + last_used_at: Some(common_utils::date_time::now()), + client_secret: None, + }; + Ok((payment_method_response, None)) + } +} + #[cfg(feature = "v2")] -pub async fn save_in_locker( +pub async fn save_in_locker_internal( _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_method_request: api::PaymentMethodCreate, @@ -1595,6 +1741,7 @@ pub async fn save_card_and_network_token_in_locker( merchant_context: &domain::MerchantContext, payment_method_create_request: api::PaymentMethodCreate, is_network_tokenization_enabled: bool, + business_profile: &domain::Profile, ) -> RouterResult<( ( api_models::payment_methods::PaymentMethodResponse, @@ -1633,6 +1780,7 @@ pub async fn save_card_and_network_token_in_locker( merchant_context, payment_method_create_request.to_owned(), Some(card_data), + business_profile, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1654,7 +1802,7 @@ pub async fn save_card_and_network_token_in_locker( ); if payment_method_status == common_enums::PaymentMethodStatus::Active { - let (res, dc) = Box::pin(save_in_locker( + let (res, dc) = Box::pin(save_in_locker_internal( state, merchant_context, payment_method_create_request.to_owned(), @@ -1699,7 +1847,7 @@ pub async fn save_card_and_network_token_in_locker( ) .await; } - let (res, dc) = Box::pin(save_in_locker( + let (res, dc) = Box::pin(save_in_locker_internal( state, merchant_context, payment_method_create_request.to_owned(), @@ -1713,13 +1861,17 @@ pub async fn save_card_and_network_token_in_locker( } } _ => { + let card_data = payment_method_create_request.card.clone(); let (res, dc) = Box::pin(save_in_locker( state, merchant_context, payment_method_create_request.to_owned(), - None, + card_data, + business_profile, )) - .await?; + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Card In Locker Failed")?; if is_network_tokenization_enabled { match &payment_method_data { diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rs index 10b965786e5..228b72bd9a8 100644 --- a/crates/router/src/core/payments/vault_session.rs +++ b/crates/router/src/core/payments/vault_session.rs @@ -2,7 +2,7 @@ use std::{fmt::Debug, str::FromStr}; pub use common_enums::enums::CallConnectorAction; use common_utils::id_type; -use error_stack::ResultExt; +use error_stack::{report, ResultExt}; pub use hyperswitch_domain_models::{ mandates::MandateData, payment_address::PaymentAddress, @@ -349,11 +349,20 @@ where api::GetToken::Connector, merchant_connector_account_type.get_mca_id(), )?; + let merchant_connector_account = match &merchant_connector_account_type { + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { + Ok(mca.as_ref()) + } + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("MerchantConnectorDetails not supported for vault operations")) + } + }?; let mut router_data = core_utils::construct_vault_router_data( state, - merchant_context.get_merchant_account(), - merchant_connector_account_type, + merchant_context.get_merchant_account().get_id(), + merchant_connector_account, None, None, connector_customer_id, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index c80a089e5d4..00bcc7a26f6 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -646,6 +646,7 @@ pub async fn save_payout_data_to_locker( None, None, None, + Default::default(), ) .await?, ); diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 0ed160784cb..9823cc94d7e 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -529,6 +529,7 @@ async fn store_bank_details_in_payment_methods( network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, + vault_source_details: Default::default(), }; new_entries.push(pm_new); diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 432a148fc41..38b9566d359 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -19,12 +19,12 @@ use error_stack::{report, ResultExt}; #[cfg(feature = "v2")] use hyperswitch_domain_models::types::VaultRouterData; use hyperswitch_domain_models::{ - merchant_connector_account::MerchantConnectorAccount, payment_address::PaymentAddress, - router_data::ErrorResponse, router_request_types, types::OrderDetailsWithAmount, -}; -#[cfg(feature = "v2")] -use hyperswitch_domain_models::{ - router_data_v2::flow_common_types::VaultConnectorFlowData, types::VaultRouterDataV2, + merchant_connector_account::MerchantConnectorAccount, + payment_address::PaymentAddress, + router_data::ErrorResponse, + router_data_v2::flow_common_types::VaultConnectorFlowData, + router_request_types, + types::{OrderDetailsWithAmount, VaultRouterDataV2}, }; use hyperswitch_interfaces::api::ConnectorSpecifications; #[cfg(feature = "v2")] @@ -2350,25 +2350,22 @@ pub(crate) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::De } } -#[cfg(feature = "v2")] pub async fn construct_vault_router_data<F>( state: &SessionState, - merchant_account: &domain::MerchantAccount, - merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, - payment_method_vaulting_data: Option<domain::PaymentMethodVaultingData>, + merchant_id: &common_utils::id_type::MerchantId, + merchant_connector_account: &MerchantConnectorAccount, + payment_method_vaulting_data: Option< + hyperswitch_domain_models::vault::PaymentMethodVaultingData, + >, connector_vault_id: Option<String>, connector_customer_id: Option<String>, ) -> RouterResult<VaultRouterDataV2<F>> { - let connector_name = merchant_connector_account - .get_connector_name() - .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 = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError)?; let resource_common_data = VaultConnectorFlowData { - merchant_id: merchant_account.get_id().to_owned(), + merchant_id: merchant_id.to_owned(), }; let router_data = types::RouterDataV2 { diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index 94adf92e3df..a5ca7e29922 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -1291,6 +1291,7 @@ mod tests { dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, + external_vault_details: domain::ExternalVaultDetails::Skip, }); let business_profile = state diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 0e8cb60ff81..3f96235c43f 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -172,6 +172,8 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { let card_testing_guard_config = item .card_testing_guard_config .or(Some(CardTestingGuardConfig::default())); + let (is_external_vault_enabled, external_vault_connector_details) = + item.external_vault_details.into(); Ok(Self { merchant_id: item.merchant_id, @@ -235,6 +237,9 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { dispute_polling_interval: item.dispute_polling_interval, is_manual_retry_enabled: item.is_manual_retry_enabled, always_enable_overcapture: item.always_enable_overcapture, + is_external_vault_enabled, + external_vault_connector_details: external_vault_connector_details + .map(ForeignFrom::foreign_from), }) } } @@ -495,5 +500,13 @@ pub async fn create_profile_from_merchant_account( dispute_polling_interval: request.dispute_polling_interval, is_manual_retry_enabled: request.is_manual_retry_enabled, always_enable_overcapture: request.always_enable_overcapture, + external_vault_details: domain::ExternalVaultDetails::try_from(( + request.is_external_vault_enabled, + request + .external_vault_connector_details + .map(ForeignInto::foreign_into), + )) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error while generating external_vault_details")?, })) } diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index adef987b03d..f8ee7842fd9 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -76,21 +76,19 @@ impl ConnectorData { }) } - #[cfg(feature = "v2")] pub fn get_external_vault_connector_by_name( _connectors: &Connectors, - connector: &enums::Connector, + connector: String, connector_type: GetToken, connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<Self, errors::ApiErrorResponse> { - let connector_enum = Self::convert_connector(&connector.to_string())?; - let external_vault_connector_name = - 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_enum = Self::convert_connector(&connector)?; + let external_vault_connector_name = enums::VaultConnectors::from_str(&connector) + .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 = enums::Connector::from(external_vault_connector_name); Ok(Self { connector: connector_enum, diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs index c5efabce398..29cbe3e735d 100644 --- a/crates/router/src/types/domain.rs +++ b/crates/router/src/types/domain.rs @@ -10,12 +10,20 @@ mod merchant_account { pub use hyperswitch_domain_models::merchant_account::*; } +#[cfg(feature = "v2")] mod business_profile { pub use hyperswitch_domain_models::business_profile::{ Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate, }; } +#[cfg(feature = "v1")] +mod business_profile { + pub use hyperswitch_domain_models::business_profile::{ + ExternalVaultDetails, Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate, + }; +} + pub mod merchant_context { pub use hyperswitch_domain_models::merchant_context::{Context, MerchantContext}; } diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs index 88d60e7b3d4..45ee498967b 100644 --- a/crates/router/src/types/payment_methods.rs +++ b/crates/router/src/types/payment_methods.rs @@ -51,11 +51,16 @@ pub struct AddVaultRequest<D> { pub ttl: i64, } -#[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultResponse { + #[cfg(feature = "v2")] pub entity_id: Option<id_type::GlobalCustomerId>, + #[cfg(feature = "v1")] + pub entity_id: Option<id_type::CustomerId>, + #[cfg(feature = "v2")] pub vault_id: domain::VaultId, + #[cfg(feature = "v1")] + pub vault_id: String, pub fingerprint_id: Option<String>, } diff --git a/migrations/2025-09-20-190742_add_external_vault_source_in_payment_method_and_is_external_vault_enabled_in_profile/down.sql b/migrations/2025-09-20-190742_add_external_vault_source_in_payment_method_and_is_external_vault_enabled_in_profile/down.sql new file mode 100644 index 00000000000..2763c4865e7 --- /dev/null +++ b/migrations/2025-09-20-190742_add_external_vault_source_in_payment_method_and_is_external_vault_enabled_in_profile/down.sql @@ -0,0 +1,9 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_methods DROP COLUMN IF EXISTS external_vault_source; + +ALTER TABLE payment_methods DROP COLUMN IF EXISTS vault_type; + +-- This file should undo anything in `up.sql` +ALTER TABLE business_profile DROP COLUMN IF EXISTS external_vault_mode; + +ALTER TABLE business_profile DROP COLUMN IF EXISTS external_vault_connector_details; \ No newline at end of file diff --git a/migrations/2025-09-20-190742_add_external_vault_source_in_payment_method_and_is_external_vault_enabled_in_profile/up.sql b/migrations/2025-09-20-190742_add_external_vault_source_in_payment_method_and_is_external_vault_enabled_in_profile/up.sql new file mode 100644 index 00000000000..503b8d3b3e9 --- /dev/null +++ b/migrations/2025-09-20-190742_add_external_vault_source_in_payment_method_and_is_external_vault_enabled_in_profile/up.sql @@ -0,0 +1,11 @@ +-- Your SQL goes here +ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS external_vault_source VARCHAR(64); + +ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS vault_type VARCHAR(64); + +-- Your SQL goes here +ALTER TABLE business_profile +ADD COLUMN IF NOT EXISTS is_external_vault_enabled BOOLEAN; + +ALTER TABLE business_profile +ADD COLUMN IF NOT EXISTS external_vault_connector_details JSONB; \ No newline at end of file
2025-09-04T07:51:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add external vault support in v1 payments flow. Currently we only save card in hs-card-vault Added new support to save card in external vault based merchant-profile configuration. Changes in code - During First CIT (fresh card for a customer c1 - setup future usage - on_session with customer acceptance) - based on profile level config, vault is decided, vault creds are fetched from MCA. payment method data is stored in respective vault. During Repeat CIT (Saved card for a customer c1 - payment token for c1) - based on pm entry - vault type, and vault mca id, if external, mca creds are fetched, if internal, default flow. DB changes - In business profile in api level & db level- ``` is_external_vault_enabled: Option<bool>, //Indicates if external vault is enabled or not. external_vault_connector_details: Option<ExternalVaultConnectorDetails>,// holds the active External Vault Connector Details ``` In Payment method table in db level (diesel model) - ``` pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, //holds the mca of external vault with which payment method data has been stored pub vault_type: Option<storage_enums::VaultType>, //enum variant whether it is ext vault or internal vault ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create Vault Connector MCA (Eg - VGS) ``` curl --location 'http://localhost:8080/account/merchant_1758632854/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jN7RVfxJgyz3GB7OASKFved09yY2lA17xEJSBbj47tBN03inP9rCADUooCF5Ozz6' \ --data '{ "connector_type": "vault_processor", "connector_name": "vgs", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "api key", "key1": "key 1", "api_secret": "api_secret" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ ], "metadata": { "endpoint_prefix": "ghjg", "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" } } ], "merchant_info": { "merchant_name": "Narayan Bhat" } } }, "connector_webhook_details": { "merchant_secret": "7091687210DF6DCA38B2E670B3D68EB53516A26CA85590E29024FFBD7CD23980" }, "profile_id":"pro_KH7MujUjH2miLhfzGlAB" }' ``` - Update Profile with below config to enable external vault ``` "is_external_vault_enabled": "enable", "external_vault_connector_details": { "vault_connector_id": "mca_lRJXlrSQ557zrIJUalxK" } ``` - Create payment with customer acceptance, and setup_future_usage - on_session/off_session ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:api key' \ --data-raw ' { "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_1758488194", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "card_number", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ], "profile_id": "pro_KH7MujUjH2miLhfzGlAB" }' ``` - Payment method should be saved with external_vault_source - mca_lRJXlrSQ557zrIJUalxK (VGS mca id) vault_type - external <img width="1536" height="587" alt="Screenshot 2025-09-22 at 2 35 04 AM" src="https://github.com/user-attachments/assets/a7837f92-fd4f-4ddb-a887-190f3f1b3bc3" /> - If VGS is not enabled, then external_vault_source - <Empty> vault_type - internal <img width="1466" height="583" alt="Screenshot 2025-09-22 at 2 36 08 AM" src="https://github.com/user-attachments/assets/69b98983-1cae-478c-bc55-8fc1997e44ca" /> - make repeat CIT Please note, test backward compatibility how to -make a payment with existing customer's saved payment method ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0b263179af1b9dc3186c09c53b700b6a1f754d0e
juspay/hyperswitch
juspay__hyperswitch-9490
Bug: [FEATURE] Add External Vault Insert and Retrieve flow for Tokenex Add External Vault Insert - Tokenize and Retrieve - Detokenize flow for Tokenex
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 52f2b3c2e02..0b4d53c1857 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -177,6 +177,7 @@ pub enum BillingConnectors { pub enum VaultConnectors { Vgs, HyperswitchVault, + Tokenex, } impl From<VaultConnectors> for Connector { @@ -184,6 +185,7 @@ impl From<VaultConnectors> for Connector { match value { VaultConnectors::Vgs => Self::Vgs, VaultConnectors::HyperswitchVault => Self::HyperswitchVault, + VaultConnectors::Tokenex => Self::Tokenex, } } } diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 6f429829f5f..cf2e9f1c79b 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -336,7 +336,7 @@ pub enum Connector { Threedsecureio, // Tokenio, //Thunes, - // Tokenex, added as template code for future usage + Tokenex, Tokenio, Trustpay, Trustpayments, @@ -548,6 +548,7 @@ impl Connector { | Self::Cardinal | Self::CtpVisa | Self::Noon + | Self::Tokenex | Self::Tokenio | Self::Stripe | Self::Datatrans @@ -870,7 +871,8 @@ impl TryFrom<Connector> for RoutableConnectors { | Connector::Threedsecureio | Connector::Vgs | Connector::CtpVisa - | Connector::Cardinal => Err("Invalid conversion. Not a routable connector"), + | Connector::Cardinal + | Connector::Tokenex => Err("Invalid conversion. Not a routable connector"), } } } diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 9dc646f36d7..3c868782155 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -535,6 +535,7 @@ impl ConnectorConfig { Connector::Stax => Ok(connector_data.stax), Connector::Stripe => Ok(connector_data.stripe), Connector::Stripebilling => Ok(connector_data.stripebilling), + Connector::Tokenex => Ok(connector_data.tokenex), Connector::Tokenio => Ok(connector_data.tokenio), Connector::Trustpay => Ok(connector_data.trustpay), Connector::Trustpayments => Ok(connector_data.trustpayments), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index e27c801fafb..7be63721c9b 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7087,8 +7087,9 @@ required=false type="Text" [tokenex] -[tokenex.connector_auth.HeaderKey] +[tokenex.connector_auth.BodyKey] api_key = "API Key" +key1 = "TokenEx ID" [gigadat] [gigadat.connector_auth.HeaderKey] diff --git a/crates/hyperswitch_connectors/src/connectors/tokenex.rs b/crates/hyperswitch_connectors/src/connectors/tokenex.rs index f4477cca6aa..3dbe640beb3 100644 --- a/crates/hyperswitch_connectors/src/connectors/tokenex.rs +++ b/crates/hyperswitch_connectors/src/connectors/tokenex.rs @@ -7,29 +7,26 @@ 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::{ - payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, + ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + RefundsData, SetupMandateRequestData, VaultRequestData, }, router_response_types::{ ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + VaultResponseData, }, - types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, - }, + types::VaultRouterData, }; use hyperswitch_interfaces::{ api::{ @@ -45,20 +42,10 @@ use hyperswitch_interfaces::{ use masking::{ExposeInterface, Mask}; use transformers as tokenex; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{constants::headers, types::ResponseRouterData}; #[derive(Clone)] -pub struct Tokenex { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), -} - -impl Tokenex { - pub fn new() -> &'static Self { - &Self { - amount_converter: &StringMinorUnitForConnector, - } - } -} +pub struct Tokenex; impl api::Payment for Tokenex {} impl api::PaymentSession for Tokenex {} @@ -72,6 +59,9 @@ impl api::Refund for Tokenex {} impl api::RefundExecute for Tokenex {} impl api::RefundSync for Tokenex {} impl api::PaymentToken for Tokenex {} +impl api::ExternalVaultInsert for Tokenex {} +impl api::ExternalVault for Tokenex {} +impl api::ExternalVaultRetrieve for Tokenex {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Tokenex @@ -79,6 +69,13 @@ impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, Pay // Not Implemented (R) } +pub mod auth_headers { + pub const TOKENEX_ID: &str = "tx-tokenex-id"; + pub const TOKENEX_API_KEY: &str = "tx-apikey"; + pub const TOKENEX_SCHEME: &str = "tx-token-scheme"; + pub const TOKENEX_SCHEME_VALUE: &str = "PCI"; +} + impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Tokenex where Self: ConnectorIntegration<Flow, Request, Response>, @@ -88,12 +85,26 @@ 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); + let auth = tokenex::TokenexAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let header = vec![ + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + ), + ( + auth_headers::TOKENEX_ID.to_string(), + auth.tokenex_id.expose().into_masked(), + ), + ( + auth_headers::TOKENEX_API_KEY.to_string(), + auth.api_key.expose().into_masked(), + ), + ( + auth_headers::TOKENEX_SCHEME.to_string(), + auth_headers::TOKENEX_SCHEME_VALUE.to_string().into(), + ), + ]; Ok(header) } } @@ -155,31 +166,7 @@ impl ConnectorCommon for Tokenex { } } -impl ConnectorValidation for Tokenex { - fn validate_mandate_payment( - &self, - _pm_type: Option<enums::PaymentMethodType>, - pm_data: PaymentMethodData, - ) -> CustomResult<(), errors::ConnectorError> { - match pm_data { - PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( - "validate_mandate_payment does not support cards".to_string(), - ) - .into()), - _ => Ok(()), - } - } - - fn validate_psync_reference_id( - &self, - _data: &PaymentsSyncData, - _is_three_ds: bool, - _status: enums::AttemptStatus, - _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, - ) -> CustomResult<(), errors::ConnectorError> { - Ok(()) - } -} +impl ConnectorValidation for Tokenex {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Tokenex { //TODO: implement sessions flow @@ -189,200 +176,62 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Tokenex {} -impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Tokenex { - 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() - } +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Tokenex {} - fn get_url( - &self, - _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) - } +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tokenex {} - 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 = tokenex::TokenexRouterData::from((amount, req)); - let connector_req = tokenex::TokenexPaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Tokenex {} - 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(), - )) - } +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Tokenex {} - fn handle_response( - &self, - data: &PaymentsAuthorizeRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: tokenex::TokenexPaymentsResponse = res - .response - .parse_struct("Tokenex 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, - }) - } +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tokenex {} - 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 Tokenex { - 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() - } +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Tokenex {} +impl ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> + for Tokenex +{ 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, + _req: &VaultRouterData<ExternalVaultInsertFlow>, 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: tokenex::TokenexPaymentsResponse = res - .response - .parse_struct("tokenex 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) + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/v2/Pci/Tokenize", self.base_url(connectors))) } -} -impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Tokenex { fn get_headers( &self, - req: &PaymentsCaptureRouterData, + req: &VaultRouterData<ExternalVaultInsertFlow>, 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, + req: &VaultRouterData<ExternalVaultInsertFlow>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let connector_req = tokenex::TokenexInsertRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &PaymentsCaptureRouterData, + req: &VaultRouterData<ExternalVaultInsertFlow>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .url(&types::ExternalVaultInsertType::get_url( + self, req, connectors, + )?) .attach_default_headers() - .headers(types::PaymentsCaptureType::get_headers( + .headers(types::ExternalVaultInsertType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsCaptureType::get_request_body( + .set_body(types::ExternalVaultInsertType::get_request_body( self, req, connectors, )?) .build(), @@ -391,13 +240,13 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn handle_response( &self, - data: &PaymentsCaptureRouterData, + data: &VaultRouterData<ExternalVaultInsertFlow>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: tokenex::TokenexPaymentsResponse = res + ) -> CustomResult<VaultRouterData<ExternalVaultInsertFlow>, errors::ConnectorError> { + let response: tokenex::TokenexInsertResponse = res .response - .parse_struct("Tokenex PaymentsCaptureResponse") + .parse_struct("TokenexInsertResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -417,125 +266,53 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Tokenex {} - -impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tokenex { - 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() - } - +impl ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> + for Tokenex +{ 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 = tokenex::TokenexRouterData::from((refund_amount, req)); - let connector_req = tokenex::TokenexRefundRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &RefundsRouterData<Execute>, + _req: &VaultRouterData<ExternalVaultRetrieveFlow>, 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: tokenex::RefundResponse = res - .response - .parse_struct("tokenex 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) + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}/v2/Pci/DetokenizeWithCvv", + self.base_url(connectors) + )) } -} -impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Tokenex { fn get_headers( &self, - req: &RefundSyncRouterData, + req: &VaultRouterData<ExternalVaultRetrieveFlow>, 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( + fn get_request_body( &self, - _req: &RefundSyncRouterData, + req: &VaultRouterData<ExternalVaultRetrieveFlow>, _connectors: &Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = tokenex::TokenexRetrieveRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &RefundSyncRouterData, + req: &VaultRouterData<ExternalVaultRetrieveFlow>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() - .method(Method::Get) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .method(Method::Post) + .url(&types::ExternalVaultRetrieveType::get_url( + self, req, connectors, + )?) .attach_default_headers() - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .set_body(types::RefundSyncType::get_request_body( + .headers(types::ExternalVaultRetrieveType::get_headers( + self, req, connectors, + )?) + .set_body(types::ExternalVaultRetrieveType::get_request_body( self, req, connectors, )?) .build(), @@ -544,13 +321,13 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Tokenex { fn handle_response( &self, - data: &RefundSyncRouterData, + data: &VaultRouterData<ExternalVaultRetrieveFlow>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: tokenex::RefundResponse = res + ) -> CustomResult<VaultRouterData<ExternalVaultRetrieveFlow>, errors::ConnectorError> { + let response: tokenex::TokenexRetrieveResponse = res .response - .parse_struct("tokenex RefundSyncResponse") + .parse_struct("TokenexRetrieveResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); diff --git a/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs index 163fa16fa29..9d7082746b3 100644 --- a/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs @@ -1,20 +1,22 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_utils::{ + ext_traits::{Encode, StringExt}, + types::StringMinorUnit, +}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, - router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + router_flow_types::{ExternalVaultInsertFlow, ExternalVaultRetrieveFlow}, + router_request_types::VaultRequestData, + router_response_types::VaultResponseData, + types::VaultRouterData, + vault::PaymentMethodVaultingData, }; use hyperswitch_interfaces::errors; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; -use crate::types::{RefundsResponseRouterData, ResponseRouterData}; +use crate::types::ResponseRouterData; -//TODO: Fill the struct with respective fields pub struct TokenexRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, @@ -30,33 +32,27 @@ impl<T> From<(StringMinorUnit, T)> for TokenexRouterData<T> { } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] -pub struct TokenexPaymentsRequest { - amount: StringMinorUnit, - card: TokenexCard, +pub struct TokenexInsertRequest { + data: Secret<String>, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct TokenexCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, -} - -impl TryFrom<&TokenexRouterData<&PaymentsAuthorizeRouterData>> for TokenexPaymentsRequest { +impl<F> TryFrom<&VaultRouterData<F>> for TokenexInsertRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &TokenexRouterData<&PaymentsAuthorizeRouterData>, - ) -> Result<Self, Self::Error> { - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( - "Card payment method not implemented".to_string(), + fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> { + match item.request.payment_method_vaulting_data.clone() { + Some(PaymentMethodVaultingData::Card(req_card)) => { + let stringified_card = req_card + .encode_to_string_of_json() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Self { + data: Secret::new(stringified_card), + }) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment method apart from card".to_string(), ) .into()), - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } @@ -65,148 +61,126 @@ impl TryFrom<&TokenexRouterData<&PaymentsAuthorizeRouterData>> for TokenexPaymen // Auth Struct pub struct TokenexAuthType { pub(super) api_key: Secret<String>, + pub(super) tokenex_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for TokenexAuthType { 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 { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), + tokenex_id: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum TokenexPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, -} -impl From<TokenexPaymentStatus> for common_enums::AttemptStatus { - fn from(item: TokenexPaymentStatus) -> Self { - match item { - TokenexPaymentStatus::Succeeded => Self::Charged, - TokenexPaymentStatus::Failed => Self::Failure, - TokenexPaymentStatus::Processing => Self::Authorizing, - } - } -} - -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct TokenexPaymentsResponse { - status: TokenexPaymentStatus, - id: String, -} - -impl<F, T> TryFrom<ResponseRouterData<F, TokenexPaymentsResponse, T, PaymentsResponseData>> - for RouterData<F, T, PaymentsResponseData> +pub struct TokenexInsertResponse { + token: String, + first_six: String, + success: bool, +} +impl + TryFrom< + ResponseRouterData< + ExternalVaultInsertFlow, + TokenexInsertResponse, + VaultRequestData, + VaultResponseData, + >, + > for RouterData<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, TokenexPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData< + ExternalVaultInsertFlow, + TokenexInsertResponse, + VaultRequestData, + VaultResponseData, + >, ) -> Result<Self, Self::Error> { + let resp = item.response; + 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, + status: common_enums::AttemptStatus::Started, + response: Ok(VaultResponseData::ExternalVaultInsertResponse { + connector_vault_id: resp.token.clone(), + //fingerprint is not provided by tokenex, using token as fingerprint + fingerprint_id: resp.token.clone(), }), ..item.data }) } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct TokenexRefundRequest { - pub amount: StringMinorUnit, -} - -impl<F> TryFrom<&TokenexRouterData<&RefundsRouterData<F>>> for TokenexRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &TokenexRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { - Ok(Self { - amount: item.amount.to_owned(), - }) - } -} - -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Copy, 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 - } - } +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct TokenexRetrieveRequest { + token: Secret<String>, //Currently only card number is tokenized. Data can be stringified and can be tokenized + cache_cvv: bool, } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct TokenexRetrieveResponse { + value: Secret<String>, + success: bool, } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { +impl<F> TryFrom<&VaultRouterData<F>> for TokenexRetrieveRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, - ) -> Result<Self, Self::Error> { + fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> { + let connector_vault_id = item.request.connector_vault_id.as_ref().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "connector_vault_id", + }, + )?; Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), - }), - ..item.data + token: Secret::new(connector_vault_id.clone()), + cache_cvv: false, //since cvv is not stored at tokenex }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { +impl + TryFrom< + ResponseRouterData< + ExternalVaultRetrieveFlow, + TokenexRetrieveResponse, + VaultRequestData, + VaultResponseData, + >, + > for RouterData<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: ResponseRouterData< + ExternalVaultRetrieveFlow, + TokenexRetrieveResponse, + VaultRequestData, + VaultResponseData, + >, ) -> Result<Self, Self::Error> { + let resp = item.response; + + let card_detail: api_models::payment_methods::CardDetail = resp + .value + .clone() + .expose() + .parse_struct("CardDetail") + .change_context(errors::ConnectorError::ParsingFailed)?; + Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + status: common_enums::AttemptStatus::Started, + response: Ok(VaultResponseData::ExternalVaultRetrieveResponse { + vault_data: PaymentMethodVaultingData::Card(card_detail), }), ..item.data }) } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct TokenexErrorResponse { pub status_code: u16, diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 057aca866f4..ad6a276b672 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -7765,7 +7765,6 @@ default_imp_for_external_vault!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, - connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -7911,7 +7910,6 @@ default_imp_for_external_vault_insert!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, - connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -8202,7 +8200,6 @@ default_imp_for_external_vault_retrieve!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, - connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index 29e13cfd378..a4bc945b935 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -492,6 +492,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { trustpayments::transformers::TrustpaymentsAuthType::try_from(self.auth_type)?; Ok(()) } + api_enums::Connector::Tokenex => { + tokenex::transformers::TokenexAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Tokenio => { tokenio::transformers::TokenioAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 32953cd5eaf..3792cfa280e 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -550,7 +550,7 @@ pub fn build_unified_connector_service_external_vault_proxy_metadata( } )) } - api_enums::VaultConnectors::HyperswitchVault => None, + api_enums::VaultConnectors::HyperswitchVault | api_enums::VaultConnectors::Tokenex => None, }; match unified_service_vault_metdata { diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index adef987b03d..3c20816b68b 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -434,6 +434,7 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new()))) } // enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))), + enums::Connector::Tokenex => Ok(ConnectorEnum::Old(Box::new(&connector::Tokenex))), enums::Connector::Tokenio => { Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new()))) } diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index bad9c07fe2c..9f514337a68 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -353,6 +353,7 @@ impl FeatureMatrixConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new()))) } // enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))), + enums::Connector::Tokenex => Ok(ConnectorEnum::Old(Box::new(&connector::Tokenex))), enums::Connector::Tokenio => { Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new()))) } diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index ee9ec93c5a1..ae8dfa26727 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -145,6 +145,11 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Stripe => Self::Stripe, api_enums::Connector::Stripebilling => Self::Stripebilling, // api_enums::Connector::Thunes => Self::Thunes, + api_enums::Connector::Tokenex => { + Err(common_utils::errors::ValidationError::InvalidValue { + message: "Tokenex is not a routable connector".to_string(), + })? + } api_enums::Connector::Tokenio => Self::Tokenio, api_enums::Connector::Trustpay => Self::Trustpay, api_enums::Connector::Trustpayments => Self::Trustpayments, diff --git a/crates/router/tests/connectors/tokenex.rs b/crates/router/tests/connectors/tokenex.rs index fbcbe13019a..72fe2daacce 100644 --- a/crates/router/tests/connectors/tokenex.rs +++ b/crates/router/tests/connectors/tokenex.rs @@ -12,8 +12,8 @@ impl utils::Connector for TokenexTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Tokenex; utils::construct_connector_data_old( - Box::new(Tokenex::new()), - types::Connector::Plaid, + Box::new(&Tokenex), + types::Connector::Tokenex, api::GetToken::Connector, None, ) diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index d58a1d8388f..e44d56a57d6 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -121,7 +121,7 @@ pub struct ConnectorAuthentication { pub taxjar: Option<HeaderKey>, pub threedsecureio: Option<HeaderKey>, pub thunes: Option<HeaderKey>, - pub tokenex: Option<HeaderKey>, + pub tokenex: Option<BodyKey>, pub tokenio: Option<HeaderKey>, pub stripe_au: Option<HeaderKey>, pub stripe_uk: Option<HeaderKey>,
2025-09-22T08:05:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add external vault insert - tokenize and retrieve - detokenize flows for tokenex vault connector ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Currently this cannot be tested. since external vault support is added in this pr - https://github.com/juspay/hyperswitch/pull/9274 ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
3bd78ac5c1ff120d6afd46e02df498a16ece6f5f
juspay/hyperswitch
juspay__hyperswitch-9458
Bug: Send cvv to nexixpay card payments. Mandatorily send cvv to nexixpay card payments.
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 5c8fdd5e020..68ad70da2a7 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -410,6 +410,7 @@ pub struct ShippingAddress { pub struct NexixpayCard { pan: CardNumber, expiry_date: Secret<String>, + cvv: Secret<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -798,6 +799,7 @@ impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaym card: NexixpayCard { pan: req_card.card_number.clone(), expiry_date: req_card.get_expiry_date_as_mmyy()?, + cvv: req_card.card_cvc.clone(), }, recurrence: recurrence_request_obj, }, @@ -1357,6 +1359,7 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>> PaymentMethodData::Card(req_card) => Ok(NexixpayCard { pan: req_card.card_number.clone(), expiry_date: req_card.get_expiry_date_as_mmyy()?, + cvv: req_card.card_cvc.clone(), }), PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_)
2025-09-19T15:44:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Mandatorily send cvv to nexixpay card payments. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: **' \ --data-raw '{ "amount": 3545, "currency": "EUR", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4349 9401 9900 4549", "card_exp_month": "05", "card_exp_year": "26", "card_cvc": "396" } }, "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "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", "description": "Its my first payment request", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "country": "BR", "zip": "94122", "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": "BR", "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" }, "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 }' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0513c2cd719f59a23843104146e2f5f6863378a1
juspay/hyperswitch
juspay__hyperswitch-9457
Bug: fix(routing): update_gateway_score_condition
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 296f60f8d4a..b865110a1a6 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -9451,9 +9451,8 @@ impl RoutingApproach { pub fn from_decision_engine_approach(approach: &str) -> Self { match approach { "SR_SELECTION_V3_ROUTING" => Self::SuccessRateExploitation, - "SR_V3_HEDGING" => Self::SuccessRateExploration, + "SR_V3_HEDGING" | "DEFAULT" => Self::SuccessRateExploration, "NTW_BASED_ROUTING" => Self::DebitRouting, - "DEFAULT" => Self::StraightThroughRouting, _ => Self::DefaultFallback, } } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 292a668a07c..7d7336cf794 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2268,8 +2268,13 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( async move { let should_route_to_open_router = state.conf.open_router.dynamic_routing_enabled; + let is_success_rate_based = matches!( + payment_attempt.routing_approach, + Some(enums::RoutingApproach::SuccessRateExploitation) + | Some(enums::RoutingApproach::SuccessRateExploration) + ); - if should_route_to_open_router { + if should_route_to_open_router && is_success_rate_based { routing_helpers::update_gateway_score_helper_with_open_router( &state, &payment_attempt,
2025-09-19T10:43:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR updates the dynamic routing logic to ensure that update_gateway_score_helper_with_open_router is invoked only when the payment_attempt.routing_approach is either: SuccessRateExploitation or SuccessRateExploration. This updates the routing logic and the payment response tracker to improve how routing approaches are interpreted and when gateway scores are updated. The main changes clarify the mapping of routing approaches and ensure that gateway score updates are only triggered for specific routing strategies. Routing approach mapping improvements: * Added support for `"DEFAULT"` to map to `SuccessRateExploration` in `RoutingApproach::from_decision_engine_approach`, making the handling of default approaches more consistent. (`crates/common_enums/src/enums.rs`) Payment response update logic: * Changed the gateway score update condition in `payment_response_update_tracker` to require both dynamic routing to be enabled and the routing approach to be success-rate based, preventing updates for approaches that do not use success rate logic. (`crates/router/src/core/payments/operations/payment_response.rs`) This pull request updates routing logic to ensure that gateway score updates via Open Router only occur for success rate-based routing approaches. It also refines the mapping from decision engine approaches to routing approaches, making the behavior for the `"DEFAULT"` case more consistent. Routing logic improvements: * In `payment_response_update_tracker`, gateway score updates using Open Router are now restricted to cases where the routing approach is either `SuccessRateExploitation` or `SuccessRateExploration`, instead of being applied for all dynamic routing. Routing approach mapping changes: * In `RoutingApproach::from_decision_engine_approach`, the `"DEFAULT"` case is now mapped to `SuccessRateExploration` (alongside `"SR_V3_HEDGING"`), and is no longer mapped to `StraightThroughRouting`, improving consistency in approach selection. <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## How did you test it? sr_based ``` curl --location 'http://localhost:8080/account/merchant_1758275545/business_profile/pro_RiCX7Rsxbd4WReAR9TEh/dynamic_routing/success_based/create?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'api-key: *****' \ --data '{ "decision_engine_configs": { "defaultBucketSize": 200, "defaultHedgingPercent": 5 } }' ``` ``` { "id": "routing_S27CKCr6Mp8e3VmUnGf0", "profile_id": "pro_RiCX7Rsxbd4WReAR9TEh", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1758275557, "modified_at": 1758275557, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` activate ``` curl --location 'http://localhost:8080/routing/routing_S27CKCr6Mp8e3VmUnGf0/activate' \ --header 'Content-Type: application/json' \ --header 'api-key: *****' \ --data '{}' ``` ``` { "id": "routing_S27CKCr6Mp8e3VmUnGf0", "profile_id": "pro_RiCX7Rsxbd4WReAR9TEh", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1758275557, "modified_at": 1758275557, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1758275545/business_profile/pro_RiCX7Rsxbd4WReAR9TEh/dynamic_routing/set_volume_split?split=20' \ --header 'api-key: *****' ``` ``` { "routing_type": "dynamic", "split": 20 } ``` payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: *****' \ --data-raw '{ "amount": 6540, "currency": "USD", "amount_to_capture": 6540, "confirm": true, "profile_id": "pro_RiCX7Rsxbd4WReAR9TEh", "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", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "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": 6540, "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 }' ``` ``` { "payment_id": "pay_QifEdH91f7xnl124ICdD", "merchant_id": "merchant_1758275545", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 6540, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_QifEdH91f7xnl124ICdD", "created": "2025-09-19T10:16:18.704Z", "currency": "USD", "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": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "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", "origin_zip": null }, "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "sku": null, "upc": null, "brand": null, "amount": 6540, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "description": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": null, "unit_of_measure": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null, "unit_discount_amount": 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": 1758276978, "expires": 1758280578, "secret": "epk_721a0329318e4cb4bc8075b73c371a07" }, "manual_retry_allowed": null, "connector_transaction_id": "pi_3S91MVD5R7gDAGff06OHFTNL", "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, "adyen": null }, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3S91MVD5R7gDAGff06OHFTNL", "payment_link": null, "profile_id": "pro_RiCX7Rsxbd4WReAR9TEh", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_4NgqlrfFxugpnylD8XPF", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-19T10:31:18.704Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": "104557651805572", "payment_method_status": null, "updated": "2025-09-19T10:16:20.099Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": false, "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": false, "network_details": null } ``` ## Screenshot <img width="1319" height="326" alt="Screenshot 2025-09-19 at 7 09 13 PM" src="https://github.com/user-attachments/assets/d0c17cc5-f3cb-41bf-af65-212f9e36af41" /> <img width="1326" height="311" alt="Screenshot 2025-09-19 at 7 06 13 PM" src="https://github.com/user-attachments/assets/2ef8bd31-fd08-4441-9a80-2c201d008b35" />
e2f1a456a17645b9ccac771d3608794c4956277d
juspay/hyperswitch
juspay__hyperswitch-9462
Bug: [FEATURE] Add connector template code for Tokenex Add connector template code for Tokenex (Vault Connector)
diff --git a/config/config.example.toml b/config/config.example.toml index 68e55ee70ff..bae0da78fbb 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -305,6 +305,7 @@ stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" +tokenex.base_url = "https://test-api.tokenex.com" tokenio.base_url = "https://api.sandbox.token.io" stripe.base_url_file_upload = "https://files.stripe.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 903b040e5f9..f1addc2b581 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -142,6 +142,7 @@ stripe.base_url_file_upload = "https://files.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" thunes.base_url = "https://api.limonetikqualif.com/" +tokenex.base_url = "https://test-api.tokenex.com" tokenio.base_url = "https://api.sandbox.token.io" trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpayments.base_url = "https://webservices.securetrading.net/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 27034e858f9..3fd609dd9b7 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -146,6 +146,7 @@ stripe.base_url_file_upload = "https://files.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.taxjar.com/v2/" thunes.base_url = "https://api.limonetik.com/" +tokenex.base_url = "https://api.tokenex.com" tokenio.base_url = "https://api.token.io" trustpay.base_url = "https://tpgw.trustpay.eu/" trustpayments.base_url = "https://webservices.securetrading.net/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index c23bbac335f..44238899b50 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -146,6 +146,7 @@ stripe.base_url_file_upload = "https://files.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" thunes.base_url = "https://api.limonetikqualif.com/" +tokenex.base_url = "https://test-api.tokenex.com" tokenio.base_url = "https://api.sandbox.token.io" trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpayments.base_url = "https://webservices.securetrading.net/" diff --git a/config/development.toml b/config/development.toml index 1ab982e80f5..e145d1eb087 100644 --- a/config/development.toml +++ b/config/development.toml @@ -343,6 +343,7 @@ stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" +tokenex.base_url = "https://test-api.tokenex.com" tokenio.base_url = "https://api.sandbox.token.io" stripe.base_url_file_upload = "https://files.stripe.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 28daee87ac5..c36904d5fe8 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -231,6 +231,7 @@ stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" +tokenex.base_url = "https://test-api.tokenex.com" tokenio.base_url = "https://api.sandbox.token.io" stripe.base_url_file_upload = "https://files.stripe.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 128f2a9eac3..9991ba8a27e 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -336,6 +336,7 @@ pub enum Connector { Threedsecureio, // Tokenio, //Thunes, + // Tokenex, added as template code for future usage Tokenio, Trustpay, Trustpayments, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index b79a2111a56..186e08989ec 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -329,6 +329,7 @@ pub struct ConnectorConfig { pub stripe_payout: Option<ConnectorTomlConfig>, pub stripebilling: Option<ConnectorTomlConfig>, pub signifyd: Option<ConnectorTomlConfig>, + pub tokenex: Option<ConnectorTomlConfig>, pub tokenio: Option<ConnectorTomlConfig>, pub trustpay: Option<ConnectorTomlConfig>, pub trustpayments: Option<ConnectorTomlConfig>, diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 3f155b92b80..7d68c4de4fb 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7085,3 +7085,7 @@ label="mastercard Payment Facilitator Id" placeholder="Enter mastercard Payment Facilitator Id" required=false type="Text" + +[tokenex] +[tokenex.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 8a3c5606160..eff63730974 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5803,3 +5803,7 @@ label="mastercard Payment Facilitator Id" placeholder="Enter mastercard Payment Facilitator Id" required=false type="Text" + +[tokenex] +[tokenex.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 74a9c713e69..379ea955c9a 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7066,3 +7066,7 @@ label="mastercard Payment Facilitator Id" placeholder="Enter mastercard Payment Facilitator Id" required=false type="Text" + +[tokenex] +[tokenex.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index bf3fab9335a..806c21859f7 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -110,6 +110,7 @@ pub mod stripebilling; pub mod taxjar; pub mod threedsecureio; pub mod thunes; +pub mod tokenex; pub mod tokenio; pub mod trustpay; pub mod trustpayments; @@ -156,7 +157,8 @@ pub use self::{ recurly::Recurly, redsys::Redsys, riskified::Riskified, santander::Santander, shift4::Shift4, sift::Sift, signifyd::Signifyd, silverflow::Silverflow, square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, - thunes::Thunes, tokenio::Tokenio, trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, + thunes::Thunes, tokenex::Tokenex, tokenio::Tokenio, trustpay::Trustpay, + trustpayments::Trustpayments, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, worldpay::Worldpay, worldpayvantiv::Worldpayvantiv, worldpayxml::Worldpayxml, xendit::Xendit, diff --git a/crates/hyperswitch_connectors/src/connectors/tokenex.rs b/crates/hyperswitch_connectors/src/connectors/tokenex.rs new file mode 100644 index 00000000000..f4477cca6aa --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/tokenex.rs @@ -0,0 +1,621 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::enums; +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::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 tokenex; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Tokenex { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Tokenex { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Tokenex {} +impl api::PaymentSession for Tokenex {} +impl api::ConnectorAccessToken for Tokenex {} +impl api::MandateSetup for Tokenex {} +impl api::PaymentAuthorize for Tokenex {} +impl api::PaymentSync for Tokenex {} +impl api::PaymentCapture for Tokenex {} +impl api::PaymentVoid for Tokenex {} +impl api::Refund for Tokenex {} +impl api::RefundExecute for Tokenex {} +impl api::RefundSync for Tokenex {} +impl api::PaymentToken for Tokenex {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Tokenex +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Tokenex +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 Tokenex { + fn id(&self) -> &'static str { + "tokenex" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.tokenex.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = tokenex::TokenexAuthType::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: tokenex::TokenexErrorResponse = res + .response + .parse_struct("TokenexErrorResponse") + .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, + connector_metadata: None, + }) + } +} + +impl ConnectorValidation for Tokenex { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Tokenex { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Tokenex {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Tokenex {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Tokenex { + 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 = tokenex::TokenexRouterData::from((amount, req)); + let connector_req = tokenex::TokenexPaymentsRequest::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: tokenex::TokenexPaymentsResponse = res + .response + .parse_struct("Tokenex 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 Tokenex { + 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: tokenex::TokenexPaymentsResponse = res + .response + .parse_struct("tokenex 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 Tokenex { + 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: tokenex::TokenexPaymentsResponse = res + .response + .parse_struct("Tokenex 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 Tokenex {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tokenex { + 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 = tokenex::TokenexRouterData::from((refund_amount, req)); + let connector_req = tokenex::TokenexRefundRequest::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: tokenex::RefundResponse = res + .response + .parse_struct("tokenex 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 Tokenex { + 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: tokenex::RefundResponse = res + .response + .parse_struct("tokenex 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 Tokenex { + 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)) + } +} + +static TOKENEX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static TOKENEX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Tokenex", + description: "Tokenex connector", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Alpha, +}; + +static TOKENEX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Tokenex { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&TOKENEX_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*TOKENEX_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&TOKENEX_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs new file mode 100644 index 00000000000..163fa16fa29 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs @@ -0,0 +1,219 @@ +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}; + +//TODO: Fill the struct with respective fields +pub struct TokenexRouterData<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 TokenexRouterData<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 TokenexPaymentsRequest { + amount: StringMinorUnit, + card: TokenexCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct TokenexCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&TokenexRouterData<&PaymentsAuthorizeRouterData>> for TokenexPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &TokenexRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct TokenexAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for TokenexAuthType { + 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, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum TokenexPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<TokenexPaymentStatus> for common_enums::AttemptStatus { + fn from(item: TokenexPaymentStatus) -> Self { + match item { + TokenexPaymentStatus::Succeeded => Self::Charged, + TokenexPaymentStatus::Failed => Self::Failure, + TokenexPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct TokenexPaymentsResponse { + status: TokenexPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, TokenexPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, TokenexPaymentsResponse, 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 TokenexRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&TokenexRouterData<&RefundsRouterData<F>>> for TokenexRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &TokenexRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 TokenexErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index f109ea3fb2f..3a5c3e77bc3 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -278,6 +278,7 @@ default_imp_for_authorize_session_token!( connectors::Volt, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -419,6 +420,7 @@ default_imp_for_calculate_tax!( connectors::Stripebilling, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -572,6 +574,7 @@ default_imp_for_session_update!( connectors::Prophetpay, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -712,6 +715,7 @@ default_imp_for_post_session_tokens!( connectors::Prophetpay, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -854,6 +858,7 @@ default_imp_for_create_order!( connectors::Prophetpay, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -997,6 +1002,7 @@ default_imp_for_update_metadata!( connectors::Riskified, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1139,6 +1145,7 @@ default_imp_for_cancel_post_capture!( connectors::Riskified, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1255,6 +1262,7 @@ default_imp_for_complete_authorize!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1395,6 +1403,7 @@ default_imp_for_incremental_authorization!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1531,6 +1540,7 @@ default_imp_for_create_customer!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1660,6 +1670,7 @@ default_imp_for_connector_redirect_response!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Tsys, connectors::UnifiedAuthenticationService, @@ -1797,6 +1808,7 @@ default_imp_for_pre_authenticate_steps!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1939,6 +1951,7 @@ default_imp_for_authenticate_steps!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2081,6 +2094,7 @@ default_imp_for_post_authenticate_steps!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2212,6 +2226,7 @@ default_imp_for_pre_processing_steps!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Tsys, connectors::UnifiedAuthenticationService, @@ -2353,6 +2368,7 @@ default_imp_for_post_processing_steps!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2498,6 +2514,7 @@ default_imp_for_approve!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2643,6 +2660,7 @@ default_imp_for_reject!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2787,6 +2805,7 @@ default_imp_for_webhook_source_verification!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2931,6 +2950,7 @@ default_imp_for_accept_dispute!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3072,6 +3092,7 @@ default_imp_for_submit_evidence!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3214,6 +3235,7 @@ default_imp_for_defend_dispute!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3359,6 +3381,7 @@ default_imp_for_fetch_disputes!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3503,6 +3526,7 @@ default_imp_for_dispute_sync!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3653,6 +3677,7 @@ default_imp_for_file_upload!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3781,6 +3806,7 @@ default_imp_for_payouts!( connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3922,6 +3948,7 @@ default_imp_for_payouts_create!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -4066,6 +4093,7 @@ default_imp_for_payouts_retrieve!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -4209,6 +4237,7 @@ default_imp_for_payouts_eligibility!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -4347,6 +4376,7 @@ default_imp_for_payouts_fulfill!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -4489,6 +4519,7 @@ default_imp_for_payouts_cancel!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -4633,6 +4664,7 @@ default_imp_for_payouts_quote!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -4776,6 +4808,7 @@ default_imp_for_payouts_recipient!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -4920,6 +4953,7 @@ default_imp_for_payouts_recipient_account!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -5065,6 +5099,7 @@ default_imp_for_frm_sale!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -5210,6 +5245,7 @@ default_imp_for_frm_checkout!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -5355,6 +5391,7 @@ default_imp_for_frm_transaction!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -5500,6 +5537,7 @@ default_imp_for_frm_fulfillment!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -5645,6 +5683,7 @@ default_imp_for_frm_record_return!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -5786,6 +5825,7 @@ default_imp_for_revoking_mandates!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -5929,6 +5969,7 @@ default_imp_for_uas_pre_authentication!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -6071,6 +6112,7 @@ default_imp_for_uas_post_authentication!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -6214,6 +6256,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -6348,6 +6391,7 @@ default_imp_for_connector_request_id!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -6485,6 +6529,7 @@ default_imp_for_fraud_check!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -6651,6 +6696,7 @@ default_imp_for_connector_authentication!( connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -6793,6 +6839,7 @@ default_imp_for_uas_authentication!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -6929,6 +6976,7 @@ default_imp_for_revenue_recovery!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -7088,6 +7136,7 @@ default_imp_for_subscriptions!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -7233,6 +7282,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -7377,6 +7427,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -7522,6 +7573,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Threedsecureio, connectors::Taxjar, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -7660,6 +7712,7 @@ default_imp_for_external_vault!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -7804,6 +7857,7 @@ default_imp_for_external_vault_insert!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -7946,6 +8000,7 @@ default_imp_for_gift_card_balance_check!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -8091,6 +8146,7 @@ default_imp_for_external_vault_retrieve!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -8235,6 +8291,7 @@ default_imp_for_external_vault_delete!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -8379,6 +8436,7 @@ default_imp_for_external_vault_create!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -8523,6 +8581,7 @@ default_imp_for_connector_authentication_token!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -8666,6 +8725,7 @@ default_imp_for_external_vault_proxy_payments_create!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index f675f95e909..5f67ba53ec7 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -378,6 +378,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -523,6 +524,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -657,6 +659,7 @@ default_imp_for_new_connector_integration_connector_authentication_token!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Tsys, @@ -796,6 +799,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -941,6 +945,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1086,6 +1091,7 @@ default_imp_for_new_connector_integration_fetch_disputes!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1232,6 +1238,7 @@ default_imp_for_new_connector_integration_dispute_sync!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1378,6 +1385,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1522,6 +1530,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1677,6 +1686,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1824,6 +1834,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -1971,6 +1982,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2118,6 +2130,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2265,6 +2278,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2412,6 +2426,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2559,6 +2574,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2706,6 +2722,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2853,6 +2870,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -2998,6 +3016,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3145,6 +3164,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3292,6 +3312,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3439,6 +3460,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3586,6 +3608,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3733,6 +3756,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3876,6 +3900,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -3989,6 +4014,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpayments, connectors::Tsys, @@ -4131,6 +4157,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpayments, connectors::Tsys, @@ -4265,6 +4292,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpayments, connectors::Tsys, @@ -4435,6 +4463,7 @@ default_imp_for_new_connector_integration_external_vault!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, @@ -4579,6 +4608,7 @@ default_imp_for_new_connector_integration_external_vault_proxy!( connectors::Taxjar, connectors::Threedsecureio, connectors::Thunes, + connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rs index 1565d9240c4..739f89ce4d5 100644 --- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs +++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs @@ -126,6 +126,7 @@ pub struct Connectors { pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, + pub tokenex: ConnectorParams, pub tokenio: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub trustpayments: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 45d7ad513d8..b378e685f56 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -40,9 +40,9 @@ pub use hyperswitch_connectors::connectors::{ santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, - threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenio, - tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, - tsys, tsys::Tsys, unified_authentication_service, + threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, + tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, + trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index d03e5e18afb..4f405f56ee3 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -110,6 +110,7 @@ mod stax; mod stripe; mod stripebilling; mod taxjar; +mod tokenex; mod tokenio; mod trustpay; mod trustpayments; diff --git a/crates/router/tests/connectors/tokenex.rs b/crates/router/tests/connectors/tokenex.rs new file mode 100644 index 00000000000..fbcbe13019a --- /dev/null +++ b/crates/router/tests/connectors/tokenex.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 TokenexTest; +impl ConnectorActions for TokenexTest {} +impl utils::Connector for TokenexTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Tokenex; + utils::construct_connector_data_old( + Box::new(Tokenex::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .tokenex + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "tokenex".to_string() + } +} + +static CONNECTOR: TokenexTest = TokenexTest {}; + +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/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 9703b6a2c98..64fa913d512 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -120,6 +120,7 @@ pub struct ConnectorAuthentication { pub taxjar: Option<HeaderKey>, pub threedsecureio: Option<HeaderKey>, pub thunes: Option<HeaderKey>, + pub tokenex: Option<HeaderKey>, pub tokenio: Option<HeaderKey>, pub stripe_au: Option<HeaderKey>, pub stripe_uk: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 97d6076b074..cd4fe3fc8c0 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -198,6 +198,7 @@ stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" +tokenex.base_url = "https://test-api.tokenex.com" tokenio.base_url = "https://api.sandbox.token.io" stripe.base_url_file_upload = "https://files.stripe.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index b42835e091c..9f6a3062c48 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 affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
2025-09-17T09:56:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> template for Tokenex integration ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> No Testing Required ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0b263179af1b9dc3186c09c53b700b6a1f754d0e
juspay/hyperswitch
juspay__hyperswitch-9456
Bug: [FEATURE] : Add wasm changes for Paysafe connector Add wasm changes for , interac , skrill and paysafe card
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index fffeed0c3e7..4c1d94e9908 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6872,6 +6872,12 @@ payment_method_type = "Discover" payment_method_type = "CartesBancaires" [[paysafe.debit]] payment_method_type = "UnionPay" +[[paysafe.bank_redirect]] +payment_method_type = "interac" +[[paysafe.wallet]] +payment_method_type = "skrill" +[[paysafe.gift_card]] +payment_method_type = "pay_safe_card" [paysafe.connector_auth.BodyKey] api_key = "Username" key1 = "Password" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 8ac797ff3c5..83eed6a3431 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5539,6 +5539,12 @@ payment_method_type = "Discover" payment_method_type = "CartesBancaires" [[paysafe.debit]] payment_method_type = "UnionPay" +[[paysafe.bank_redirect]] +payment_method_type = "interac" +[[paysafe.wallet]] +payment_method_type = "skrill" +[[paysafe.gift_card]] +payment_method_type = "pay_safe_card" [paysafe.connector_auth.BodyKey] api_key = "Username" key1 = "Password" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 5e283de61af..26dc729b5a6 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6849,6 +6849,12 @@ payment_method_type = "Discover" payment_method_type = "CartesBancaires" [[paysafe.debit]] payment_method_type = "UnionPay" +[[paysafe.bank_redirect]] +payment_method_type = "interac" +[[paysafe.wallet]] +payment_method_type = "skrill" +[[paysafe.gift_card]] +payment_method_type = "pay_safe_card" [paysafe.connector_auth.BodyKey] api_key = "Username" key1 = "Password"
2025-09-19T13:15:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add wasm changes for , interac , skrill and paysafe card ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e29a121bfd10f00486dfa33e9d8cbd18ecc625eb
juspay/hyperswitch
juspay__hyperswitch-9465
Bug: DB changes for split payments (v2) The following DB changes need to be made to support split payments: In PaymentIntent: - Add `active_attempts_group_id` column - Add `active_attempt_id_type` column In PaymentAttempt: - Add `attempts_group_id` column While currently a `payment_intent` can have only a single `active_attempt`, For split payments case, a `payment_intent` will have a group of active attempts. These attempts will be linked together by the `attempts_group_id`. This `attempts_group_id` will be stored in the payment intent as the `active_attempts_group_id`. The `active_attempt_id` will be ignored in split payments case.
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 581858a85de..cc384ab9ecc 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2904,6 +2904,29 @@ pub enum SplitTxnsEnabled { Skip, } +#[derive( + Clone, + Debug, + Copy, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum ActiveAttemptIDType { + AttemptsGroupID, + #[default] + AttemptID, +} + #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index d42b9d8d108..af797360ff8 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -129,6 +129,8 @@ pub struct PaymentAttempt { pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, + /// A string indicating the group of the payment attempt. Used in split payments flow + pub attempts_group_id: Option<String>, } #[cfg(feature = "v1")] @@ -300,6 +302,7 @@ pub struct PaymentListFilters { pub struct PaymentAttemptNew { pub payment_id: id_type::GlobalPaymentId, pub merchant_id: id_type::MerchantId, + pub attempts_group_id: Option<String>, pub status: storage_enums::AttemptStatus, pub error_message: Option<String>, pub surcharge_amount: Option<MinorUnit>, @@ -1011,6 +1014,7 @@ impl PaymentAttemptUpdateInternal { .or(source.connector_request_reference_id), is_overcapture_enabled: source.is_overcapture_enabled, network_details: source.network_details, + attempts_group_id: source.attempts_group_id, } } } diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 38123c0a3f0..0e578012a3b 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -97,6 +97,8 @@ pub struct PaymentIntent { pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub id: common_utils::id_type::GlobalPaymentId, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, + pub active_attempts_group_id: Option<String>, + pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>, } #[cfg(feature = "v1")] @@ -808,6 +810,8 @@ impl PaymentIntentUpdateInternal { enable_partial_authorization: None, split_txns_enabled: source.split_txns_enabled, enable_overcapture: None, + active_attempt_id_type: source.active_attempt_id_type, + active_attempts_group_id: source.active_attempts_group_id, } } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index f05b4e460c3..185ca6098b3 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1011,6 +1011,8 @@ diesel::table! { #[max_length = 32] network_decline_code -> Nullable<Varchar>, network_error_message -> Nullable<Text>, + #[max_length = 64] + attempts_group_id -> Nullable<Varchar>, } } @@ -1106,6 +1108,10 @@ diesel::table! { id -> Varchar, #[max_length = 16] split_txns_enabled -> Nullable<Varchar>, + #[max_length = 64] + active_attempts_group_id -> Nullable<Varchar>, + #[max_length = 16] + active_attempt_id_type -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 370bafd2a90..fa6dd17bc91 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -461,6 +461,10 @@ pub struct PaymentIntent { pub setup_future_usage: storage_enums::FutureUsage, /// 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>, + /// This field represents whether there are attempt groups for this payment intent. Used in split payments workflow + pub active_attempt_id_type: common_enums::ActiveAttemptIDType, + /// The ID of the active attempt group for the payment intent + pub active_attempts_group_id: Option<String>, /// The order details for the payment. pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// This is the list of payment method types that are allowed for the payment intent. @@ -661,6 +665,8 @@ impl PaymentIntent { last_synced: None, setup_future_usage: request.setup_future_usage.unwrap_or_default(), active_attempt_id: None, + active_attempt_id_type: common_enums::ActiveAttemptIDType::AttemptID, + active_attempts_group_id: None, order_details, allowed_payment_method_types, connector_metadata, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 7f8b9020618..bbc2da59d78 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -398,6 +398,8 @@ pub struct PaymentAttempt { pub payment_id: id_type::GlobalPaymentId, /// Merchant id for the payment attempt pub merchant_id: id_type::MerchantId, + /// Group id for the payment attempt + pub attempts_group_id: Option<String>, /// Amount details for the payment attempt pub amount_details: AttemptAmountDetails, /// Status of the payment attempt. This is the status that is updated by the connector. @@ -575,6 +577,7 @@ impl PaymentAttempt { Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), + attempts_group_id: None, amount_details: attempt_amount_details, status: common_enums::AttemptStatus::Started, // This will be decided by the routing algorithm and updated in update trackers @@ -665,6 +668,7 @@ impl PaymentAttempt { Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), + attempts_group_id: None, amount_details: attempt_amount_details, status: common_enums::AttemptStatus::Started, connector: Some(request.connector.clone()), @@ -761,6 +765,7 @@ impl PaymentAttempt { Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), + attempts_group_id: None, amount_details: attempt_amount_details, status: common_enums::AttemptStatus::Started, connector: None, @@ -879,6 +884,7 @@ impl PaymentAttempt { Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), + attempts_group_id: None, amount_details: AttemptAmountDetails::from(amount_details), status: request.status, connector, @@ -2383,6 +2389,7 @@ impl behaviour::Conversion for PaymentAttempt { let Self { payment_id, merchant_id, + attempts_group_id, status, error, amount_details, @@ -2528,6 +2535,7 @@ impl behaviour::Conversion for PaymentAttempt { network_transaction_id, is_overcapture_enabled: None, network_details: None, + attempts_group_id, }) } @@ -2600,6 +2608,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.clone(), + attempts_group_id: storage_model.attempts_group_id, id: storage_model.id, status: storage_model.status, amount_details, @@ -2665,6 +2674,7 @@ impl behaviour::Conversion for PaymentAttempt { let Self { payment_id, merchant_id, + attempts_group_id, status, error, amount_details, @@ -2806,6 +2816,7 @@ impl behaviour::Conversion for PaymentAttempt { created_by: created_by.map(|cb| cb.to_string()), connector_request_reference_id, network_details: None, + attempts_group_id, }) } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 8cd3be165e0..809abb00674 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1659,6 +1659,8 @@ impl behaviour::Conversion for PaymentIntent { last_synced, setup_future_usage, active_attempt_id, + active_attempt_id_type, + active_attempts_group_id, order_details, allowed_payment_method_types, connector_metadata, @@ -1714,6 +1716,8 @@ impl behaviour::Conversion for PaymentIntent { last_synced, setup_future_usage: Some(setup_future_usage), active_attempt_id, + active_attempt_id_type: Some(active_attempt_id_type), + active_attempts_group_id, order_details: order_details.map(|order_details| { order_details .into_iter() @@ -1877,6 +1881,8 @@ impl behaviour::Conversion for PaymentIntent { last_synced: storage_model.last_synced, setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(), active_attempt_id: storage_model.active_attempt_id, + active_attempt_id_type: storage_model.active_attempt_id_type.unwrap_or_default(), + active_attempts_group_id: storage_model.active_attempts_group_id, order_details: storage_model.order_details.map(|order_details| { order_details .into_iter() diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index 9afb697e14e..68659698c58 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -153,6 +153,7 @@ pub struct KafkaPaymentAttempt<'a> { pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a id_type::GlobalAttemptId, + pub attempts_group_id: Option<&'a String>, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub connector: Option<&'a String>, @@ -232,6 +233,7 @@ impl<'a> KafkaPaymentAttempt<'a> { let PaymentAttempt { payment_id, merchant_id, + attempts_group_id, amount_details, status, connector, @@ -291,6 +293,7 @@ impl<'a> KafkaPaymentAttempt<'a> { payment_id, merchant_id, attempt_id: id, + attempts_group_id: attempts_group_id.as_ref(), status: *status, amount: amount_details.get_net_amount(), connector: connector.as_ref(), diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index 46a05d6fcf1..5e18c5909ef 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -155,6 +155,7 @@ pub struct KafkaPaymentAttemptEvent<'a> { pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a id_type::GlobalAttemptId, + pub attempts_group_id: Option<&'a String>, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub connector: Option<&'a String>, @@ -234,6 +235,7 @@ impl<'a> KafkaPaymentAttemptEvent<'a> { let PaymentAttempt { payment_id, merchant_id, + attempts_group_id, amount_details, status, connector, @@ -293,6 +295,7 @@ impl<'a> KafkaPaymentAttemptEvent<'a> { payment_id, merchant_id, attempt_id: id, + attempts_group_id: attempts_group_id.as_ref(), status: *status, amount: amount_details.get_net_amount(), connector: connector.as_ref(), diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index 85cf80cd8a7..cd31a221044 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -130,6 +130,8 @@ pub struct KafkaPaymentIntent<'a> { pub setup_future_usage: storage_enums::FutureUsage, pub off_session: bool, pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>, + pub active_attempt_id_type: common_enums::ActiveAttemptIDType, + pub active_attempts_group_id: Option<&'a String>, pub attempt_count: i16, pub profile_id: &'a id_type::ProfileId, pub customer_email: Option<HashedString<pii::EmailStrategy>>, @@ -200,6 +202,8 @@ impl<'a> KafkaPaymentIntent<'a> { last_synced, setup_future_usage, active_attempt_id, + active_attempt_id_type, + active_attempts_group_id, order_details, allowed_payment_method_types, connector_metadata, @@ -255,6 +259,8 @@ impl<'a> KafkaPaymentIntent<'a> { setup_future_usage: *setup_future_usage, off_session: setup_future_usage.is_off_session(), active_attempt_id: active_attempt_id.as_ref(), + active_attempt_id_type: *active_attempt_id_type, + active_attempts_group_id: active_attempts_group_id.as_ref(), attempt_count: *attempt_count, profile_id, customer_email: None, diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index edfb570901a..37e2eb6146e 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -83,6 +83,8 @@ pub struct KafkaPaymentIntentEvent<'a> { pub setup_future_usage: storage_enums::FutureUsage, pub off_session: bool, pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>, + pub active_attempt_id_type: common_enums::ActiveAttemptIDType, + pub active_attempts_group_id: Option<&'a String>, pub attempt_count: i16, pub profile_id: &'a id_type::ProfileId, pub customer_email: Option<HashedString<pii::EmailStrategy>>, @@ -212,6 +214,8 @@ impl<'a> KafkaPaymentIntentEvent<'a> { last_synced, setup_future_usage, active_attempt_id, + active_attempt_id_type, + active_attempts_group_id, order_details, allowed_payment_method_types, connector_metadata, @@ -267,6 +271,8 @@ impl<'a> KafkaPaymentIntentEvent<'a> { setup_future_usage: *setup_future_usage, off_session: setup_future_usage.is_off_session(), active_attempt_id: active_attempt_id.as_ref(), + active_attempt_id_type: *active_attempt_id_type, + active_attempts_group_id: active_attempts_group_id.as_ref(), attempt_count: *attempt_count, profile_id, customer_email: None, diff --git a/v2_compatible_migrations/2025-09-19-061700-0000_add-group-id-in-payment-intent-and-attempt/down.sql b/v2_compatible_migrations/2025-09-19-061700-0000_add-group-id-in-payment-intent-and-attempt/down.sql new file mode 100644 index 00000000000..c8d1b06586c --- /dev/null +++ b/v2_compatible_migrations/2025-09-19-061700-0000_add-group-id-in-payment-intent-and-attempt/down.sql @@ -0,0 +1,8 @@ +ALTER TABLE payment_attempt + DROP COLUMN IF EXISTS attempts_group_id; + +ALTER TABLE payment_intent + DROP COLUMN IF EXISTS active_attempts_group_id; + +ALTER TABLE payment_intent + DROP COLUMN IF EXISTS active_attempt_id_type; \ No newline at end of file diff --git a/v2_compatible_migrations/2025-09-19-061700-0000_add-group-id-in-payment-intent-and-attempt/up.sql b/v2_compatible_migrations/2025-09-19-061700-0000_add-group-id-in-payment-intent-and-attempt/up.sql new file mode 100644 index 00000000000..b14308c8910 --- /dev/null +++ b/v2_compatible_migrations/2025-09-19-061700-0000_add-group-id-in-payment-intent-and-attempt/up.sql @@ -0,0 +1,8 @@ +ALTER TABLE payment_attempt + ADD COLUMN IF NOT EXISTS attempts_group_id VARCHAR(64); + +ALTER TABLE payment_intent + ADD COLUMN IF NOT EXISTS active_attempts_group_id VARCHAR(64); + +ALTER TABLE payment_intent + ADD COLUMN IF NOT EXISTS active_attempt_id_type VARCHAR(16); \ No newline at end of file
2025-09-22T06:18:50Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added DB changes for split payments In PaymentIntent: - Add `active_attempts_group_id` column - Add `active_attempt_id_type` column In PaymentAttempt: - Add `attempts_group_id` column While currently a payment_intent can have only a single active_attempt, For split payments case, a payment_intent will have a group of active attempts. These attempts will be linked together by the `attempts_group_id`. This `attempts_group_id` will be stored in the payment intent as the `active_attempts_group_id`. The active_attempt_id will be ignored in split payments case. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #9465 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This PR only contains DB changes. No API changes are done ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2553780051e3a2fe54fcb99384e4bd8021d52048
juspay/hyperswitch
juspay__hyperswitch-9463
Bug: feature: Subscriptions get plans ## description Get plans api for subscriptions
diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs index c9cc3acd2ce..9378d7796f4 100644 --- a/crates/api_models/src/subscription.rs +++ b/crates/api_models/src/subscription.rs @@ -141,8 +141,58 @@ impl SubscriptionResponse { } } +#[derive(Debug, Clone, serde::Serialize)] +pub struct GetPlansResponse { + pub plan_id: String, + pub name: String, + pub description: Option<String>, + pub price_id: Vec<SubscriptionPlanPrices>, +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct SubscriptionPlanPrices { + pub price_id: String, + pub plan_id: Option<String>, + pub amount: MinorUnit, + pub currency: api_enums::Currency, + pub interval: PeriodUnit, + pub interval_count: i64, + pub trial_period: Option<i64>, + pub trial_period_unit: Option<PeriodUnit>, +} + +#[derive(Debug, Clone, serde::Serialize)] +pub enum PeriodUnit { + Day, + Week, + Month, + Year, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct ClientSecret(String); + +impl ClientSecret { + pub fn new(secret: String) -> Self { + Self(secret) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(serde::Deserialize, serde::Serialize, Debug)] +pub struct GetPlansQuery { + pub client_secret: Option<ClientSecret>, + pub limit: Option<u32>, + pub offset: Option<u32>, +} + impl ApiEventMetric for SubscriptionResponse {} impl ApiEventMetric for CreateSubscriptionRequest {} +impl ApiEventMetric for GetPlansQuery {} +impl ApiEventMetric for GetPlansResponse {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionPaymentDetails { @@ -227,6 +277,7 @@ pub struct PaymentResponseData { pub error_code: Option<String>, pub error_message: Option<String>, pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub client_secret: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionRequest { diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index b2d66db1f4b..f3e935c6dd5 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -843,7 +843,13 @@ fn get_chargebee_plans_query_params( ) -> CustomResult<String, errors::ConnectorError> { // Try to get limit from request, else default to 10 let limit = _req.request.limit.unwrap_or(10); - let param = format!("?limit={}&type[is]={}", limit, constants::PLAN_ITEM_TYPE); + let offset = _req.request.offset.unwrap_or(0); + let param = format!( + "?limit={}&offset={}&type[is]={}", + limit, + offset, + constants::PLAN_ITEM_TYPE + ); Ok(param) } diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 4c7b135f1a2..324418e22b7 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -1248,12 +1248,13 @@ pub struct ChargebeePlanPriceItem { pub period: i64, pub period_unit: ChargebeePeriodUnit, pub trial_period: Option<i64>, - pub trial_period_unit: ChargebeeTrialPeriodUnit, + pub trial_period_unit: Option<ChargebeeTrialPeriodUnit>, pub price: MinorUnit, pub pricing_model: ChargebeePricingModel, } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] pub enum ChargebeePricingModel { FlatFee, PerUnit, @@ -1263,6 +1264,7 @@ pub enum ChargebeePricingModel { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] pub enum ChargebeePeriodUnit { Day, Week, @@ -1271,6 +1273,7 @@ pub enum ChargebeePeriodUnit { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] pub enum ChargebeeTrialPeriodUnit { Day, Month, @@ -1308,8 +1311,9 @@ impl<F, T> interval_count: prices.item_price.period, trial_period: prices.item_price.trial_period, trial_period_unit: match prices.item_price.trial_period_unit { - ChargebeeTrialPeriodUnit::Day => Some(subscriptions::PeriodUnit::Day), - ChargebeeTrialPeriodUnit::Month => Some(subscriptions::PeriodUnit::Month), + Some(ChargebeeTrialPeriodUnit::Day) => Some(subscriptions::PeriodUnit::Day), + Some(ChargebeeTrialPeriodUnit::Month) => Some(subscriptions::PeriodUnit::Month), + None => None, }, }) .collect(); diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 70f7c4830cf..3ed5130e077 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -37,6 +37,7 @@ pub mod router_flow_types; pub mod router_request_types; pub mod router_response_types; pub mod routing; +pub mod subscription; #[cfg(feature = "tokenization_v2")] pub mod tokenization; pub mod transformers; diff --git a/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs index 8599116e8f4..f93185b7d30 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs @@ -29,6 +29,21 @@ pub struct GetSubscriptionPlansRequest { pub offset: Option<u32>, } +impl GetSubscriptionPlansRequest { + pub fn new(limit: Option<u32>, offset: Option<u32>) -> Self { + Self { limit, offset } + } +} + +impl Default for GetSubscriptionPlansRequest { + fn default() -> Self { + Self { + limit: Some(10), + offset: Some(0), + } + } +} + #[derive(Debug, Clone)] pub struct GetSubscriptionPlanPricesRequest { pub plan_price_id: String, diff --git a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs index 3da78e63beb..183b2f7ed38 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs @@ -33,6 +33,7 @@ pub enum SubscriptionStatus { Onetime, Cancelled, Failed, + Created, } #[cfg(feature = "v1")] @@ -47,6 +48,7 @@ impl From<SubscriptionStatus> for api_models::subscription::SubscriptionStatus { SubscriptionStatus::Onetime => Self::Onetime, SubscriptionStatus::Cancelled => Self::Cancelled, SubscriptionStatus::Failed => Self::Failed, + SubscriptionStatus::Created => Self::Created, } } } @@ -80,6 +82,22 @@ pub struct SubscriptionPlanPrices { pub trial_period_unit: Option<PeriodUnit>, } +#[cfg(feature = "v1")] +impl From<SubscriptionPlanPrices> for api_models::subscription::SubscriptionPlanPrices { + fn from(item: SubscriptionPlanPrices) -> Self { + Self { + price_id: item.price_id, + plan_id: item.plan_id, + amount: item.amount, + currency: item.currency, + interval: item.interval.into(), + interval_count: item.interval_count, + trial_period: item.trial_period, + trial_period_unit: item.trial_period_unit.map(Into::into), + } + } +} + #[derive(Debug, Clone)] pub enum PeriodUnit { Day, @@ -88,6 +106,18 @@ pub enum PeriodUnit { Year, } +#[cfg(feature = "v1")] +impl From<PeriodUnit> for api_models::subscription::PeriodUnit { + fn from(unit: PeriodUnit) -> Self { + match unit { + PeriodUnit::Day => Self::Day, + PeriodUnit::Week => Self::Week, + PeriodUnit::Month => Self::Month, + PeriodUnit::Year => Self::Year, + } + } +} + #[derive(Debug, Clone)] pub struct GetSubscriptionEstimateResponse { pub sub_total: MinorUnit, diff --git a/crates/hyperswitch_domain_models/src/subscription.rs b/crates/hyperswitch_domain_models/src/subscription.rs new file mode 100644 index 00000000000..af2390de3f8 --- /dev/null +++ b/crates/hyperswitch_domain_models/src/subscription.rs @@ -0,0 +1,50 @@ +use common_utils::events::ApiEventMetric; +use error_stack::ResultExt; + +use crate::errors::api_error_response::ApiErrorResponse; + +const SECRET_SPLIT: &str = "_secret"; + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct ClientSecret(String); + +impl ClientSecret { + pub fn new(secret: String) -> Self { + Self(secret) + } + + pub fn get_subscription_id(&self) -> error_stack::Result<String, ApiErrorResponse> { + let sub_id = self + .0 + .split(SECRET_SPLIT) + .next() + .ok_or(ApiErrorResponse::MissingRequiredField { + field_name: "client_secret", + }) + .attach_printable("Failed to extract subscription_id from client_secret")?; + + Ok(sub_id.to_string()) + } +} + +impl std::fmt::Display for ClientSecret { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +impl ApiEventMetric for ClientSecret {} + +#[cfg(feature = "v1")] +impl From<api_models::subscription::ClientSecret> for ClientSecret { + fn from(api_secret: api_models::subscription::ClientSecret) -> Self { + Self::new(api_secret.as_str().to_string()) + } +} + +#[cfg(feature = "v1")] +impl From<ClientSecret> for api_models::subscription::ClientSecret { + fn from(domain_secret: ClientSecret) -> Self { + Self::new(domain_secret.to_string()) + } +} diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 7ef35b8c0d1..1ec8514fc65 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -4,7 +4,10 @@ use api_models::subscription::{ use common_enums::connector_enums; use common_utils::id_type::GenerateId; use error_stack::ResultExt; -use hyperswitch_domain_models::{api::ApplicationResponse, merchant_context::MerchantContext}; +use hyperswitch_domain_models::{ + api::ApplicationResponse, merchant_context::MerchantContext, + router_response_types::subscriptions as subscription_response_types, +}; use super::errors::{self, RouterResponse}; use crate::{ @@ -28,7 +31,7 @@ pub async fn create_subscription( merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, request: subscription_types::CreateSubscriptionRequest, -) -> RouterResponse<SubscriptionResponse> { +) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { let subscription_id = common_utils::id_type::SubscriptionId::generate(); let profile = @@ -43,7 +46,7 @@ pub async fn create_subscription( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), - customer, + Some(customer), profile.clone(), ) .await?; @@ -65,7 +68,7 @@ pub async fn create_subscription( .create_payment_with_confirm_false(subscription.handler.state, &request) .await .attach_printable("subscriptions: failed to create payment")?; - invoice_handler + let invoice_entry = invoice_handler .create_invoice_entry( &state, billing_handler.merchant_connector_id, @@ -88,9 +91,67 @@ pub async fn create_subscription( .await .attach_printable("subscriptions: failed to update subscription")?; - Ok(ApplicationResponse::Json( - subscription.to_subscription_response(), - )) + let response = subscription.generate_response( + &invoice_entry, + &payment, + subscription_response_types::SubscriptionStatus::Created, + )?; + + Ok(ApplicationResponse::Json(response)) +} + +pub async fn get_subscription_plans( + state: SessionState, + merchant_context: MerchantContext, + profile_id: common_utils::id_type::ProfileId, + query: subscription_types::GetPlansQuery, +) -> RouterResponse<Vec<subscription_types::GetPlansResponse>> { + let profile = + SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) + .await + .attach_printable("subscriptions: failed to find business profile")?; + + let subscription_handler = SubscriptionHandler::new(&state, &merchant_context); + + if let Some(client_secret) = query.client_secret { + subscription_handler + .find_and_validate_subscription(&client_secret.into()) + .await? + }; + + let billing_handler = BillingHandler::create( + &state, + merchant_context.get_merchant_account(), + merchant_context.get_merchant_key_store(), + None, + profile.clone(), + ) + .await?; + + let get_plans_response = billing_handler + .get_subscription_plans(&state, query.limit, query.offset) + .await?; + + let mut response = Vec::new(); + + for plan in &get_plans_response.list { + let plan_price_response = billing_handler + .get_subscription_plan_prices(&state, plan.subscription_provider_plan_id.clone()) + .await?; + + response.push(subscription_types::GetPlansResponse { + plan_id: plan.subscription_provider_plan_id.clone(), + name: plan.name.clone(), + description: plan.description.clone(), + price_id: plan_price_response + .list + .into_iter() + .map(subscription_types::SubscriptionPlanPrices::from) + .collect::<Vec<_>>(), + }) + } + + Ok(ApplicationResponse::Json(response)) } /// Creates and confirms a subscription in one operation. @@ -116,7 +177,7 @@ pub async fn create_and_confirm_subscription( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), - customer, + Some(customer), profile.clone(), ) .await?; @@ -259,7 +320,7 @@ pub async fn confirm_subscription( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), - customer, + Some(customer), profile.clone(), ) .await?; diff --git a/crates/router/src/core/subscription/billing_processor_handler.rs b/crates/router/src/core/subscription/billing_processor_handler.rs index 4cc8ad31073..2e1d3b7ff7e 100644 --- a/crates/router/src/core/subscription/billing_processor_handler.rs +++ b/crates/router/src/core/subscription/billing_processor_handler.rs @@ -5,7 +5,8 @@ use common_utils::{ext_traits::ValueExt, pii}; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ - InvoiceRecordBackData, SubscriptionCreateData, SubscriptionCustomerData, + GetSubscriptionPlanPricesData, GetSubscriptionPlansData, InvoiceRecordBackData, + SubscriptionCreateData, SubscriptionCustomerData, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions as subscription_request_types, @@ -27,7 +28,7 @@ pub struct BillingHandler { pub connector_data: api_types::ConnectorData, pub connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams, pub connector_metadata: Option<pii::SecretSerdeValue>, - pub customer: hyperswitch_domain_models::customer::Customer, + pub customer: Option<hyperswitch_domain_models::customer::Customer>, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, } @@ -37,7 +38,7 @@ impl BillingHandler { state: &SessionState, merchant_account: &hyperswitch_domain_models::merchant_account::MerchantAccount, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, - customer: hyperswitch_domain_models::customer::Customer, + customer: Option<hyperswitch_domain_models::customer::Customer>, profile: hyperswitch_domain_models::business_profile::Profile, ) -> errors::RouterResult<Self> { let merchant_connector_id = profile.get_billing_processor_id()?; @@ -109,8 +110,15 @@ impl BillingHandler { billing_address: Option<api_models::payments::Address>, payment_method_data: Option<api_models::payments::PaymentMethodData>, ) -> errors::RouterResult<ConnectorCustomerResponseData> { + let customer = + self.customer + .as_ref() + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "customer", + })?; + let customer_req = ConnectorCustomerData { - email: self.customer.email.clone().map(pii::Email::from), + email: customer.email.clone().map(pii::Email::from), payment_method_data: payment_method_data.clone().map(|pmd| pmd.into()), description: None, phone: None, @@ -275,6 +283,87 @@ impl BillingHandler { } } + pub async fn get_subscription_plans( + &self, + state: &SessionState, + limit: Option<u32>, + offset: Option<u32>, + ) -> errors::RouterResult<subscription_response_types::GetSubscriptionPlansResponse> { + let get_plans_request = + subscription_request_types::GetSubscriptionPlansRequest::new(limit, offset); + + let router_data = self.build_router_data( + state, + get_plans_request, + GetSubscriptionPlansData { + connector_meta_data: self.connector_metadata.clone(), + }, + )?; + + let connector_integration = self.connector_data.connector.get_connector_integration(); + + let response = self + .call_connector( + state, + router_data, + "get subscription plans", + connector_integration, + ) + .await?; + + match response { + Ok(resp) => Ok(resp), + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: self.connector_data.connector_name.to_string().clone(), + status_code: err.status_code, + reason: err.reason, + } + .into()), + } + } + + pub async fn get_subscription_plan_prices( + &self, + state: &SessionState, + plan_price_id: String, + ) -> errors::RouterResult<subscription_response_types::GetSubscriptionPlanPricesResponse> { + let get_plan_prices_request = + subscription_request_types::GetSubscriptionPlanPricesRequest { plan_price_id }; + + let router_data = self.build_router_data( + state, + get_plan_prices_request, + GetSubscriptionPlanPricesData { + connector_meta_data: self.connector_metadata.clone(), + }, + )?; + + let connector_integration = self.connector_data.connector.get_connector_integration(); + + let response = self + .call_connector( + state, + router_data, + "get subscription plan prices", + connector_integration, + ) + .await?; + + match response { + Ok(resp) => Ok(resp), + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: self.connector_data.connector_name.to_string().clone(), + status_code: err.status_code, + reason: err.reason, + } + .into()), + } + } + async fn call_connector<F, ResourceCommonData, Req, Resp>( &self, state: &SessionState, diff --git a/crates/router/src/core/subscription/subscription_handler.rs b/crates/router/src/core/subscription/subscription_handler.rs index 24c08313b82..b11cf517b03 100644 --- a/crates/router/src/core/subscription/subscription_handler.rs +++ b/crates/router/src/core/subscription/subscription_handler.rs @@ -5,6 +5,7 @@ use api_models::{ subscription::{self as subscription_types, SubscriptionResponse, SubscriptionStatus}, }; use common_enums::connector_enums; +use common_utils::{consts, ext_traits::OptionExt}; use diesel_models::subscription::SubscriptionNew; use error_stack::ResultExt; use hyperswitch_domain_models::{ @@ -122,6 +123,60 @@ impl<'a> SubscriptionHandler<'a> { }) } + pub async fn find_and_validate_subscription( + &self, + client_secret: &hyperswitch_domain_models::subscription::ClientSecret, + ) -> errors::RouterResult<()> { + let subscription_id = client_secret.get_subscription_id()?; + + let subscription = self + .state + .store + .find_by_merchant_id_subscription_id( + self.merchant_context.get_merchant_account().get_id(), + subscription_id.to_string(), + ) + .await + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: format!("Subscription not found for id: {subscription_id}"), + }) + .attach_printable("Unable to find subscription")?; + + self.validate_client_secret(client_secret, &subscription)?; + + Ok(()) + } + + pub fn validate_client_secret( + &self, + client_secret: &hyperswitch_domain_models::subscription::ClientSecret, + subscription: &diesel_models::subscription::Subscription, + ) -> errors::RouterResult<()> { + let stored_client_secret = subscription + .client_secret + .clone() + .get_required_value("client_secret") + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "client_secret", + }) + .attach_printable("client secret not found in db")?; + + if client_secret.to_string() != stored_client_secret { + Err(errors::ApiErrorResponse::ClientSecretInvalid.into()) + } else { + let current_timestamp = common_utils::date_time::now(); + let session_expiry = subscription + .created_at + .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); + + if current_timestamp > session_expiry { + Err(errors::ApiErrorResponse::ClientSecretExpired.into()) + } else { + Ok(()) + } + } + } + pub async fn find_subscription( &self, subscription_id: common_utils::id_type::SubscriptionId, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 60724830e0c..57a9aeb1f7f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1187,6 +1187,9 @@ impl Subscription { subscription::create_subscription(state, req, payload) }), )) + .service( + web::resource("/plans").route(web::get().to(subscription::get_subscription_plans)), + ) .service( web::resource("/{subscription_id}/confirm").route(web::post().to( |state, req, id, payload| { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index f6ba2af979a..713b51a9d77 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -87,12 +87,11 @@ impl From<Flow> for ApiIdentifier { | Flow::VolumeSplitOnRoutingType | Flow::DecisionEngineDecideGatewayCall | Flow::DecisionEngineGatewayFeedbackCall => Self::Routing, - Flow::CreateSubscription | Flow::ConfirmSubscription | Flow::CreateAndConfirmSubscription - | Flow::GetSubscription => Self::Subscription, - + | Flow::GetSubscription + | Flow::GetPlansForSubscription => Self::Subscription, Flow::RetrieveForexFlow => Self::Forex, Flow::AddToBlocklist => Self::Blocklist, Flow::DeleteFromBlocklist => Self::Blocklist, diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs index a762da71972..46432810450 100644 --- a/crates/router/src/routes/subscription.rs +++ b/crates/router/src/routes/subscription.rs @@ -60,6 +60,7 @@ pub async fn create_subscription( Ok(id) => id, Err(response) => return response, }; + Box::pin(oss_api::server_wrap( flow, state, @@ -104,6 +105,7 @@ pub async fn confirm_subscription( Ok(id) => id, Err(response) => return response, }; + Box::pin(oss_api::server_wrap( flow, state, @@ -136,6 +138,41 @@ pub async fn confirm_subscription( .await } +#[instrument(skip_all)] +pub async fn get_subscription_plans( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<subscription_types::GetPlansQuery>, +) -> impl Responder { + let flow = Flow::GetPlansForSubscription; + let api_auth = auth::ApiKeyAuth::default(); + + let profile_id = match extract_profile_id(&req) { + Ok(profile_id) => profile_id, + Err(response) => return response, + }; + + let auth_data = match auth::is_ephemeral_auth(req.headers(), api_auth) { + Ok(auth) => auth, + Err(err) => return crate::services::api::log_and_return_error_response(err), + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + query.into_inner(), + |state, auth: auth::AuthenticationData, query, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + subscription::get_subscription_plans(state, merchant_context, profile_id.clone(), query) + }, + &*auth_data, + api_locking::LockAction::NotApplicable, + )) + .await +} + /// Add support for get subscription by id #[instrument(skip_all)] pub async fn get_subscription( diff --git a/crates/router/src/workflows/invoice_sync.rs b/crates/router/src/workflows/invoice_sync.rs index 83aa45dc840..ec2d2d7a913 100644 --- a/crates/router/src/workflows/invoice_sync.rs +++ b/crates/router/src/workflows/invoice_sync.rs @@ -171,7 +171,7 @@ impl<'a> InvoiceSyncHandler<'a> { self.state, &self.merchant_account, &self.key_store, - self.customer.clone(), + Some(self.customer.clone()), self.profile.clone(), ) .await diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 46eef6fab6b..95582124cc5 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -265,6 +265,8 @@ pub enum Flow { RoutingDeleteConfig, /// Subscription create flow, CreateSubscription, + /// Subscription get plans flow, + GetPlansForSubscription, /// Subscription confirm flow, ConfirmSubscription, /// Subscription create and confirm flow,
2025-09-03T08:58:57Z
This pull request introduces a new API endpoint for retrieving subscription plans and the supporting plumbing required for it. The changes include new request/response types, authentication and expiry logic, and routing updates to expose the endpoint. The main themes are new subscription plan retrieval functionality and related codebase integration. **Subscription Plan Retrieval Functionality** * Added a new API endpoint `/subscription/plans/{client_secret}` to fetch available subscription plans, including routing and handler logic in `app.rs` and `subscription.rs`. [[1]](diffhunk://#diff-a6e49b399ffdee83dd322b3cb8bee170c65fb9c6e2e52c14222ec310f6927c54L1176-R1186) [[2]](diffhunk://#diff-d737ada25c830476b3867c693bd362d4b1142773f1b0d971556518b5c04691a3R70-R105) * Implemented the `get_subscription_plans` function in `core/subscription.rs`, which authenticates the client secret, fetches the relevant subscription, and integrates with connector services to retrieve plans. * Introduced helper functions in `core/utils/subscription.rs` for authenticating client secrets and constructing router data for connector calls. **Type and Model Updates** * Added new request and response types for subscription plan retrieval, including `GetPlansResponse` and `GetSubscriptionPlansRequest` with appropriate traits and serialization. [[1]](diffhunk://#diff-3d85d9e288cc67856867986ee406a3102ce1d0cf9fe5c8f9efed3a578608f817R108-R117) [[2]](diffhunk://#diff-8eb3ff11b17aa944306848a821a22486cbad862e5100916531fdcee5a6718636L26-R26) **Routing and Flow Integration** * Updated flow enums and routing logic to support the new subscription plans flow, ensuring correct API identifier mapping and logging. [[1]](diffhunk://#diff-f57d3f577ce7478b78b53d715f35fe97acd4f02ef2043738f053a15100a13ba5R268-R269) [[2]](diffhunk://#diff-0034b07e0697eb780f74742326da73d1e85183054d879fe55143a0ab39c0ee99L93-R93) **Module Organization** * Registered the new `subscription` module under `core/utils.rs` for better code organization.## Type of Change ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create charge-bee mca 2. Create subscription ``` curl --location 'http://localhost:8080/subscription/create' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_dQr2rAikRT2xWZr7R1QL' \ --header 'api-key: dev_wSnWYnMrVFSJ0N25i99QT08Jmx1WBurtbuDl3Ks0XQ1RQn3URdM4UntOenSPHHmT' \ --data '{ "customer_id": "cus_jtJ8WHTHnsguskpiorEt" }' ``` 3. update db (subscription table) with the mca_id ``` UPDATE subscription SET merchant_connector_id = 'mca_QRvgtteGBG6Ip2g1gKtD' WHERE id = 'subscription_vFcn0H8kSTU9bE3Khe05'; ``` 4. Get plans(with client_secret) ``` curl --location 'http://localhost:8080/subscription/plans' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Ske75Nx2J7qtHsP8cc7pFx5k4dccYBedM6UAExaLOdHCkji3uVWSqfmZ0Qz0Tnyj' \ --header 'X-Profile-Id: pro_2WzEeiNyj8fSCObXqo36' ``` Response: ``` [ { "plan_id": "cbdemo_enterprise-suite", "name": "Enterprise Suite", "description": "High-end customer support suite with enterprise-grade solutions.", "price_id": [ { "price_id": "cbdemo_enterprise-suite-monthly", "plan_id": "cbdemo_enterprise-suite", "amount": 14100, "currency": "INR", "interval": "Month", "interval_count": 1, "trial_period": null, "trial_period_unit": null }, { "price_id": "cbdemo_enterprise-suite-annual", "plan_id": "cbdemo_enterprise-suite", "amount": 169000, "currency": "INR", "interval": "Year", "interval_count": 1, "trial_period": null, "trial_period_unit": null } ] }, { "plan_id": "cbdemo_business-suite", "name": "Business Suite", "description": "Advanced customer support plan with premium features.", "price_id": [ { "price_id": "cbdemo_business-suite-monthly", "plan_id": "cbdemo_business-suite", "amount": 9600, "currency": "INR", "interval": "Month", "interval_count": 1, "trial_period": null, "trial_period_unit": null }, { "price_id": "cbdemo_business-suite-annual", "plan_id": "cbdemo_business-suite", "amount": 115000, "currency": "INR", "interval": "Year", "interval_count": 1, "trial_period": null, "trial_period_unit": null } ] }, { "plan_id": "cbdemo_professional-suite", "name": "Professional Suite", "description": "Comprehensive customer support plan with extended capabilities.", "price_id": [ { "price_id": "cbdemo_professional-suite-monthly", "plan_id": "cbdemo_professional-suite", "amount": 4600, "currency": "INR", "interval": "Month", "interval_count": 1, "trial_period": null, "trial_period_unit": null }, { "price_id": "cbdemo_professional-suite-annual", "plan_id": "cbdemo_professional-suite", "amount": 55000, "currency": "INR", "interval": "Year", "interval_count": 1, "trial_period": null, "trial_period_unit": null } ] }, { "plan_id": "cbdemo_essential-support", "name": "Essential Support", "description": "Basic customer support plan with core features.", "price_id": [ { "price_id": "cbdemo_essential-support-monthly", "plan_id": "cbdemo_essential-support", "amount": 1600, "currency": "INR", "interval": "Month", "interval_count": 1, "trial_period": null, "trial_period_unit": null }, { "price_id": "cbdemo_essential-support-annual", "plan_id": "cbdemo_essential-support", "amount": 19000, "currency": "INR", "interval": "Year", "interval_count": 1, "trial_period": null, "trial_period_unit": null } ] } ] ``` 5. Get plans(without client_secret) ``` curl --location 'http://localhost:8080/subscription/plans?subscription_id=subscription_CLjJKIwjKlhuHk1BNOWc' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_UknLiMdqzEcVS5XJiJLqY3kfRT7WznSlbGYkV9kVHGy9GLHmNlNWJxGCEGrljHwt' ``` Response: ``` [ { "plan_id": "cbdemo_enterprise-suite", "name": "Enterprise Suite", "description": "High-end customer support suite with enterprise-grade solutions." }, { "plan_id": "cbdemo_business-suite", "name": "Business Suite", "description": "Advanced customer support plan with premium features." }, { "plan_id": "cbdemo_professional-suite", "name": "Professional Suite", "description": "Comprehensive customer support plan with extended capabilities." }, { "plan_id": "cbdemo_essential-support", "name": "Essential Support", "description": "Basic customer support plan with core features." } ] ``` Subscriptions create - ``` curl --location 'http://localhost:8080/subscriptions/create' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_2WzEeiNyj8fSCObXqo36' \ --header 'api-key: dev_Ske75Nx2J7qtHsP8cc7pFx5k4dccYBedM6UAExaLOdHCkji3uVWSqfmZ0Qz0Tnyj' \ --data '{ "customer_id": "cus_zppXAwRyRF6yXH5PEqJd", "amount": 14100, "currency": "USD", "payment_details": { "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com" } }' ``` Response - ``` {"id":"sub_uIILXUeoPUSzKzl67wyE","merchant_reference_id":null,"status":"created","plan_id":null,"price_id":null,"coupon":null,"profile_id":"pro_2WzEeiNyj8fSCObXqo36","payment":{"payment_id":"pay_niPeSIobMcl8Du4mkYce","status":"requires_payment_method","amount":14100,"currency":"USD","connector":null,"payment_method_id":null,"payment_experience":null,"error_code":null,"error_message":null,"payment_method_type":null,"client_secret":"pay_niPeSIobMcl8Du4mkYce_secret_mdzBqY9TeWppcvjJLIEu"},"customer_id":"cus_zppXAwRyRF6yXH5PEqJd","invoice":{"id":"invoice_FJEWqTVRZUgfzfAoowLi","subscription_id":"sub_uIILXUeoPUSzKzl67wyE","merchant_id":"merchant_1758626894","profile_id":"pro_2WzEeiNyj8fSCObXqo36","merchant_connector_id":"mca_eN6JxSK2NkuT0wSYAH5s","payment_intent_id":"pay_niPeSIobMcl8Du4mkYce","payment_method_id":null,"customer_id":"cus_zppXAwRyRF6yXH5PEqJd","amount":14100,"currency":"USD","status":"invoice_created"},"billing_processor_subscription_id":null} ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
90c7cffcd5b555bb5f18e320f723fce265781e9e
juspay/hyperswitch
juspay__hyperswitch-9437
Bug: [FEATURE] L2-l3 data for checkout ### Feature Description Add l2-l3 data for checkout ### Possible Implementation https://www.checkout.com/docs/payments/manage-payments/submit-level-2-or-level-3-data ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs index 912ea1f5d3e..8ebe17a2acc 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs @@ -1,7 +1,11 @@ -use common_enums::enums::{self, AttemptStatus, PaymentChannel}; +use common_enums::{ + enums::{self, AttemptStatus, PaymentChannel}, + CountryAlpha2, +}; use common_utils::{ errors::{CustomResult, ParsingError}, ext_traits::ByteSliceExt, + id_type::CustomerId, request::Method, types::MinorUnit, }; @@ -25,6 +29,7 @@ use hyperswitch_domain_models::{ use hyperswitch_interfaces::{consts, errors, webhooks}; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; +use serde_with::skip_serializing_none; use time::PrimitiveDateTime; use url::Url; @@ -269,6 +274,54 @@ pub struct ReturnUrl { pub failure_url: Option<String>, } +#[skip_serializing_none] +#[derive(Debug, Default, Serialize)] +pub struct CheckoutCustomer { + pub name: Option<CustomerId>, + pub tax_number: Option<Secret<String>>, +} + +#[skip_serializing_none] +#[derive(Debug, Default, Serialize)] +pub struct CheckoutProcessing { + pub order_id: Option<String>, + pub tax_amount: Option<MinorUnit>, + pub discount_amount: Option<MinorUnit>, + pub duty_amount: Option<MinorUnit>, + pub shipping_amount: Option<MinorUnit>, + pub shipping_tax_amount: Option<MinorUnit>, +} + +#[skip_serializing_none] +#[derive(Debug, Default, Serialize)] +pub struct CheckoutShippingAddress { + pub country: Option<CountryAlpha2>, + pub zip: Option<Secret<String>>, +} + +#[skip_serializing_none] +#[derive(Debug, Default, Serialize)] +pub struct CheckoutShipping { + pub address: Option<CheckoutShippingAddress>, + pub from_address_zip: Option<String>, +} + +#[skip_serializing_none] +#[derive(Debug, Default, Serialize)] +pub struct CheckoutLineItem { + pub commodity_code: Option<String>, + pub discount_amount: Option<MinorUnit>, + pub name: Option<String>, + pub quantity: Option<u16>, + pub reference: Option<String>, + pub tax_exempt: Option<bool>, + pub tax_amount: Option<MinorUnit>, + pub total_amount: Option<MinorUnit>, + pub unit_of_measure: Option<String>, + pub unit_price: Option<MinorUnit>, +} + +#[skip_serializing_none] #[derive(Debug, Serialize)] pub struct PaymentsRequest { pub source: PaymentSource, @@ -285,6 +338,12 @@ pub struct PaymentsRequest { pub payment_type: CheckoutPaymentType, pub merchant_initiated: Option<bool>, pub previous_payment_id: Option<String>, + + // Level 2/3 data fields + pub customer: Option<CheckoutCustomer>, + pub processing: Option<CheckoutProcessing>, + pub shipping: Option<CheckoutShipping>, + pub items: Option<Vec<CheckoutLineItem>>, } #[derive(Debug, Serialize, Deserialize)] @@ -512,8 +571,51 @@ impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequ let auth_type: CheckoutAuthType = connector_auth.try_into()?; let processing_channel_id = auth_type.processing_channel_id; let metadata = item.router_data.request.metadata.clone().map(Into::into); + let (customer, processing, shipping, items) = + if let Some(l2l3_data) = &item.router_data.l2_l3_data { + ( + Some(CheckoutCustomer { + name: l2l3_data.customer_id.clone(), + tax_number: l2l3_data.customer_tax_registration_id.clone(), + }), + Some(CheckoutProcessing { + order_id: l2l3_data.merchant_order_reference_id.clone(), + tax_amount: l2l3_data.order_tax_amount, + discount_amount: l2l3_data.discount_amount, + duty_amount: l2l3_data.duty_amount, + shipping_amount: l2l3_data.shipping_cost, + shipping_tax_amount: l2l3_data.shipping_amount_tax, + }), + Some(CheckoutShipping { + address: Some(CheckoutShippingAddress { + country: l2l3_data.shipping_country, + zip: l2l3_data.shipping_destination_zip.clone(), + }), + from_address_zip: l2l3_data.shipping_origin_zip.clone().map(|z| z.expose()), + }), + l2l3_data.order_details.as_ref().map(|details| { + details + .iter() + .map(|item| CheckoutLineItem { + commodity_code: item.commodity_code.clone(), + discount_amount: item.unit_discount_amount, + name: Some(item.product_name.clone()), + quantity: Some(item.quantity), + reference: item.product_id.clone(), + tax_exempt: None, + tax_amount: item.total_tax_amount, + total_amount: item.total_amount, + unit_of_measure: item.unit_of_measure.clone(), + unit_price: Some(item.amount), + }) + .collect() + }), + ) + } else { + (None, None, None, None) + }; - Ok(Self { + let request = Self { source: source_var, amount: item.amount.to_owned(), currency: item.router_data.request.currency.to_string(), @@ -526,7 +628,13 @@ impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequ payment_type, merchant_initiated, previous_payment_id, - }) + customer, + processing, + shipping, + items, + }; + + Ok(request) } }
2025-09-19T06:29:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Add l2l3 data for checkout - Note : checkout recommends some checks like line_items should sum up proper total and discount amount. But it doesn't throw any errors for this. Hence in this pr we are not adding any such validations . ## Request ```json { "amount": 30000, "capture_method": "automatic", "currency": "USD", "confirm": true, "payment_method": "card", "payment_method_type": "credit", "billing": { "address": { "zip": "560095", "country": "AT", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "payment_method_data": { "card": { "card_number": "4000000000009995", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } }, //l2l3 data "merchant_order_reference_id":"fasdfasfasf", "customer_id": "nithxxinn", "order_tax_amount": 10000, "shipping_cost": 21, "discount_amount": 1, "duty_amount": 2, "shipping_amount_tax":22, "order_details": [ //l2 l3data { "commodity_code": "8471", "unit_discount_amount": 1200, "product_name": "Laptop", "quantity": 1, "product_id":"fafasdfasdfdasdfsadfsadfrewfdscrwefdscerwfdasewfdsacxzfdsasdf", "total_tax_amount": 5000, "amount": 8000, "unit_of_measure": "EA", "unit_price": 8000 }, { "commodity_code": "471", "unit_discount_amount": 34, "product_name": "Laptop", "quantity": 1, "product_id":"fas22df", "total_tax_amount": 3000, "amount": 4000, "unit_of_measure": "EA", "unit_price": 8500 } ] } ``` ## Response ```json { "payment_id": "pay_v01RncbYqwx0ZtB6x7yV", "merchant_id": "merchant_1758258316", "status": "succeeded", "amount": 30000, "net_amount": 40021, "shipping_cost": 21, "amount_capturable": 0, "amount_received": 40021, "connector": "checkout", "client_secret": "pay_v01RncbYqwx0ZtB6x7yV_secret_iolJ5SxVFNsQljPaO42C", "created": "2025-09-19T06:18:02.547Z", "currency": "USD", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "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": "card", "payment_method_data": { "card": { "last4": "9995", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_result": "G", "card_validation_result": "Y" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "AT", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": [ { "sku": null, "upc": null, "brand": null, "amount": 8000, "category": null, "quantity": 1, "tax_rate": null, "product_id": "fafasdfasdfdasdfsadfsadfrewfdscrwefdscerwfdasewfdsacxzfdsasdf", "description": null, "product_name": "Laptop", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": "8471", "unit_of_measure": "EA", "product_img_link": null, "product_tax_code": null, "total_tax_amount": 5000, "requires_shipping": null, "unit_discount_amount": 1200 }, { "sku": null, "upc": null, "brand": null, "amount": 4000, "category": null, "quantity": 1, "tax_rate": null, "product_id": "fas22df", "description": null, "product_name": "Laptop", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": "471", "unit_of_measure": "EA", "product_img_link": null, "product_tax_code": null, "total_tax_amount": 3000, "requires_shipping": null, "unit_discount_amount": 34 } ], "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1758262682, "expires": 1758266282, "secret": "epk_e62d911ac98c4ccea72189e40ad83af4" }, "manual_retry_allowed": null, "connector_transaction_id": "pay_2667htrzd3qu7bx4fk36nkiva4", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_v01RncbYqwx0ZtB6x7yV_1", "payment_link": null, "profile_id": "pro_tqppxjNXH3TckLuEmhDJ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_z4uydERX9Y3VqfGMXeuh", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-19T06:33:02.547Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": "716806996896398", "payment_method_status": null, "updated": "2025-09-19T06:18:04.255Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "fasdfasfasf", "order_tax_amount": 10000, "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` ## connector mapping ```json { "source": { "type": "card", "number": "4000000000009995", "expiry_month": "01", "expiry_year": "2026", "cvv": "100" }, "amount": 40021, "currency": "USD", "processing_channel_id": "pc_jx5lvimg4obe7nhoqnhptm6xoq", "3ds": { "enabled": false, "force_3ds": false, "eci": null, "cryptogram": null, "xid": null, "version": null, "challenge_indicator": "no_preference" }, "success_url": "http://localhost:8080/payments/pay_v01RncbYqwx0ZtB6x7yV/merchant_1758258316/redirect/response/checkout?status=success", "failure_url": "http://localhost:8080/payments/pay_v01RncbYqwx0ZtB6x7yV/merchant_1758258316/redirect/response/checkout?status=failure", "capture": true, "reference": "pay_v01RncbYqwx0ZtB6x7yV_1", "payment_type": "Regular", "merchant_initiated": false, "customer": { "name": "nithxxinn" }, "processing": { "order_id": "fasdfasfasf", "tax_amount": 10000, "discount_amount": 1, "duty_amount": 2, "shipping_amount": 21, "shipping_tax_amount": 22 }, "shipping": { "address": {} }, "items": [ { "commodity_code": "8471", "discount_amount": 1200, "name": "Laptop", "quantity": 1, "reference": "fafasdfasdfdasdfsadfsadfrewfdscrwefdscerwfdasewfdsacxzfdsasdf", "tax_amount": 5000, "unit_of_measure": "EA", "unit_price": 8000 }, { "commodity_code": "471", "discount_amount": 34, "name": "Laptop", "quantity": 1, "reference": "fas22df", "tax_amount": 3000, "unit_of_measure": "EA", "unit_price": 4000 } ] } ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
8930e1ed289bb4c128da664849af1095bafd45a7
juspay/hyperswitch
juspay__hyperswitch-9447
Bug: [BUG] Failed payment for Cashtocode via UCS returns status requires_merchant_action ### Bug Description In UCS when we get None as attempt status we map it to payments_grpc::PaymentStatus::AttemptStatusUnspecified. In payments via Unified Connector Service path, when for error responses it returned attempt_status_unspecified, it was being mapped to AttemptStatus::Unresolved instead of None. This prevented the proper failure handling logic from executing, causing payments that should fail to not return the expected failure status. ### Expected Behavior Failed payments should return failed status ### Actual Behavior Failed payments gave requires_merchant_action status ### Steps To Reproduce Make a payment for cashtocode via UCS with wrong currency/creds. ### Context For The Bug _No response_ ### Environment macos sequoia rustc 1.87.0 ### 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/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 031fd0de7ce..93f7339b954 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -888,14 +888,17 @@ async fn call_unified_connector_service_authorize( let payment_authorize_response = response.into_inner(); - let (status, router_data_response, status_code) = + let (router_data_response, status_code) = handle_unified_connector_service_response_for_payment_authorize( payment_authorize_response.clone(), ) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize UCS response")?; - router_data.status = status; + let router_data_response = router_data_response.map(|(response, status)| { + router_data.status = status; + response + }); router_data.response = router_data_response; router_data.raw_connector_response = payment_authorize_response .raw_connector_response @@ -972,14 +975,17 @@ async fn call_unified_connector_service_repeat_payment( let payment_repeat_response = response.into_inner(); - let (status, router_data_response, status_code) = + let (router_data_response, status_code) = handle_unified_connector_service_response_for_payment_repeat( payment_repeat_response.clone(), ) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize UCS response")?; - router_data.status = status; + let router_data_response = router_data_response.map(|(response, status)| { + router_data.status = status; + response + }); router_data.response = router_data_response; router_data.raw_connector_response = payment_repeat_response .raw_connector_response diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs index fca6c1d3c03..42482131610 100644 --- a/crates/router/src/core/payments/flows/external_proxy_flow.rs +++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs @@ -428,14 +428,17 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData> let payment_authorize_response = response.into_inner(); - let (status, router_data_response, status_code) = + let (router_data_response, status_code) = unified_connector_service::handle_unified_connector_service_response_for_payment_authorize( payment_authorize_response.clone(), ) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize UCS response")?; - router_data.status = status; + let router_data_response = router_data_response.map(|(response, status)|{ + router_data.status = status; + response + }); router_data.response = router_data_response; router_data.raw_connector_response = payment_authorize_response .raw_connector_response diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 9683129ca97..404d14923da 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -295,14 +295,17 @@ impl Feature<api::PSync, types::PaymentsSyncData> let payment_get_response = response.into_inner(); - let (status, router_data_response, status_code) = + let (router_data_response, status_code) = handle_unified_connector_service_response_for_payment_get( payment_get_response.clone(), ) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize UCS response")?; - router_data.status = status; + let router_data_response = router_data_response.map(|(response, status)| { + router_data.status = status; + response + }); router_data.response = router_data_response; router_data.raw_connector_response = payment_get_response .raw_connector_response diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 6e30faf7143..3831ac09ba0 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -317,14 +317,17 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup let payment_register_response = response.into_inner(); - let (status, router_data_response, status_code) = + let (router_data_response, status_code) = handle_unified_connector_service_response_for_payment_register( payment_register_response.clone(), ) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize UCS response")?; - router_data.status = status; + let router_data_response = router_data_response.map(|(response, status)| { + router_data.status = status; + response + }); router_data.response = router_data_response; router_data.connector_http_status_code = Some(status_code); diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 3792cfa280e..62f72860d09 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -55,6 +55,15 @@ pub mod transformers; // Re-export webhook transformer types for easier access pub use transformers::WebhookTransformData; +/// Type alias for return type used by unified connector service response handlers +type UnifiedConnectorServiceResult = CustomResult< + ( + Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>, + u16, + ), + UnifiedConnectorServiceError, +>; + /// Generic version of should_call_unified_connector_service that works with any type /// implementing OperationSessionGetters trait pub async fn should_call_unified_connector_service<F: Clone, T, D>( @@ -570,82 +579,46 @@ pub fn build_unified_connector_service_external_vault_proxy_metadata( pub fn handle_unified_connector_service_response_for_payment_authorize( response: PaymentServiceAuthorizeResponse, -) -> CustomResult< - ( - AttemptStatus, - Result<PaymentsResponseData, ErrorResponse>, - u16, - ), - UnifiedConnectorServiceError, -> { - let status = AttemptStatus::foreign_try_from(response.status())?; - +) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = - Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; + Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; - Ok((status, router_data_response, status_code)) + Ok((router_data_response, status_code)) } pub fn handle_unified_connector_service_response_for_payment_get( response: payments_grpc::PaymentServiceGetResponse, -) -> CustomResult< - ( - AttemptStatus, - Result<PaymentsResponseData, ErrorResponse>, - u16, - ), - UnifiedConnectorServiceError, -> { - let status = AttemptStatus::foreign_try_from(response.status())?; - +) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = - Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; + Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; - Ok((status, router_data_response, status_code)) + Ok((router_data_response, status_code)) } pub fn handle_unified_connector_service_response_for_payment_register( response: payments_grpc::PaymentServiceRegisterResponse, -) -> CustomResult< - ( - AttemptStatus, - Result<PaymentsResponseData, ErrorResponse>, - u16, - ), - UnifiedConnectorServiceError, -> { - let status = AttemptStatus::foreign_try_from(response.status())?; - +) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = - Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; + Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; - Ok((status, router_data_response, status_code)) + Ok((router_data_response, status_code)) } pub fn handle_unified_connector_service_response_for_payment_repeat( response: payments_grpc::PaymentServiceRepeatEverythingResponse, -) -> CustomResult< - ( - AttemptStatus, - Result<PaymentsResponseData, ErrorResponse>, - u16, - ), - UnifiedConnectorServiceError, -> { - let status = AttemptStatus::foreign_try_from(response.status())?; - +) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = - Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; + Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; - Ok((status, router_data_response, status_code)) + Ok((router_data_response, status_code)) } pub fn build_webhook_secrets_from_merchant_connector_account( diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index b7dc46788c5..70d0ee40bdc 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -512,15 +512,13 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon } impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> - for Result<PaymentsResponseData, ErrorResponse> + for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse> { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from( response: payments_grpc::PaymentServiceAuthorizeResponse, ) -> Result<Self, Self::Error> { - let status = AttemptStatus::foreign_try_from(response.status())?; - let connector_response_reference_id = response.response_ref_id.as_ref().and_then(|identifier| { identifier @@ -573,12 +571,17 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> let status_code = convert_connector_service_status_code(response.status_code)?; let response = if response.error_code.is_some() { + let attempt_status = match response.status() { + payments_grpc::PaymentStatus::AttemptStatusUnspecified => None, + _ => Some(AttemptStatus::foreign_try_from(response.status())?), + }; + Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), status_code, - attempt_status: Some(status), + attempt_status, connector_transaction_id: connector_response_reference_id, network_decline_code: None, network_advice_code: None, @@ -586,16 +589,21 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> connector_metadata: None, }) } else { - Ok(PaymentsResponseData::TransactionResponse { - resource_id, - redirection_data: Box::new(redirection_data), - mandate_reference: Box::new(None), - connector_metadata, - network_txn_id: response.network_txn_id.clone(), - connector_response_reference_id, - incremental_authorization_allowed: response.incremental_authorization_allowed, - charges: None, - }) + let status = AttemptStatus::foreign_try_from(response.status())?; + + Ok(( + PaymentsResponseData::TransactionResponse { + resource_id, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), + connector_metadata, + network_txn_id: response.network_txn_id.clone(), + connector_response_reference_id, + incremental_authorization_allowed: response.incremental_authorization_allowed, + charges: None, + }, + status, + )) }; Ok(response) @@ -603,15 +611,13 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> } impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> - for Result<PaymentsResponseData, ErrorResponse> + for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse> { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from( response: payments_grpc::PaymentServiceGetResponse, ) -> Result<Self, Self::Error> { - let status = AttemptStatus::foreign_try_from(response.status())?; - let connector_response_reference_id = response.response_ref_id.as_ref().and_then(|identifier| { identifier @@ -635,12 +641,17 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> }; let response = if response.error_code.is_some() { + let attempt_status = match response.status() { + payments_grpc::PaymentStatus::AttemptStatusUnspecified => None, + _ => Some(AttemptStatus::foreign_try_from(response.status())?), + }; + Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), status_code, - attempt_status: Some(status), + attempt_status, connector_transaction_id: connector_response_reference_id, network_decline_code: None, network_advice_code: None, @@ -648,23 +659,28 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> connector_metadata: None, }) } else { - Ok(PaymentsResponseData::TransactionResponse { - resource_id, - redirection_data: Box::new(None), - mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| { - hyperswitch_domain_models::router_response_types::MandateReference { - connector_mandate_id: grpc_mandate.mandate_id, - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - } - })), - connector_metadata: None, - network_txn_id: response.network_txn_id.clone(), - connector_response_reference_id, - incremental_authorization_allowed: None, - charges: None, - }) + let status = AttemptStatus::foreign_try_from(response.status())?; + + Ok(( + PaymentsResponseData::TransactionResponse { + resource_id, + redirection_data: Box::new(None), + mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| { + hyperswitch_domain_models::router_response_types::MandateReference { + connector_mandate_id: grpc_mandate.mandate_id, + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + } + })), + connector_metadata: None, + network_txn_id: response.network_txn_id.clone(), + connector_response_reference_id, + incremental_authorization_allowed: None, + charges: None, + }, + status, + )) }; Ok(response) @@ -672,15 +688,13 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> } impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse> - for Result<PaymentsResponseData, ErrorResponse> + for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse> { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from( response: payments_grpc::PaymentServiceRegisterResponse, ) -> Result<Self, Self::Error> { - let status = AttemptStatus::foreign_try_from(response.status())?; - let connector_response_reference_id = response.response_ref_id.as_ref().and_then(|identifier| { identifier @@ -698,12 +712,16 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse> let status_code = convert_connector_service_status_code(response.status_code)?; let response = if response.error_code.is_some() { + let attempt_status = match response.status() { + payments_grpc::PaymentStatus::AttemptStatusUnspecified => None, + _ => Some(AttemptStatus::foreign_try_from(response.status())?), + }; Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), status_code, - attempt_status: Some(status), + attempt_status, connector_transaction_id: connector_response_reference_id, network_decline_code: None, network_advice_code: None, @@ -711,7 +729,9 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse> connector_metadata: None, }) } else { - Ok(PaymentsResponseData::TransactionResponse { + let status = AttemptStatus::foreign_try_from(response.status())?; + + Ok((PaymentsResponseData::TransactionResponse { resource_id: response.registration_id.as_ref().and_then(|identifier| { identifier .id_type @@ -748,7 +768,7 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse> connector_response_reference_id, incremental_authorization_allowed: response.incremental_authorization_allowed, charges: None, - }) + }, status)) }; Ok(response) @@ -756,15 +776,13 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse> } impl ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse> - for Result<PaymentsResponseData, ErrorResponse> + for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse> { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from( response: payments_grpc::PaymentServiceRepeatEverythingResponse, ) -> Result<Self, Self::Error> { - let status = AttemptStatus::foreign_try_from(response.status())?; - let connector_response_reference_id = response.response_ref_id.as_ref().and_then(|identifier| { identifier @@ -790,12 +808,16 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse> let status_code = convert_connector_service_status_code(response.status_code)?; let response = if response.error_code.is_some() { + let attempt_status = match response.status() { + payments_grpc::PaymentStatus::AttemptStatusUnspecified => None, + _ => Some(AttemptStatus::foreign_try_from(response.status())?), + }; Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), status_code, - attempt_status: Some(status), + attempt_status, connector_transaction_id: transaction_id, network_decline_code: None, network_advice_code: None, @@ -803,7 +825,9 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse> connector_metadata: None, }) } else { - Ok(PaymentsResponseData::TransactionResponse { + let status = AttemptStatus::foreign_try_from(response.status())?; + + Ok((PaymentsResponseData::TransactionResponse { resource_id: match transaction_id.as_ref() { Some(transaction_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(transaction_id.clone()), None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, @@ -815,7 +839,7 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse> connector_response_reference_id, incremental_authorization_allowed: None, charges: None, - }) + }, status)) }; Ok(response) diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 0fd012e9f7a..d627a3c04cb 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -170,7 +170,7 @@ where } }?; - let (status, router_data_response, status_code) = + let (router_data_response, status_code) = unified_connector_service::handle_unified_connector_service_response_for_payment_get( payment_get_response.clone(), ) @@ -178,7 +178,10 @@ where .attach_printable("Failed to process UCS webhook response using PSync handler")?; let mut updated_router_data = router_data; - updated_router_data.status = status; + let router_data_response = router_data_response.map(|(response, status)| { + updated_router_data.status = status; + response + }); let _ = router_data_response.map_err(|error_response| { updated_router_data.response = Err(error_response);
2025-09-18T18:13:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> In UCS when we get None as attempt status we map it to `payments_grpc::PaymentStatus::AttemptStatusUnspecified`. In payments via Unified Connector Service path, when for error responses it returned `attempt_status_unspecified`, it was being mapped to `AttemptStatus::Unresolved` instead of `None`. This prevented the proper failure handling logic from executing, causing payments that should fail to not return the expected failure status. FIX: - Changed the mapping of `payments_grpc::PaymentStatus::AttemptStatusUnspecified` from `Ok(Self::Unresolved)` to `Ok(None)` in case of Errorresponse. - Wrapped Attemptstatus in Ok response and router_data.status is updated in case of Ok response only. - Allows proper failure logic to execute instead of forcing payments to Unresolved state ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context In UCS when we get None as attempt status we map it to `payments_grpc::PaymentStatus::AttemptStatusUnspecified`. In payments via Unified Connector Service path, when for error responses it returned `attempt_status_unspecified`, it was being mapped to `AttemptStatus::Unresolved` instead of `None`. This prevented the proper failure handling logic from executing, causing payments that should fail to not return the expected failure status. <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Make a payment via UCS for cashtocode which should fail.(Wrong currency/pmt combination EUR+Evoucher) Request ```json { "amount": 1000, "currency": "EUR", "confirm": true, "payment_method_data": "reward", "payment_method_type": "evoucher", "payment_method":"reward", "capture_method": "automatic", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "en-US", "color_depth": 24, "screen_height": 1117, "screen_width": 1728, "time_zone": -330, "java_enabled": true, "java_script_enabled": true }, "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://www.google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" }, "phone": { "number": "1233456789", "country_code": "+1" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" }, "phone": { "number": "1233456789", "country_code": "+1" } } } ``` Response ```json { "payment_id": "pay_eOOvKUOzk8dfmIILn2kg", "merchant_id": "merchant_1758217838", "status": "failed", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "cashtocode", "client_secret": "pay_eOOvKUOzk8dfmIILn2kg_secret_25bCUExuNbcQIyhhU6j2", "created": "2025-09-22T17:14:03.089Z", "currency": "USD", "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "customer": { "id": "cus_5ZiQdWmdv9efuLCPWeoN", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "reward", "payment_method_data": "reward", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null, "origin_zip": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null, "origin_zip": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "\"bad_request\"", "error_message": "Validation errors occured while creating/updating paytoken", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "evoucher", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "created_at": 1758561243, "expires": 1758564843, "secret": "epk_1fcce0a1fa2f403f9a63b9e03e153e33" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "unified_connector_service" }, "reference_id": null, "payment_link": null, "profile_id": "pro_kOI1WKKcE3imNaYJENz3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tjMqk5r3abjCMBxp7WAy", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-22T17:29:03.089Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": -330, "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "color_depth": 24, "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-22T17:14:04.092Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": "{\"errors\":[{\"message\":\"requestedUrl must be a valid URL\",\"type\":\"Validation error\",\"path\":\"requestedUrl\"},{\"message\":\"cancelUrl must be empty or a valid URL\",\"type\":\"Validation error\",\"path\":\"cancelUrl\"}],\"error\":\"bad_request\",\"error_description\":\"Validation errors occured while creating/updating paytoken\"}", "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": { "network_advice_code": null } } ``` success case unchanged ```json { "payment_id": "pay_cpaXS8mYQTM0j8WoynYq", "merchant_id": "merchant_1758105428", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "fiuu", "client_secret": "pay_cpaXS8mYQTM0j8WoynYq_secret_YV89WcIDUTqpzr7FnDA2", "created": "2025-09-22T17:15:24.386Z", "currency": "MYR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "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": "12", "card_exp_year": "2029", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Musterhausen", "country": "MY", "line1": "Musterstr", "line2": "CA", "line3": "CA", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Musterhausen", "country": "MY", "line1": "1467", "line2": "CA", "line3": "CA", "zip": "12345", "state": "California", "first_name": "Max", "last_name": "Mustermann", "origin_zip": null }, "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": "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": "StripeCustomer", "created_at": 1758561324, "expires": 1758564924, "secret": "epk_f470436ee1e546399b67d346f0bb3428" }, "manual_retry_allowed": null, "connector_transaction_id": "31048203", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "unified_connector_service" }, "reference_id": null, "payment_link": null, "profile_id": "pro_YLnpohCCiP6L0NP2H5No", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_renfow5Kuk3DLSsizTH4", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-22T17:30:24.386Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "103.77.139.95", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-22T17:15:25.498Z", "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": "..........", "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ab00b083e963a5d5228af6b061b603a68d7efa17
juspay/hyperswitch
juspay__hyperswitch-9451
Bug: [FEATURE]: [GIGADAT] Connector Template Code Connector Template Code for Gigadat
diff --git a/config/config.example.toml b/config/config.example.toml index bae0da78fbb..ea27effe833 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -233,6 +233,7 @@ fiuu.secondary_base_url="https://sandbox.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-test.getneteurope.com/engine/rest" +gigadat.base_url = "https://interac.express-connect.com/" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api-sandbox.gocardless.com" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index f1addc2b581..c381bc0596a 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -72,6 +72,7 @@ fiuu.secondary_base_url="https://sandbox.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-test.getneteurope.com/engine/rest" +gigadat.base_url = "https://interac.express-connect.com/" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api-sandbox.gocardless.com" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 3fd609dd9b7..34bfffa8f3f 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -76,6 +76,7 @@ fiuu.secondary_base_url="https://api.merchant.razer.com/" fiuu.third_base_url="https://api.merchant.razer.com/" forte.base_url = "https://api.forte.net/v3" getnet.base_url = "https://api.getneteurope.com/engine/rest" +gigadat.base_url = "https://interac.express-connect.com/" globalpay.base_url = "https://apis.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api.gocardless.com" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 44238899b50..a13157b860e 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -76,6 +76,7 @@ fiuu.secondary_base_url="https://sandbox.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-test.getneteurope.com/engine/rest" +gigadat.base_url = "https://interac.express-connect.com/" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api-sandbox.gocardless.com" diff --git a/config/development.toml b/config/development.toml index e145d1eb087..b05755409e0 100644 --- a/config/development.toml +++ b/config/development.toml @@ -271,6 +271,7 @@ fiuu.secondary_base_url = "https://sandbox.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-test.getneteurope.com/engine/rest" +gigadat.base_url = "https://interac.express-connect.com/" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api-sandbox.gocardless.com" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c36904d5fe8..896f3eeba6b 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -159,6 +159,7 @@ fiuu.secondary_base_url = "https://sandbox.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-test.getneteurope.com/engine/rest" +gigadat.base_url = "https://interac.express-connect.com/" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api-sandbox.gocardless.com" diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 186e08989ec..9dc646f36d7 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -273,6 +273,7 @@ pub struct ConnectorConfig { pub flexiti: Option<ConnectorTomlConfig>, pub forte: Option<ConnectorTomlConfig>, pub getnet: Option<ConnectorTomlConfig>, + pub gigadat: Option<ConnectorTomlConfig>, pub globalpay: Option<ConnectorTomlConfig>, pub globepay: Option<ConnectorTomlConfig>, pub gocardless: Option<ConnectorTomlConfig>, diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 7d68c4de4fb..e27c801fafb 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -7089,3 +7089,7 @@ type="Text" [tokenex] [tokenex.connector_auth.HeaderKey] api_key = "API Key" + +[gigadat] +[gigadat.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index eff63730974..6d026312b56 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5807,3 +5807,7 @@ type="Text" [tokenex] [tokenex.connector_auth.HeaderKey] api_key = "API Key" + +[gigadat] +[gigadat.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 379ea955c9a..96b9586f3c7 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -7070,3 +7070,7 @@ type="Text" [tokenex] [tokenex.connector_auth.HeaderKey] api_key = "API Key" + +[gigadat] +[gigadat.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 806c21859f7..d0b8ed74eb9 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -46,6 +46,7 @@ pub mod fiuu; pub mod flexiti; pub mod forte; pub mod getnet; +pub mod gigadat; pub mod globalpay; pub mod globepay; pub mod gocardless; @@ -142,10 +143,10 @@ pub use self::{ custombilling::Custombilling, cybersource::Cybersource, datatrans::Datatrans, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, dwolla::Dwolla, ebanx::Ebanx, elavon::Elavon, facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, - fiuu::Fiuu, flexiti::Flexiti, forte::Forte, getnet::Getnet, globalpay::Globalpay, - globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments, helcim::Helcim, hipay::Hipay, - hyperswitch_vault::HyperswitchVault, hyperwallet::Hyperwallet, iatapay::Iatapay, - inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, + fiuu::Fiuu, flexiti::Flexiti, forte::Forte, getnet::Getnet, gigadat::Gigadat, + globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments, + helcim::Helcim, hipay::Hipay, hyperswitch_vault::HyperswitchVault, hyperwallet::Hyperwallet, + iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, katapult::Katapult, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, mpgs::Mpgs, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat.rs b/crates/hyperswitch_connectors/src/connectors/gigadat.rs new file mode 100644 index 00000000000..bebad38b04c --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/gigadat.rs @@ -0,0 +1,621 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::enums; +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::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 gigadat; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Gigadat { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Gigadat { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Gigadat {} +impl api::PaymentSession for Gigadat {} +impl api::ConnectorAccessToken for Gigadat {} +impl api::MandateSetup for Gigadat {} +impl api::PaymentAuthorize for Gigadat {} +impl api::PaymentSync for Gigadat {} +impl api::PaymentCapture for Gigadat {} +impl api::PaymentVoid for Gigadat {} +impl api::Refund for Gigadat {} +impl api::RefundExecute for Gigadat {} +impl api::RefundSync for Gigadat {} +impl api::PaymentToken for Gigadat {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Gigadat +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gigadat +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 Gigadat { + fn id(&self) -> &'static str { + "gigadat" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.gigadat.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = gigadat::GigadatAuthType::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: gigadat::GigadatErrorResponse = res + .response + .parse_struct("GigadatErrorResponse") + .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, + connector_metadata: None, + }) + } +} + +impl ConnectorValidation for Gigadat { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Gigadat { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Gigadat {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Gigadat {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Gigadat { + 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 = gigadat::GigadatRouterData::from((amount, req)); + let connector_req = gigadat::GigadatPaymentsRequest::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: gigadat::GigadatPaymentsResponse = res + .response + .parse_struct("Gigadat 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 Gigadat { + 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: gigadat::GigadatPaymentsResponse = res + .response + .parse_struct("gigadat 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 Gigadat { + 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: gigadat::GigadatPaymentsResponse = res + .response + .parse_struct("Gigadat 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 Gigadat {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gigadat { + 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 = gigadat::GigadatRouterData::from((refund_amount, req)); + let connector_req = gigadat::GigadatRefundRequest::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: gigadat::RefundResponse = res + .response + .parse_struct("gigadat 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 Gigadat { + 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: gigadat::RefundResponse = res + .response + .parse_struct("gigadat 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 Gigadat { + 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)) + } +} + +static GIGADAT_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static GIGADAT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Gigadat", + description: "Gigadat connector", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, +}; + +static GIGADAT_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Gigadat { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&GIGADAT_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*GIGADAT_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&GIGADAT_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs new file mode 100644 index 00000000000..db58300ed34 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs @@ -0,0 +1,219 @@ +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}; + +//TODO: Fill the struct with respective fields +pub struct GigadatRouterData<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 GigadatRouterData<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 GigadatPaymentsRequest { + amount: StringMinorUnit, + card: GigadatCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct GigadatCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&GigadatRouterData<&PaymentsAuthorizeRouterData>> for GigadatPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &GigadatRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct GigadatAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for GigadatAuthType { + 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, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum GigadatPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<GigadatPaymentStatus> for common_enums::AttemptStatus { + fn from(item: GigadatPaymentStatus) -> Self { + match item { + GigadatPaymentStatus::Succeeded => Self::Charged, + GigadatPaymentStatus::Failed => Self::Failure, + GigadatPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct GigadatPaymentsResponse { + status: GigadatPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, GigadatPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, GigadatPaymentsResponse, 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 GigadatRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&GigadatRouterData<&RefundsRouterData<F>>> for GigadatRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &GigadatRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 GigadatErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 3a5c3e77bc3..057aca866f4 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -214,6 +214,7 @@ default_imp_for_authorize_session_token!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -357,6 +358,7 @@ default_imp_for_calculate_tax!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -499,6 +501,7 @@ default_imp_for_session_update!( connectors::Fiservemea, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, @@ -643,6 +646,7 @@ default_imp_for_post_session_tokens!( connectors::Fiservemea, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, @@ -785,6 +789,7 @@ default_imp_for_create_order!( connectors::Fiservemea, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, @@ -929,6 +934,7 @@ default_imp_for_update_metadata!( connectors::Fiservemea, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, @@ -1073,6 +1079,7 @@ default_imp_for_cancel_post_capture!( connectors::Fiservemea, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, @@ -1212,6 +1219,7 @@ default_imp_for_complete_authorize!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, @@ -1342,6 +1350,7 @@ default_imp_for_incremental_authorization!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1480,6 +1489,7 @@ default_imp_for_create_customer!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gpayments, @@ -1618,6 +1628,7 @@ default_imp_for_connector_redirect_response!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, @@ -1746,6 +1757,7 @@ default_imp_for_pre_authenticate_steps!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1889,6 +1901,7 @@ default_imp_for_authenticate_steps!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2032,6 +2045,7 @@ default_imp_for_post_authenticate_steps!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2173,6 +2187,7 @@ default_imp_for_pre_processing_steps!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gpayments, @@ -2305,6 +2320,7 @@ default_imp_for_post_processing_steps!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2450,6 +2466,7 @@ default_imp_for_approve!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2596,6 +2613,7 @@ default_imp_for_reject!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2743,6 +2761,7 @@ default_imp_for_webhook_source_verification!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2886,6 +2905,7 @@ default_imp_for_accept_dispute!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3029,6 +3049,7 @@ default_imp_for_submit_evidence!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3171,6 +3192,7 @@ default_imp_for_defend_dispute!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3317,6 +3339,7 @@ default_imp_for_fetch_disputes!( connectors::Forte, connectors::Flexiti, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3462,6 +3485,7 @@ default_imp_for_dispute_sync!( connectors::Forte, connectors::Flexiti, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3614,6 +3638,7 @@ default_imp_for_file_upload!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3748,6 +3773,7 @@ default_imp_for_payouts!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3888,6 +3914,7 @@ default_imp_for_payouts_create!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4032,6 +4059,7 @@ default_imp_for_payouts_retrieve!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4174,6 +4202,7 @@ default_imp_for_payouts_eligibility!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4317,6 +4346,7 @@ default_imp_for_payouts_fulfill!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4457,6 +4487,7 @@ default_imp_for_payouts_cancel!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4601,6 +4632,7 @@ default_imp_for_payouts_quote!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4746,6 +4778,7 @@ default_imp_for_payouts_recipient!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4891,6 +4924,7 @@ default_imp_for_payouts_recipient_account!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -5037,6 +5071,7 @@ default_imp_for_frm_sale!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -5183,6 +5218,7 @@ default_imp_for_frm_checkout!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -5329,6 +5365,7 @@ default_imp_for_frm_transaction!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -5475,6 +5512,7 @@ default_imp_for_frm_fulfillment!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -5621,6 +5659,7 @@ default_imp_for_frm_record_return!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -5762,6 +5801,7 @@ default_imp_for_revoking_mandates!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -5906,6 +5946,7 @@ default_imp_for_uas_pre_authentication!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -6049,6 +6090,7 @@ default_imp_for_uas_post_authentication!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -6193,6 +6235,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -6329,6 +6372,7 @@ default_imp_for_connector_request_id!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -6467,6 +6511,7 @@ default_imp_for_fraud_check!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -6635,6 +6680,7 @@ default_imp_for_connector_authentication!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -6776,6 +6822,7 @@ default_imp_for_uas_authentication!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -6912,6 +6959,7 @@ default_imp_for_revenue_recovery!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -7072,6 +7120,7 @@ default_imp_for_subscriptions!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -7219,6 +7268,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -7364,6 +7414,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -7509,6 +7560,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -7648,6 +7700,7 @@ default_imp_for_external_vault!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -7793,6 +7846,7 @@ default_imp_for_external_vault_insert!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -7936,6 +7990,7 @@ default_imp_for_gift_card_balance_check!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -8082,6 +8137,7 @@ default_imp_for_external_vault_retrieve!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -8227,6 +8283,7 @@ default_imp_for_external_vault_delete!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -8374,6 +8431,7 @@ default_imp_for_external_vault_create!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -8518,6 +8576,7 @@ default_imp_for_connector_authentication_token!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -8661,6 +8720,7 @@ default_imp_for_external_vault_proxy_payments_create!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 5f67ba53ec7..621e41dcb93 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -314,6 +314,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -461,6 +462,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -599,6 +601,7 @@ default_imp_for_new_connector_integration_connector_authentication_token!( connectors::Fiuu, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -735,6 +738,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -881,6 +885,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1027,6 +1032,7 @@ default_imp_for_new_connector_integration_fetch_disputes!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1174,6 +1180,7 @@ default_imp_for_new_connector_integration_dispute_sync!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1321,6 +1328,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1466,6 +1474,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1622,6 +1631,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1770,6 +1780,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -1918,6 +1929,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2066,6 +2078,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2214,6 +2227,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2362,6 +2376,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2510,6 +2525,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2658,6 +2674,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2806,6 +2823,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -2952,6 +2970,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3100,6 +3119,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3248,6 +3268,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3396,6 +3417,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3544,6 +3566,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3692,6 +3715,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3838,6 +3862,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -3930,6 +3955,7 @@ macro_rules! default_imp_for_new_connector_integration_frm { #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm!( + connectors::Gigadat, connectors::Affirm, connectors::Paytm, connectors::Airwallex, @@ -4075,6 +4101,7 @@ macro_rules! default_imp_for_new_connector_integration_connector_authentication } default_imp_for_new_connector_integration_connector_authentication!( + connectors::Gigadat, connectors::Affirm, connectors::Paytm, connectors::Airwallex, @@ -4209,6 +4236,7 @@ macro_rules! default_imp_for_new_connector_integration_revenue_recovery { } default_imp_for_new_connector_integration_revenue_recovery!( + connectors::Gigadat, connectors::Affirm, connectors::Paytm, connectors::Airwallex, @@ -4399,6 +4427,7 @@ default_imp_for_new_connector_integration_external_vault!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, @@ -4544,6 +4573,7 @@ default_imp_for_new_connector_integration_external_vault_proxy!( connectors::Flexiti, connectors::Forte, connectors::Getnet, + connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rs index 739f89ce4d5..cca03101902 100644 --- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs +++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs @@ -61,6 +61,7 @@ pub struct Connectors { pub flexiti: ConnectorParams, pub forte: ConnectorParams, pub getnet: ConnectorParams, + pub gigadat: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index b378e685f56..895d9ae1a2e 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -19,30 +19,31 @@ pub use hyperswitch_connectors::connectors::{ deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, dwolla, dwolla::Dwolla, ebanx, ebanx::Ebanx, elavon, elavon::Elavon, facilitapay, facilitapay::Facilitapay, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, - fiuu::Fiuu, flexiti, flexiti::Flexiti, forte, forte::Forte, getnet, getnet::Getnet, globalpay, - globalpay::Globalpay, globepay, globepay::Globepay, gocardless, gocardless::Gocardless, - gpayments, gpayments::Gpayments, helcim, helcim::Helcim, hipay, hipay::Hipay, - hyperswitch_vault, hyperswitch_vault::HyperswitchVault, hyperwallet, hyperwallet::Hyperwallet, - iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, - jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, katapult, - katapult::Katapult, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, mollie, - mollie::Mollie, moneris, moneris::Moneris, mpgs, mpgs::Mpgs, multisafepay, - multisafepay::Multisafepay, netcetera, netcetera::Netcetera, nexinets, nexinets::Nexinets, - nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, - nordea, nordea::Nordea, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, - opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payload, - payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paysafe, - paysafe::Paysafe, paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, - peachpayments, peachpayments::Peachpayments, phonepe, phonepe::Phonepe, placetopay, - placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, - prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, - recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, santander, - santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, - silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, - stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, - threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, - tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, - trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, + fiuu::Fiuu, flexiti, flexiti::Flexiti, forte, forte::Forte, getnet, getnet::Getnet, gigadat, + gigadat::Gigadat, globalpay, globalpay::Globalpay, globepay, globepay::Globepay, gocardless, + gocardless::Gocardless, gpayments, gpayments::Gpayments, helcim, helcim::Helcim, hipay, + hipay::Hipay, hyperswitch_vault, hyperswitch_vault::HyperswitchVault, hyperwallet, + hyperwallet::Hyperwallet, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, + itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, + juspaythreedsserver::Juspaythreedsserver, katapult, katapult::Katapult, klarna, klarna::Klarna, + mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, mpgs, + mpgs::Mpgs, multisafepay, multisafepay::Multisafepay, netcetera, netcetera::Netcetera, + nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, + nomupay::Nomupay, noon, noon::Noon, nordea, nordea::Nordea, novalnet, novalnet::Novalnet, + nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, + payeezy, payeezy::Payeezy, payload, payload::Payload, payme, payme::Payme, payone, + payone::Payone, paypal, paypal::Paypal, paysafe, paysafe::Paysafe, paystack, + paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, peachpayments, + peachpayments::Peachpayments, phonepe, phonepe::Phonepe, placetopay, placetopay::Placetopay, + plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, + rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, + redsys::Redsys, riskified, riskified::Riskified, santander, santander::Santander, shift4, + shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, silverflow, + silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, stripe::Stripe, + stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, threedsecureio, + threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, tokenex::Tokenex, tokenio, + tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, + tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, diff --git a/crates/router/tests/connectors/gigadat.rs b/crates/router/tests/connectors/gigadat.rs new file mode 100644 index 00000000000..f77277ad24a --- /dev/null +++ b/crates/router/tests/connectors/gigadat.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 GigadatTest; +impl ConnectorActions for GigadatTest {} +impl utils::Connector for GigadatTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Gigadat; + utils::construct_connector_data_old( + Box::new(Gigadat::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .gigadat + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "gigadat".to_string() + } +} + +static CONNECTOR: GigadatTest = GigadatTest {}; + +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 4f405f56ee3..fbabe1155f4 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -49,6 +49,7 @@ mod fiuu; mod flexiti; mod forte; mod getnet; +mod gigadat; mod globalpay; mod globepay; mod gocardless; diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 64fa913d512..d58a1d8388f 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -59,6 +59,7 @@ pub struct ConnectorAuthentication { pub flexiti: Option<HeaderKey>, pub forte: Option<MultiAuthKey>, pub getnet: Option<HeaderKey>, + pub gigadat: Option<HeaderKey>, pub globalpay: Option<BodyKey>, pub globepay: Option<BodyKey>, pub gocardless: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index cd4fe3fc8c0..e072a370b91 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -126,6 +126,7 @@ fiuu.secondary_base_url = "https://sandbox.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-test.getneteurope.com/engine/rest" +gigadat.base_url = "https://interac.express-connect.com/" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api-sandbox.gocardless.com" diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 9f6a3062c48..22573052f11 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 affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet gigadat globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenex tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
2025-09-19T10:36:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Connector Template code ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? No test required as it is template code ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
juspay/hyperswitch
juspay__hyperswitch-9436
Bug: [FEATURE] Nuvei Apple pay hyperswitch-decryption flow ### Feature Description Implement hyperswitch-decryption flow for nuvei connector ### Possible Implementation ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index e471cf41ee9..15291889d7b 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -3709,7 +3709,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector"] +options=["Connector","Hyperswitch"] [[nuvei.metadata.google_pay]] name="merchant_name" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 8e74e8c1c46..a40ec24a73c 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -2857,6 +2857,57 @@ api_secret = "Merchant Secret" [nuvei.connector_webhook_details] merchant_secret = "Source verification key" +[[nuvei.metadata.apple_pay]] +name = "certificate" +label = "Merchant Certificate (Base64 Encoded)" +placeholder = "Enter Merchant Certificate (Base64 Encoded)" +required = true +type = "Text" +[[nuvei.metadata.apple_pay]] +name = "certificate_keys" +label = "Merchant PrivateKey (Base64 Encoded)" +placeholder = "Enter Merchant PrivateKey (Base64 Encoded)" +required = true +type = "Text" +[[nuvei.metadata.apple_pay]] +name = "merchant_identifier" +label = "Apple Merchant Identifier" +placeholder = "Enter Apple Merchant Identifier" +required = true +type = "Text" +[[nuvei.metadata.apple_pay]] +name = "display_name" +label = "Display Name" +placeholder = "Enter Display Name" +required = true +type = "Text" +[[nuvei.metadata.apple_pay]] +name = "initiative" +label = "Domain" +placeholder = "Enter Domain" +required = true +type = "Text" +[[nuvei.metadata.apple_pay]] +name = "initiative_context" +label = "Domain Name" +placeholder = "Enter Domain Name" +required = true +type = "Text" +[[nuvei.metadata.apple_pay]] +name = "merchant_business_country" +label = "Merchant Business Country" +placeholder = "Enter Merchant Business Country" +required = true +type = "Select" +options = [] +[[nuvei.metadata.apple_pay]] +name = "payment_processing_details_at" +label = "Payment Processing Details At" +placeholder = "Enter Payment Processing Details At" +required = true +type = "Radio" +options = ["Connector","Hyperswitch"] + [opennode] [[opennode.crypto]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 0ec6cbd7f82..3b1e18d8903 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -3680,7 +3680,9 @@ label = "Payment Processing Details At" placeholder = "Enter Payment Processing Details At" required = true type = "Radio" -options = ["Connector"] +options = ["Connector","Hyperswitch"] + + [[nuvei.metadata.google_pay]] name = "merchant_name" diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 4483412424d..110263e3896 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -1,5 +1,7 @@ use common_enums::{enums, CaptureMethod, FutureUsage, PaymentChannel}; -use common_types::payments::{ApplePayPaymentData, GpayTokenizationData}; +use common_types::payments::{ + ApplePayPaymentData, ApplePayPredecryptData, GPayPredecryptData, GpayTokenizationData, +}; use common_utils::{ crypto::{self, GenerateDigest}, date_time, @@ -19,7 +21,7 @@ use hyperswitch_domain_models::{ }, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, - ErrorResponse, L2L3Data, RouterData, + ErrorResponse, L2L3Data, PaymentMethodToken, RouterData, }, router_flow_types::{ refunds::{Execute, RSync}, @@ -1032,6 +1034,40 @@ struct ApplePayPaymentMethodCamelCase { #[serde(rename = "type")] pm_type: Secret<String>, } + +fn get_google_pay_decrypt_data( + predecrypt_data: &GPayPredecryptData, + is_rebilling: Option<String>, + brand: Option<String>, +) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { + Ok(NuveiPaymentsRequest { + is_rebilling, + payment_option: PaymentOption { + card: Some(Card { + brand, + card_number: Some(predecrypt_data.application_primary_account_number.clone()), + last4_digits: Some(Secret::new( + predecrypt_data + .application_primary_account_number + .clone() + .get_last4(), + )), + expiration_month: Some(predecrypt_data.card_exp_month.clone()), + expiration_year: Some(predecrypt_data.card_exp_year.clone()), + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::GooglePay, + mobile_token: None, + cryptogram: predecrypt_data.cryptogram.clone(), + eci_provider: predecrypt_data.eci_indicator.clone(), + }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }) +} + fn get_googlepay_info<F, Req>( item: &RouterData<F, Req, PaymentsResponseData>, gpay_data: &GooglePayWalletData, @@ -1044,37 +1080,21 @@ where } else { None }; - match gpay_data.tokenization_data { - GpayTokenizationData::Decrypted(ref gpay_predecrypt_data) => Ok(NuveiPaymentsRequest { + + if let Ok(PaymentMethodToken::GooglePayDecrypt(ref token)) = item.get_payment_method_token() { + return get_google_pay_decrypt_data( + token, is_rebilling, - payment_option: PaymentOption { - card: Some(Card { - brand: Some(gpay_data.info.card_network.clone()), - card_number: Some( - gpay_predecrypt_data - .application_primary_account_number - .clone(), - ), - last4_digits: Some(Secret::new( - gpay_predecrypt_data - .application_primary_account_number - .clone() - .get_last4(), - )), - expiration_month: Some(gpay_predecrypt_data.card_exp_month.clone()), - expiration_year: Some(gpay_predecrypt_data.card_exp_year.clone()), - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::GooglePay, - mobile_token: None, - cryptogram: gpay_predecrypt_data.cryptogram.clone(), - eci_provider: gpay_predecrypt_data.eci_indicator.clone(), - }), - ..Default::default() - }), - ..Default::default() - }, - ..Default::default() - }), + Some(gpay_data.info.card_network.clone()), + ); + } + + match &gpay_data.tokenization_data { + GpayTokenizationData::Decrypted(gpay_predecrypt_data) => get_google_pay_decrypt_data( + gpay_predecrypt_data, + is_rebilling, + Some(gpay_data.info.card_network.clone()), + ), GpayTokenizationData::Encrypted(ref encrypted_data) => Ok(NuveiPaymentsRequest { is_rebilling, payment_option: PaymentOption { @@ -1127,6 +1147,62 @@ where } } +fn get_apple_pay_decrypt_data( + apple_pay_predecrypt_data: &ApplePayPredecryptData, + is_rebilling: Option<String>, + network: String, +) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { + Ok(NuveiPaymentsRequest { + is_rebilling, + payment_option: PaymentOption { + card: Some(Card { + brand: Some(network), + card_number: Some( + apple_pay_predecrypt_data + .application_primary_account_number + .clone(), + ), + last4_digits: Some(Secret::new( + apple_pay_predecrypt_data + .application_primary_account_number + .get_last4(), + )), + expiration_month: Some( + apple_pay_predecrypt_data + .application_expiration_month + .clone(), + ), + expiration_year: Some( + apple_pay_predecrypt_data + .application_expiration_year + .clone(), + ), + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::ApplePay, + mobile_token: None, + cryptogram: Some( + apple_pay_predecrypt_data + .payment_data + .online_payment_cryptogram + .clone(), + ), + eci_provider: Some( + apple_pay_predecrypt_data + .payment_data + .eci_indicator + .clone() + .ok_or_else(missing_field_err( + "payment_method_data.wallet.apple_pay.payment_data.eci_indicator", + ))?, + ), + }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }) +} fn get_applepay_info<F, Req>( item: &RouterData<F, Req, PaymentsResponseData>, apple_pay_data: &ApplePayWalletData, @@ -1139,58 +1215,24 @@ where } else { None }; + if let Ok(PaymentMethodToken::ApplePayDecrypt(ref token)) = item.get_payment_method_token() { + return get_apple_pay_decrypt_data( + token, + is_rebilling, + apple_pay_data.payment_method.network.clone(), + ); + } match apple_pay_data.payment_data { - ApplePayPaymentData::Decrypted(ref apple_pay_predecrypt_data) => Ok(NuveiPaymentsRequest { - is_rebilling, - payment_option: PaymentOption { - card: Some(Card { - brand: Some(apple_pay_data.payment_method.network.clone()), - card_number: Some( - apple_pay_predecrypt_data - .application_primary_account_number - .clone(), - ), - last4_digits: Some(Secret::new( - apple_pay_predecrypt_data - .application_primary_account_number - .get_last4(), - )), - expiration_month: Some( - apple_pay_predecrypt_data - .application_expiration_month - .clone(), - ), - expiration_year: Some( - apple_pay_predecrypt_data - .application_expiration_year - .clone(), - ), - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::ApplePay, - mobile_token: None, - cryptogram: Some( - apple_pay_predecrypt_data - .payment_data - .online_payment_cryptogram - .clone(), - ), - eci_provider: Some( - apple_pay_predecrypt_data - .payment_data - .eci_indicator.clone() - .ok_or_else(missing_field_err( - "payment_method_data.wallet.apple_pay.payment_data.eci_indicator", - ))?, - ), - }), - ..Default::default() - }), - ..Default::default() - }, - ..Default::default() - }), + ApplePayPaymentData::Decrypted(ref apple_pay_predecrypt_data) => { + get_apple_pay_decrypt_data( + apple_pay_predecrypt_data, + is_rebilling, + apple_pay_data.payment_method.network.clone(), + ) + } + ApplePayPaymentData::Encrypted(ref encrypted_data) => Ok(NuveiPaymentsRequest { - is_rebilling, + is_rebilling, payment_option: PaymentOption { card: Some(Card { external_token: Some(ExternalToken { @@ -1621,6 +1663,7 @@ where data: (&RouterData<F, Req, PaymentsResponseData>, String), ) -> Result<Self, Self::Error> { let item = data.0; + let request_data = match item.request.get_payment_method_data_required()?.clone() { PaymentMethodData::Card(card) => get_card_info(item, &card), PaymentMethodData::MandatePayment => Self::try_from(item), @@ -1768,19 +1811,14 @@ where let amount_details = get_amount_details(&item.l2_l3_data, currency)?; let l2_l3_items: Option<Vec<NuveiItem>> = get_l2_l3_items(&item.l2_l3_data, currency)?; let address = { - if let Some(billing_address) = item.get_optional_billing() { - let mut billing_address = billing_address.clone(); - item.get_billing_first_name()?; - billing_address.email = match item.get_billing_email() { - Ok(email) => Some(email), - Err(_) => Some(item.request.get_email_required()?), - }; - item.get_billing_country()?; - - Some(billing_address) - } else { - None - } + let mut billing_address = item.get_billing()?.clone(); + item.get_billing_first_name()?; + billing_address.email = match item.get_billing_email() { + Ok(email) => Some(email), + Err(_) => Some(item.request.get_email_required()?), + }; + item.get_billing_country()?; + Some(billing_address) }; let shipping_address: Option<ShippingAddress> = 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 c9b09f7eee2..bfb3e36b291 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1514,7 +1514,23 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { .concat(), ), ), - (Connector::Nuvei, fields(vec![], vec![], card_basic())), + ( + Connector::Nuvei, + fields( + vec![], + vec![], + [ + card_basic(), + vec![ + RequiredField::BillingEmail, + RequiredField::BillingCountries(vec!["ALL"]), + RequiredField::BillingFirstName("first_name", FieldType::UserFullName), + RequiredField::BillingLastName("last_name", FieldType::UserFullName), + ], + ] + .concat(), + ), + ), ( Connector::Paybox, fields( @@ -2310,6 +2326,19 @@ fn get_wallet_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFi connectors(vec![ (Connector::Stripe, fields(vec![], vec![], vec![])), (Connector::Adyen, fields(vec![], vec![], vec![])), + ( + Connector::Nuvei, + fields( + vec![], + vec![], + vec![ + RequiredField::BillingEmail, + RequiredField::BillingCountries(vec!["ALL"]), + RequiredField::BillingFirstName("first_name", FieldType::UserFullName), + RequiredField::BillingLastName("last_name", FieldType::UserFullName), + ], + ), + ), ( Connector::Bankofamerica, RequiredFieldFinal { @@ -2465,7 +2494,19 @@ fn get_wallet_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFi Connector::Novalnet, fields(vec![], vec![], vec![RequiredField::BillingEmail]), ), - (Connector::Nuvei, fields(vec![], vec![], vec![])), + ( + Connector::Nuvei, + fields( + vec![], + vec![], + vec![ + RequiredField::BillingEmail, + RequiredField::BillingCountries(vec!["ALL"]), + RequiredField::BillingFirstName("first_name", FieldType::UserFullName), + RequiredField::BillingLastName("last_name", FieldType::UserFullName), + ], + ), + ), (Connector::Airwallex, fields(vec![], vec![], vec![])), (Connector::Authorizedotnet, fields(vec![], vec![], vec![])), (Connector::Checkout, fields(vec![], vec![], vec![])),
2025-09-18T07:15:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add support for hyperswitch side decrypt flow for applepay in Nuvei - Hyperswitch can decrypt applepay token without involvement of connector if it has Apple pay processing certificate and private key. # how did i test Payment Request ```json { "amount": 6500, "currency": "USD", "email": "[email protected]", "customer_id": "hello5", "capture_method": "automatic", "confirm": true, "return_url": "https://hyperswitch-demo-store.netlify.app/?isTestingMode=true&hyperswitchClientUrl=https://beta.hyperswitch.io/v1&hyperswitchCustomPodUri=&hyperswitchCustomBackendUrl=&publishableKey=pk_snd_e6c328fa58824247865647d532583e66&secretKey=snd_H0f0rZqfaXlv6kz81O6tQptd2e250u5vlFsA1L50ogMglapamZmDzJ7qRlj4mNlM&profileId=pro_PxNHqEwbZM6rbIfgClSg&environment=Sandbox", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "eyJkYXRhIjoiSWRNbUFu***************d****************2NDQ5NDlmMWUxNGZiYmM4NTdiNjk5N2NkYWJlMzczZGEyOTI3ZmU5NzcifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 0492", "network": "Visa", "type": "debit" }, "transaction_identifier": "85ea39d59610a6860eb723644949f1e14fbbc857b6997cdabe373da2927fe977" } } }, "payment_method": "wallet", "payment_method_type": "apple_pay", "connector": [ "nuvei" ], "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "en-US", "color_depth": 24, "screen_height": 1117, "screen_width": 1728, "ip_address": "192.168.1.1", "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "device_model": "Macintosh", "os_type": "macOS", "os_version": "10.15.7" }, "payment_type": "normal" } ``` ## Response ```json { "payment_id": "pay_7wu0YSHTd8LFDE8KD2UN", "merchant_id": "merchant_1758115709", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "nuvei", "client_secret": "pay_7wu0YSHTd8LFDE8KD2UN_secret_kIWxoLIlS4kexcOCmHz1", "created": "2025-09-18T07:35:21.765Z", "currency": "USD", "customer_id": "hello5", "customer": { "id": "hello5", "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": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "0492", "card_network": "Visa", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://hyperswitch-demo-store.netlify.app/?isTestingMode=true&hyperswitchClientUrl=https://beta.hyperswitch.io/v1&hyperswitchCustomPodUri=&hyperswitchCustomBackendUrl=&publishableKey=pk_snd_e6c328fa58824247865647d532583e66&secretKey=snd_H0f0rZqfaXlv6kz81O6tQptd2e250u5vlFsA1L50ogMglapamZmDzJ7qRlj4mNlM&profileId=pro_PxNHqEwbZM6rbIfgClSg&environment=Sandbox", "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": "apple_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "hello5", "created_at": 1758180921, "expires": 1758184521, "secret": "epk_228ed6b0222a461b9497d73df63c5e11" }, "manual_retry_allowed": null, "connector_transaction_id": "7110000000017082220", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8937234111", "payment_link": null, "profile_id": "pro_G0scDt6GAZBxs3brIkts", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_4ioDaxsfaPf9R3aZCrE6", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-18T07:50:21.765Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "192.168.1.1", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15", "color_depth": 24, "device_model": "Macintosh", "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_channel": null, "payment_method_id": null, "network_transaction_id": "", "payment_method_status": null, "updated": "2025-09-18T07:35:25.366Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` <img width="1478" height="714" alt="Screenshot 2025-09-18 at 1 24 08 PM" src="https://github.com/user-attachments/assets/2711bf06-f543-40bd-bd08-159920b60be3" /> ## Similarly for manual capture <img width="1531" height="861" alt="Screenshot 2025-09-18 at 1 25 41 PM" src="https://github.com/user-attachments/assets/4984713a-8837-4d8a-9783-37cefedb17d7" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
1c0fc496d1f639de4b7a94b971ce4526a3452c01
juspay/hyperswitch
juspay__hyperswitch-9432
Bug: [BUG] Validation for Negative Amount missing in Capture Flow ### Bug Description It bugs out when negative amount is given in the `/capture` call. There's no validation check for negative amount due to which the request gets passed to the connector end. ### Expected Behavior It should validate the non-negativity of the amount and throw Invalid Request error if given amount is non-positive. ### Actual Behavior It actually passes the request to the connecter end without any validation. ### 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 Payments - Capture: Request: ``` curl --location 'http://localhost:8080/payments/pay_3r321cW3JFzOFntLrxys/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data '{ "amount_to_capture": -100, "statement_descriptor_name": "Joseph", "statement_descriptor_suffix": "JS" }' ``` Response: ``` { "payment_id": "pay_kf7XQUddYDRSGeAScpKJ", "merchant_id": "merchant_1758182017", "status": "partially_captured", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": -100, "connector": "peachpayments", "client_secret": "pay_kf7XQUddYDRSGeAScpKJ_secret_LktFwkiCHl2vazBwKXht", "created": "2025-09-18T07:53:46.956Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "JP Morgan", "card_issuing_country": "INDIA", "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "30", "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, "origin_zip": 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", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "0cf747a1-57cd-4da0-a61d-2e5786957516", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "0cf747a1-57cd-4da0-a61d-2e5786957516", "payment_link": null, "profile_id": "pro_AuzXVUN1lVMbF6OOUyPQ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_N9Lqal8YvQLk1BzR1irg", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-18T08:08:46.956Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "65.1.52.128", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1312, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 848, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-18T07:53:52.749Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` ### 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/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index efad124bff0..f763bb44c4c 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -172,6 +172,11 @@ pub struct ConfigMetadata { pub shop_name: Option<InputData>, pub merchant_funding_source: Option<InputData>, pub account_id: Option<AccountIDSupportedMethods>, + pub name: Option<InputData>, + pub client_merchant_reference_id: Option<InputData>, + pub route: Option<InputData>, + pub mid: Option<InputData>, + pub tid: Option<InputData>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index e471cf41ee9..5480c27090e 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6948,8 +6948,14 @@ key1="Tenant ID" [peachpayments.connector_webhook_details] merchant_secret="Webhook Secret" -[peachpayments.metadata.merchant_name] -name="merchant_name" +[peachpayments.metadata.client_merchant_reference_id] +name="client_merchant_reference_id" +label="Client Merchant Reference Id" +placeholder="Enter Client Merchant Reference Id" +required=true +type="Text" +[peachpayments.metadata.name] +name="name" label="Merchant Name" placeholder="Enter Merchant Name" required=true @@ -7015,20 +7021,20 @@ label="Merchant Website" placeholder="Enter merchant website URL" required=true type="Text" -[peachpayments.metadata.routing_mid] -name="routing_mid" +[peachpayments.metadata.mid] +name="mid" label="Routing MID" placeholder="Enter routing MID" required=true type="Text" -[peachpayments.metadata.routing_tid] -name="routing_tid" +[peachpayments.metadata.tid] +name="tid" label="Routing TID" placeholder="Enter routing TID" required=true type="Text" -[peachpayments.metadata.routing_route] -name="routing_route" +[peachpayments.metadata.route] +name="route" label="Routing Route" placeholder="Select routing route" required=true @@ -7040,3 +7046,21 @@ label="AmEx ID" placeholder="Enter AmEx ID for routing" required=false type="Text" +[peachpayments.metadata.sub_mid] +name="sub_mid" +label="Sub Mid" +placeholder="Enter Sub Mid" +required=false +type="Text" +[peachpayments.metadata.visa_payment_facilitator_id] +name="visa_payment_facilitator_id" +label="Visa Payment Facilitator Id" +placeholder="Enter Visa Payment Facilitator Id" +required=false +type="Text" +[peachpayments.metadata.mastercard_payment_facilitator_id] +name="mastercard_payment_facilitator_id" +label="mastercard Payment Facilitator Id" +placeholder="Enter mastercard Payment Facilitator Id" +required=false +type="Text" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 8e74e8c1c46..8ea30e66bdb 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5617,8 +5617,14 @@ key1="Tenant ID" [peachpayments.connector_webhook_details] merchant_secret="Webhook Secret" -[peachpayments.metadata.merchant_name] -name="merchant_name" +[peachpayments.metadata.client_merchant_reference_id] +name="client_merchant_reference_id" +label="Client Merchant Reference Id" +placeholder="Enter Client Merchant Reference Id" +required=true +type="Text" +[peachpayments.metadata.name] +name="name" label="Merchant Name" placeholder="Enter Merchant Name" required=true @@ -5684,20 +5690,20 @@ label="Merchant Website" placeholder="Enter merchant website URL" required=true type="Text" -[peachpayments.metadata.routing_mid] -name="routing_mid" +[peachpayments.metadata.mid] +name="mid" label="Routing MID" placeholder="Enter routing MID" required=true type="Text" -[peachpayments.metadata.routing_tid] -name="routing_tid" +[peachpayments.metadata.tid] +name="tid" label="Routing TID" placeholder="Enter routing TID" required=true type="Text" -[peachpayments.metadata.routing_route] -name="routing_route" +[peachpayments.metadata.route] +name="route" label="Routing Route" placeholder="Select routing route" required=true @@ -5709,3 +5715,21 @@ label="AmEx ID" placeholder="Enter AmEx ID for routing" required=false type="Text" +[peachpayments.metadata.sub_mid] +name="sub_mid" +label="Sub Mid" +placeholder="Enter Sub Mid" +required=false +type="Text" +[peachpayments.metadata.visa_payment_facilitator_id] +name="visa_payment_facilitator_id" +label="Visa Payment Facilitator Id" +placeholder="Enter Visa Payment Facilitator Id" +required=false +type="Text" +[peachpayments.metadata.mastercard_payment_facilitator_id] +name="mastercard_payment_facilitator_id" +label="mastercard Payment Facilitator Id" +placeholder="Enter mastercard Payment Facilitator Id" +required=false +type="Text" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 0ec6cbd7f82..87d2ffdb0b3 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6930,8 +6930,14 @@ key1="Tenant ID" [peachpayments.connector_webhook_details] merchant_secret="Webhook Secret" -[peachpayments.metadata.merchant_name] -name="merchant_name" +[peachpayments.metadata.client_merchant_reference_id] +name="client_merchant_reference_id" +label="Client Merchant Reference Id" +placeholder="Enter Client Merchant Reference Id" +required=true +type="Text" +[peachpayments.metadata.name] +name="name" label="Merchant Name" placeholder="Enter Merchant Name" required=true @@ -6997,20 +7003,20 @@ label="Merchant Website" placeholder="Enter merchant website URL" required=true type="Text" -[peachpayments.metadata.routing_mid] -name="routing_mid" +[peachpayments.metadata.mid] +name="mid" label="Routing MID" placeholder="Enter routing MID" required=true type="Text" -[peachpayments.metadata.routing_tid] -name="routing_tid" +[peachpayments.metadata.tid] +name="tid" label="Routing TID" placeholder="Enter routing TID" required=true type="Text" -[peachpayments.metadata.routing_route] -name="routing_route" +[peachpayments.metadata.route] +name="route" label="Routing Route" placeholder="Select routing route" required=true @@ -7022,3 +7028,21 @@ label="AmEx ID" placeholder="Enter AmEx ID for routing" required=false type="Text" +[peachpayments.metadata.sub_mid] +name="sub_mid" +label="Sub Mid" +placeholder="Enter Sub Mid" +required=false +type="Text" +[peachpayments.metadata.visa_payment_facilitator_id] +name="visa_payment_facilitator_id" +label="Visa Payment Facilitator Id" +placeholder="Enter Visa Payment Facilitator Id" +required=false +type="Text" +[peachpayments.metadata.mastercard_payment_facilitator_id] +name="mastercard_payment_facilitator_id" +label="mastercard Payment Facilitator Id" +placeholder="Enter mastercard Payment Facilitator Id" +required=false +type="Text" diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 78339c6b4a0..37703cd1bec 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2966,6 +2966,13 @@ pub(crate) fn validate_amount_to_capture( amount: i64, amount_to_capture: Option<i64>, ) -> RouterResult<()> { + utils::when(amount_to_capture.is_some_and(|value| value <= 0), || { + Err(report!(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "amount".to_string(), + expected_format: "positive integer".to_string(), + })) + })?; + utils::when( amount_to_capture.is_some() && (Some(amount) < amount_to_capture), || {
2025-09-18T08:16:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9432) ## Description <!-- Describe your changes in detail --> Added validation check for amount in capture flow. Fixed WASM for Peachpayments ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Test Payments - Capture Request: ``` curl --location 'http://localhost:8080/payments/pay_wiEii3CAAWM0vJdiSxT4/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ClYBYyzQ6dQf7CFDM4xJc7dJqnRKVKIAzwTe8jTWmWudRHgifkuuRqZrlO9dJcJM' \ --data '{ "amount_to_capture": -100, "statement_descriptor_name": "Joseph", "statement_descriptor_suffix": "JS" }' ``` Response: ``` { "error": { "type": "invalid_request", "message": "amount contains invalid data. Expected format is positive integer", "code": "IR_05" } } ``` Dashboard WASM <img width="1309" height="1028" alt="Screenshot 2025-09-18 at 9 49 59 PM" src="https://github.com/user-attachments/assets/7f716cb8-ff72-45ad-9000-5897bd9c30b8" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
1c0fc496d1f639de4b7a94b971ce4526a3452c01
juspay/hyperswitch
juspay__hyperswitch-9410
Bug: [CHORE] update CODEOWNERS Add `hyperswitch-payouts` team as code owner to relevant modules.
2025-09-17T04:10:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR assigns the code owner to relevant modules for `hyperswitch-payouts`. ## Motivation and Context - Helps offload PR review tasks for payout related modules to the respective team. ## How did you test it? Not needed
15406557c11041bab6358f2b4b916d7333fc0a0f
juspay/hyperswitch
juspay__hyperswitch-9412
Bug: [BUG] propagate additional payout method data for recurring payouts using PSP token ### Bug Description Additional payout method data for recurring payouts (using PSP tokens) is missing in the API and webhook response. ### Expected Behavior Additional payout method data should be present in both API and webhook response if it's present. ### Actual Behavior Additional payout method data is missing. ### Steps To Reproduce 1. Create a payout using migrated token for payouts 2. Check the API and webhooks 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_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 43af1bfa852..59202837dc2 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -15,6 +15,7 @@ use common_utils::{ new_type::{ MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }, + payout_method_utils, pii::{self, Email}, }; use masking::{PeekInterface, Secret}; @@ -2299,6 +2300,33 @@ impl PaymentMethodsData { pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { todo!() } + + #[cfg(feature = "v1")] + pub fn get_additional_payout_method_data( + &self, + ) -> Option<payout_method_utils::AdditionalPayoutMethodData> { + match self { + Self::Card(card_details) => { + router_env::logger::info!("Populating AdditionalPayoutMethodData from Card payment method data for recurring payout"); + Some(payout_method_utils::AdditionalPayoutMethodData::Card( + Box::new(payout_method_utils::CardAdditionalData { + card_issuer: card_details.card_issuer.clone(), + card_network: card_details.card_network.clone(), + bank_code: None, + card_type: card_details.card_type.clone(), + card_issuing_country: card_details.issuer_country.clone(), + last4: card_details.last4_digits.clone(), + card_isin: card_details.card_isin.clone(), + card_extended_bin: None, + card_exp_month: card_details.expiry_month.clone(), + card_exp_year: card_details.expiry_year.clone(), + card_holder_name: card_details.card_holder_name.clone(), + }), + )) + } + Self::BankDetails(_) | Self::WalletDetails(_) | Self::NetworkToken(_) => None, + } + } } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 491957045c7..e0bb73fd297 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -2782,7 +2782,15 @@ pub async fn payout_create_db_entries( helpers::get_additional_payout_data(&payout_method_data, &*state.store, profile_id) .await }) - .await; + .await + // If no payout method data in request but we have a stored payment method, populate from it + .or_else(|| { + payment_method.as_ref().and_then(|payment_method| { + payment_method + .get_payment_methods_data() + .and_then(|pmd| pmd.get_additional_payout_method_data()) + }) + }); let payout_attempt_req = storage::PayoutAttemptNew { payout_attempt_id: payout_attempt_id.to_string(),
2025-09-17T16:49:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR fixes the missing additional payout method details in the response when using stored payment methods (via PSP tokens) for processing payouts. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Sends back additional payout method details (if they exist) when using PSP tokens for processing payouts. ## How did you test it? <details> <summary>1. Migrate payment method</summary> cURL curl --location --request POST 'http://localhost:8080/payment_methods/migrate-batch' \ --header 'api-key: test_admin' \ --form 'merchant_id="merchant_1758125250"' \ --form 'merchant_connector_id="mca_k6axPokgVgx67z9hmNkj"' \ --form 'file=@"tokens__migrate.csv"' [tokens__migrate.csv](https://github.com/user-attachments/files/22390753/tokens__migrate.csv) Response [ { "line_number": 1, "payment_method_id": "pm_YspT9VnuMG0XecrqkhZs", "payment_method": "card", "payment_method_type": "credit", "customer_id": "cus_AdzK04pgB274z931M7JL", "migration_status": "Success", "card_number_masked": "429318 xxxx 0008", "card_migrated": null, "network_token_migrated": true, "connector_mandate_details_migrated": true, "network_transaction_id_migrated": true } ] </details> <details> <summary>2. Update token to make it payout eligible</summary> cURL curl --location --request POST 'http://localhost:8080/payment_methods/update-batch' \ --header 'api-key: test_admin' \ --form 'merchant_id="merchant_1758125250"' \ --form 'merchant_connector_id="mca_k6axPokgVgx67z9hmNkj"' \ --form 'file=@"tokens__update.csv"' [tokens__update.csv](https://github.com/user-attachments/files/22390755/tokens__update.csv) Response [ { "payment_method_id": "pm_YspT9VnuMG0XecrqkhZs", "status": "active", "network_transaction_id": "512560415387748", "connector_mandate_details": { "payouts": { "mca_k6axPokgVgx67z9hmNkj": { "transfer_method_id": "PQJWQCVLMZD3LTT5" } }, "mca_k6axPokgVgx67z9hmNkj": { "mandate_metadata": null, "payment_method_type": "credit", "connector_mandate_id": "PQJWQCVLMZD3LTT5", "connector_mandate_status": null, "original_payment_authorized_amount": null, "original_payment_authorized_currency": null, "connector_mandate_request_reference_id": null } }, "update_status": "Success", "line_number": 1 } ] </details> <details> <summary>3. Create payout using payment_method_id</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_1cELx0sYKhaGJNBh3actVbPYXkFnnOxhQbn6JT6APnI2DPqDvncMJndF2vyFuQjs' \ --data '{"payout_method_id":"pm_YspT9VnuMG0XecrqkhZs","amount":1,"currency":"EUR","customer_id":"cus_AdzK04pgB274z931M7JL","phone_country_code":"+65","description":"Its my first payout request","connector":["adyenplatform"],"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true,"profile_id":"pro_kgnfc6bjRh1yoyyCuuYS","billing":{"address":{"line1":"Raadhuisplein","line2":"92","city":"Hoogeveen","state":"FL","zip":"7901 BW","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"0650242319","country_code":"+31"}}}' Response (must have payout_method_data) {"payout_id":"payout_uIYW6dcWF0UESBtvayES","merchant_id":"merchant_1758125250","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":"WESTPAC BANKING CORPORATION","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"AUSTRALIA","bank_code":null,"last4":"0008","card_isin":"429318","card_extended_bin":null,"card_exp_month":"3","card_exp_year":"2030","card_holder_name":"Albert Klaassen"}},"billing":{"address":{"city":"Hoogeveen","country":"NL","line1":"Raadhuisplein","line2":"92","line3":null,"zip":"7901 BW","state":"FL","first_name":"John","last_name":"Doe","origin_zip":null},"phone":{"number":"0650242319","country_code":"+31"},"email":null},"auto_fulfill":true,"customer_id":"cus_AdzK04pgB274z931M7JL","customer":{"id":"cus_AdzK04pgB274z931M7JL","name":"Albert Klaassen","email":null,"phone":null,"phone_country_code":null},"client_secret":"payout_payout_uIYW6dcWF0UESBtvayES_secret_2Rp8hjZfSHFNC7Y7U5eo","return_url":null,"business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_k6axPokgVgx67z9hmNkj","status":"failed","error_message":"Unauthorized","error_code":"00_401","profile_id":"pro_kgnfc6bjRh1yoyyCuuYS","created":"2025-09-17T16:43:54.344Z","connector_transaction_id":null,"priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":null,"phone_country_code":null,"unified_code":"UE_9000","unified_message":"Something went wrong","payout_method_id":"pm_YspT9VnuMG0XecrqkhZs"} Webhooks response (must have payout_method_data) {"merchant_id":"merchant_1758125250","event_id":"evt_0199588fabf176d1ad39603c17064d2d","event_type":"payout_failed","content":{"type":"payout_details","object":{"payout_id":"payout_uIYW6dcWF0UESBtvayES","merchant_id":"merchant_1758125250","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":"WESTPAC BANKING CORPORATION","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"AUSTRALIA","bank_code":null,"last4":"0008","card_isin":"429318","card_extended_bin":null,"card_exp_month":"3","card_exp_year":"2030","card_holder_name":"Albert Klaassen"}},"billing":{"address":{"city":"Hoogeveen","country":"NL","line1":"Raadhuisplein","line2":"92","line3":null,"zip":"7901 BW","state":"FL","first_name":"John","last_name":"Doe","origin_zip":null},"phone":{"number":"0650242319","country_code":"+31"},"email":null},"auto_fulfill":true,"customer_id":"cus_AdzK04pgB274z931M7JL","customer":{"id":"cus_AdzK04pgB274z931M7JL","name":"Albert Klaassen","email":null,"phone":null,"phone_country_code":null},"client_secret":"payout_payout_uIYW6dcWF0UESBtvayES_secret_2Rp8hjZfSHFNC7Y7U5eo","return_url":null,"business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_k6axPokgVgx67z9hmNkj","status":"failed","error_message":"Unauthorized","error_code":"00_401","profile_id":"pro_kgnfc6bjRh1yoyyCuuYS","created":"2025-09-17T16:43:54.344Z","connector_transaction_id":null,"priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":null,"phone_country_code":null,"unified_code":"UE_9000","unified_message":"Something went wrong","payout_method_id":"pm_YspT9VnuMG0XecrqkhZs"}},"timestamp":"2025-09-17T16:43:54.737Z"} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
a05827e0ed8c25463a56cd973f475fbe8fbef145
juspay/hyperswitch
juspay__hyperswitch-9413
Bug: Required fields absent in PML in case of Gift Card for OnSession (v2) In case of `Adyen` connector and `Givex` payment method subtype, required fields are absent in PML output when `setup_future_usage` is `OnSession` Need to move givex required fields to common in the required fields TOML
diff --git a/config/payment_required_fields_v2.toml b/config/payment_required_fields_v2.toml index 299da49ee02..47de2192c3e 100644 --- a/config/payment_required_fields_v2.toml +++ b/config/payment_required_fields_v2.toml @@ -2331,12 +2331,12 @@ non_mandate = [] # Payment method type: Givex [required_fields.gift_card.givex.fields.Adyen] -common = [] -mandate = [] -non_mandate = [ +common = [ { required_field = "payment_method_data.gift_card.givex.number", display_name = "gift_card_number", field_type = "user_card_number" }, { required_field = "payment_method_data.gift_card.givex.cvc", display_name = "gift_card_cvc", field_type = "user_card_cvc" } ] +mandate = [] +non_mandate = [] # CardRedirect (Assuming this section might be missing or problematic, so placing MobilePayment after GiftCard) # If CardRedirect exists and is correct, MobilePayment should come after it.
2025-09-17T08:35:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Moved required fields for `givex` gift card for `Adyen` from `non-mandate` to `common` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> config/payment_required_fields_v2.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). --> Closes #9413 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - PML Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_019956cafc887e028748d3bf29b35a2e/payment-methods' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_DsAY3PdGJ0ROvUdK6EpX' \ --header 'Authorization: publishable-key=pk_dev_304de2a7a06e4074967faa195a48bd4a, client-secret=cs_019956cafc967983b4b673f259b6680e' \ --header 'api-key: pk_dev_304de2a7a06e4074967faa195a48bd4a' ``` - PML Response: ```json { "payment_methods_enabled": [ { "payment_method_type": "card", "payment_method_subtype": "card", "payment_experience": null, "required_fields": [], "surcharge_details": null }, { "payment_method_type": "card_redirect", "payment_method_subtype": "card_redirect", "payment_experience": [ "redirect_to_url" ], "required_fields": [], "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "klarna", "payment_experience": [ "redirect_to_url" ], "required_fields": [], "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "apple_pay", "payment_experience": null, "required_fields": [], "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "google_pay", "payment_experience": null, "required_fields": [], "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "paypal", "payment_experience": null, "required_fields": [ { "required_field": "payment_method_data.billing.email", "display_name": "email_address", "field_type": "user_email_address", "value": null } ], "surcharge_details": null }, { "payment_method_type": "gift_card", "payment_method_subtype": "givex", "payment_experience": null, "required_fields": [ { "required_field": "payment_method_data.gift_card.givex.number", "display_name": "gift_card_number", "field_type": "user_card_number", "value": null }, { "required_field": "payment_method_data.gift_card.givex.cvc", "display_name": "gift_card_cvc", "field_type": "user_card_cvc", "value": null } ], "surcharge_details": null } ], "customer_payment_methods": [] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
213165968462168a59d5c56423a7c10aa04fc186
juspay/hyperswitch
juspay__hyperswitch-9406
Bug: [REFACTOR] update generate_connector_request_reference_id for Razorpay update generate_connector_request_reference_id to consume merchant_reference_id for RAZORPAY, if not provided generate a UUID instead.
diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay.rs b/crates/hyperswitch_connectors/src/connectors/razorpay.rs index 44f1b462936..59404512081 100644 --- a/crates/hyperswitch_connectors/src/connectors/razorpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/razorpay.rs @@ -836,10 +836,14 @@ impl ConnectorSpecifications for Razorpay { #[cfg(feature = "v2")] fn generate_connector_request_reference_id( &self, - _payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, + payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, _payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { // The length of receipt for Razorpay order request should not exceed 40 characters. - uuid::Uuid::now_v7().to_string() + payment_intent + .merchant_reference_id + .as_ref() + .map(|id| id.get_string_repr().to_owned()) + .unwrap_or_else(|| uuid::Uuid::now_v7().to_string()) } }
2025-09-16T13:13:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> For Razorpay (RZP) integration, the `connector_request_reference_id` will now be set as follows: - If `merchant_reference_id` is available, use it directly. - If not available, generate a UUID instead. This ensures compliance with Razorpay’s constraint that the reference ID length must not exceed **40 characters**. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Enable UCS ``` curl --location 'http://localhost:8080/v2/configs/' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'x-tenant-id: public' \ --header 'Content-Type: application/json' \ --data '{ "key": "ucs_rollout_config_cloth_seller_UPYM7gnwbWs8Cpf0vQkt_razorpay_upi_Authorize", "value": "1.0" }' ``` Create Payment (Razorpay UPI Collect) ``` { "amount_details": { "order_amount": 100, "currency": "INR" }, "merchant_connector_details": { "connector_name": "razorpay", "merchant_connector_creds": { "auth_type": "BodyKey", "api_key": "_", "key1": "_" } }, "merchant_reference_id": "razorpayirctc1758028555", "capture_method":"automatic", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "success@razorpay" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" } }, "payment_method_subtype": "upi_collect", "payment_method_type": "upi", "return_raw_connector_response": true } ``` Verify UCS logs to see if merchant_reference_id is being passed in receipt <img width="756" height="263" alt="image" src="https://github.com/user-attachments/assets/b8e56c71-1c70-4a57-bea9-b19887ebbd5b" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f3ab3d63f69279af9254f15eba5654c0680a0747
juspay/hyperswitch
juspay__hyperswitch-9408
Bug: [FEAT] create Redis API for unlocking token in revenue recovery
diff --git a/crates/api_models/src/revenue_recovery_data_backfill.rs b/crates/api_models/src/revenue_recovery_data_backfill.rs index d73ae8a33c3..34c64b75547 100644 --- a/crates/api_models/src/revenue_recovery_data_backfill.rs +++ b/crates/api_models/src/revenue_recovery_data_backfill.rs @@ -23,6 +23,11 @@ pub struct RevenueRecoveryBackfillRequest { pub daily_retry_history: Option<String>, } +#[derive(Debug, Serialize)] +pub struct UnlockStatusResponse { + pub unlocked: bool, +} + #[derive(Debug, Serialize)] pub struct RevenueRecoveryDataBackfillResponse { pub processed_records: usize, @@ -59,6 +64,12 @@ impl ApiEventMetric for RevenueRecoveryDataBackfillResponse { } } +impl ApiEventMetric for UnlockStatusResponse { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Miscellaneous) + } +} + impl ApiEventMetric for CsvParsingResult { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) diff --git a/crates/router/src/core/revenue_recovery_data_backfill.rs b/crates/router/src/core/revenue_recovery_data_backfill.rs index 4f32a914849..629b9e6a586 100644 --- a/crates/router/src/core/revenue_recovery_data_backfill.rs +++ b/crates/router/src/core/revenue_recovery_data_backfill.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use api_models::revenue_recovery_data_backfill::{ BackfillError, ComprehensiveCardData, RevenueRecoveryBackfillRequest, - RevenueRecoveryDataBackfillResponse, + RevenueRecoveryDataBackfillResponse, UnlockStatusResponse, }; use common_enums::{CardNetwork, PaymentMethodType}; use hyperswitch_domain_models::api::ApplicationResponse; @@ -60,6 +60,33 @@ pub async fn revenue_recovery_data_backfill( Ok(ApplicationResponse::Json(response)) } +pub async fn unlock_connector_customer_status( + state: SessionState, + connector_customer_id: String, +) -> RouterResult<ApplicationResponse<UnlockStatusResponse>> { + let unlocked = storage::revenue_recovery_redis_operation:: + RedisTokenManager::unlock_connector_customer_status(&state, &connector_customer_id) + .await + .map_err(|e| { + logger::error!( + "Failed to unlock connector customer status for {}: {}", + connector_customer_id, + e + ); + errors::ApiErrorResponse::InternalServerError + })?; + + let response = UnlockStatusResponse { unlocked }; + + logger::info!( + "Unlock operation completed for connector customer {}: {}", + connector_customer_id, + unlocked + ); + + Ok(ApplicationResponse::Json(response)) +} + async fn process_payment_method_record( state: &SessionState, record: &RevenueRecoveryBackfillRequest, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9f27455c75c..395306c63c1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2984,5 +2984,10 @@ impl RecoveryDataBackfill { .to(super::revenue_recovery_data_backfill::revenue_recovery_data_backfill), ), ) + .service(web::resource("/status/{token_id}").route( + web::post().to( + super::revenue_recovery_data_backfill::revenue_recovery_data_backfill_status, + ), + )) } } diff --git a/crates/router/src/routes/revenue_recovery_data_backfill.rs b/crates/router/src/routes/revenue_recovery_data_backfill.rs index 340d9a084bf..4203f52dfff 100644 --- a/crates/router/src/routes/revenue_recovery_data_backfill.rs +++ b/crates/router/src/routes/revenue_recovery_data_backfill.rs @@ -7,7 +7,7 @@ use crate::{ core::{api_locking, revenue_recovery_data_backfill}, routes::AppState, services::{api, authentication as auth}, - types::domain, + types::{domain, storage}, }; #[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))] @@ -65,3 +65,26 @@ pub async fn revenue_recovery_data_backfill( )) .await } + +#[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))] +pub async fn revenue_recovery_data_backfill_status( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> HttpResponse { + let flow = Flow::RecoveryDataBackfill; + let connector_customer_id = path.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + connector_customer_id, + |state, _: (), id, _| { + revenue_recovery_data_backfill::unlock_connector_customer_status(state, id) + }, + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +}
2025-09-16T13:10:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This API updates the lock status of customer token to unlock in revenue recovery. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> cURL:- ``` curl --location --request POST 'http://localhost:8080/v2/recovery/data-backfill/status/fake_token_number' \ --header 'Authorization: admin-api-key=' \ ``` Response:- ``` { "unlocked": true } ``` Router logs:- <img width="1058" height="759" alt="Screenshot 2025-09-16 at 18 30 15" src="https://github.com/user-attachments/assets/0a9de535-3b7f-4638-a941-bce5cfb5f4ad" /> Redis-cli logs:- <img width="391" height="65" alt="Screenshot 2025-09-16 at 18 29 46" src="https://github.com/user-attachments/assets/d5f40b53-b4c0-46e1-9168-4420b43f2908" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
5b6409d4ebdcd7b1820d72b2cc7850ded21a1ad5
juspay/hyperswitch
juspay__hyperswitch-9430
Bug: Add support to configure default billing processor for a profile
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index e0483b19503..08b3a08f619 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2210,6 +2210,10 @@ pub struct ProfileCreate { /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + + /// Merchant Connector id to be stored for billing_processor connector + #[schema(value_type = Option<String>)] + pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, } #[nutype::nutype( @@ -2367,6 +2371,10 @@ pub struct ProfileCreate { /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")] pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, + + /// Merchant Connector id to be stored for billing_processor connector + #[schema(value_type = Option<String>)] + pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] @@ -2567,6 +2575,10 @@ pub struct ProfileResponse { /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + + /// Merchant Connector id to be stored for billing_processor connector + #[schema(value_type = Option<String>)] + pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] @@ -2737,6 +2749,10 @@ pub struct ProfileResponse { #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] pub revenue_recovery_retry_algorithm_type: Option<common_enums::enums::RevenueRecoveryAlgorithmType>, + + /// Merchant Connector id to be stored for billing_processor connector + #[schema(value_type = Option<String>)] + pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] @@ -2927,6 +2943,10 @@ pub struct ProfileUpdate { /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + + /// Merchant Connector id to be stored for billing_processor connector + #[schema(value_type = Option<String>)] + pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] @@ -3079,6 +3099,10 @@ pub struct ProfileUpdate { /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")] pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, + + /// Merchant Connector id to be stored for billing_processor connector + #[schema(value_type = Option<String>)] + pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 17641cee59b..d0e44927127 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -80,6 +80,7 @@ pub struct Profile { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } @@ -141,6 +142,7 @@ pub struct ProfileNew { pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } @@ -203,6 +205,7 @@ pub struct ProfileUpdateInternal { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } @@ -264,6 +267,7 @@ impl ProfileUpdateInternal { always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, + billing_processor_id, } = self; Profile { profile_id: source.profile_id, @@ -357,6 +361,7 @@ impl ProfileUpdateInternal { .or(source.is_external_vault_enabled), external_vault_connector_details: external_vault_connector_details .or(source.external_vault_connector_details), + billing_processor_id: billing_processor_id.or(source.billing_processor_id), } } } @@ -423,6 +428,7 @@ pub struct Profile { pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, @@ -497,6 +503,7 @@ pub struct ProfileNew { pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, @@ -558,6 +565,7 @@ pub struct ProfileUpdateInternal { pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, @@ -604,6 +612,7 @@ impl ProfileUpdateInternal { always_collect_shipping_details_from_wallet_connector, tax_connector_id, is_tax_connector_enabled, + billing_processor_id, routing_algorithm_id, order_fulfillment_time, order_fulfillment_time_origin, @@ -729,6 +738,7 @@ impl ProfileUpdateInternal { split_txns_enabled: split_txns_enabled.or(source.split_txns_enabled), is_manual_retry_enabled: None, always_enable_overcapture: None, + billing_processor_id: billing_processor_id.or(source.billing_processor_id), } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 9316c470d99..0f4732577d7 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -257,6 +257,8 @@ diesel::table! { dispute_polling_interval -> Nullable<Int4>, is_manual_retry_enabled -> Nullable<Bool>, always_enable_overcapture -> Nullable<Bool>, + #[max_length = 64] + billing_processor_id -> Nullable<Varchar>, is_external_vault_enabled -> Nullable<Bool>, external_vault_connector_details -> Nullable<Jsonb>, } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 5433c9ca5ad..e745eff97d7 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -252,6 +252,8 @@ diesel::table! { dispute_polling_interval -> Nullable<Int4>, is_manual_retry_enabled -> Nullable<Bool>, always_enable_overcapture -> Nullable<Bool>, + #[max_length = 64] + billing_processor_id -> Nullable<Varchar>, is_external_vault_enabled -> Nullable<Bool>, external_vault_connector_details -> Nullable<Jsonb>, #[max_length = 64] diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 3672db0dd16..095e2a392c5 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -85,6 +85,7 @@ pub struct Profile { pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub external_vault_details: ExternalVaultDetails, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] @@ -241,6 +242,7 @@ pub struct ProfileSetter { pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub external_vault_details: ExternalVaultDetails, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] @@ -307,6 +309,7 @@ impl From<ProfileSetter> for Profile { is_manual_retry_enabled: value.is_manual_retry_enabled, always_enable_overcapture: value.always_enable_overcapture, external_vault_details: value.external_vault_details, + billing_processor_id: value.billing_processor_id, } } } @@ -376,6 +379,7 @@ pub struct ProfileGeneralUpdate { pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] @@ -463,6 +467,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, + billing_processor_id, } = *update; let is_external_vault_enabled = match is_external_vault_enabled { @@ -528,6 +533,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, + billing_processor_id, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -588,6 +594,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, + billing_processor_id: None, }, ProfileUpdate::DynamicRoutingAlgorithmUpdate { dynamic_routing_algorithm, @@ -645,6 +652,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, + billing_processor_id: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -702,6 +710,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, + billing_processor_id: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -759,6 +768,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, + billing_processor_id: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -816,6 +826,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, + billing_processor_id: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -873,6 +884,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, + billing_processor_id: None, }, ProfileUpdate::AcquirerConfigMapUpdate { acquirer_config_map, @@ -930,6 +942,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, + billing_processor_id: None, }, } } @@ -1010,6 +1023,7 @@ impl super::behaviour::Conversion for Profile { always_enable_overcapture: self.always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, + billing_processor_id: self.billing_processor_id, }) } @@ -1133,6 +1147,7 @@ impl super::behaviour::Conversion for Profile { is_manual_retry_enabled: item.is_manual_retry_enabled, always_enable_overcapture: item.always_enable_overcapture, external_vault_details, + billing_processor_id: item.billing_processor_id, }) } @@ -1200,6 +1215,7 @@ impl super::behaviour::Conversion for Profile { is_manual_retry_enabled: self.is_manual_retry_enabled, is_external_vault_enabled, external_vault_connector_details, + billing_processor_id: self.billing_processor_id, }) } } @@ -1262,6 +1278,7 @@ pub struct Profile { pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub split_txns_enabled: common_enums::SplitTxnsEnabled, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] @@ -1320,6 +1337,7 @@ pub struct ProfileSetter { pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub split_txns_enabled: common_enums::SplitTxnsEnabled, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] @@ -1383,6 +1401,7 @@ impl From<ProfileSetter> for Profile { merchant_category_code: value.merchant_category_code, merchant_country_code: value.merchant_country_code, split_txns_enabled: value.split_txns_enabled, + billing_processor_id: value.billing_processor_id, } } } @@ -1571,6 +1590,7 @@ pub struct ProfileGeneralUpdate { pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, + pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] @@ -1653,6 +1673,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_country_code, revenue_recovery_retry_algorithm_type, split_txns_enabled, + billing_processor_id, } = *update; Self { profile_name, @@ -1707,6 +1728,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code, merchant_country_code, split_txns_enabled, + billing_processor_id, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -1764,6 +1786,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -1819,6 +1842,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -1874,6 +1898,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, ProfileUpdate::DefaultRoutingFallbackUpdate { default_fallback_routing, @@ -1929,6 +1954,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -1984,6 +2010,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, ProfileUpdate::CollectCvvDuringPaymentUpdate { should_collect_cvv_during_payment, @@ -2039,6 +2066,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, ProfileUpdate::DecisionManagerRecordUpdate { three_ds_decision_manager_config, @@ -2094,6 +2122,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -2149,6 +2178,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, ProfileUpdate::RevenueRecoveryAlgorithmUpdate { revenue_recovery_retry_algorithm_type, @@ -2205,6 +2235,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, + billing_processor_id: None, }, } } @@ -2287,6 +2318,7 @@ impl super::behaviour::Conversion for Profile { split_txns_enabled: Some(self.split_txns_enabled), is_manual_retry_enabled: None, always_enable_overcapture: None, + billing_processor_id: self.billing_processor_id, }) } @@ -2383,6 +2415,7 @@ impl super::behaviour::Conversion for Profile { merchant_category_code: item.merchant_category_code, merchant_country_code: item.merchant_country_code, split_txns_enabled: item.split_txns_enabled.unwrap_or_default(), + billing_processor_id: item.billing_processor_id, }) } .await @@ -2454,6 +2487,7 @@ impl super::behaviour::Conversion for Profile { merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, split_txns_enabled: Some(self.split_txns_enabled), + billing_processor_id: self.billing_processor_id, }) } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index caa47dfea09..cd0fc3dcadd 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3485,6 +3485,7 @@ impl ProfileCreateBridge for api::ProfileCreate { )) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating external vault details")?, + billing_processor_id: self.billing_processor_id, })) } @@ -3636,6 +3637,7 @@ impl ProfileCreateBridge for api::ProfileCreate { merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, split_txns_enabled: self.split_txns_enabled.unwrap_or_default(), + billing_processor_id: self.billing_processor_id, })) } } @@ -3987,6 +3989,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { external_vault_connector_details: self .external_vault_connector_details .map(ForeignInto::foreign_into), + billing_processor_id: self.billing_processor_id, }, ))) } @@ -4132,6 +4135,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { merchant_country_code: self.merchant_country_code, revenue_recovery_retry_algorithm_type, split_txns_enabled: self.split_txns_enabled, + billing_processor_id: self.billing_processor_id, }, ))) } diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index a5ca7e29922..29acb4ecff5 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -1292,6 +1292,7 @@ mod tests { is_manual_retry_enabled: None, always_enable_overcapture: None, external_vault_details: domain::ExternalVaultDetails::Skip, + billing_processor_id: None, }); let business_profile = state diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 3f96235c43f..eedac7c4016 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -240,6 +240,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { is_external_vault_enabled, external_vault_connector_details: external_vault_connector_details .map(ForeignFrom::foreign_from), + billing_processor_id: item.billing_processor_id, }) } } @@ -328,6 +329,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { merchant_country_code: item.merchant_country_code, split_txns_enabled: item.split_txns_enabled, revenue_recovery_retry_algorithm_type: item.revenue_recovery_retry_algorithm_type, + billing_processor_id: item.billing_processor_id, }) } } @@ -508,5 +510,6 @@ pub async fn create_profile_from_merchant_account( )) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating external_vault_details")?, + billing_processor_id: request.billing_processor_id, })) } diff --git a/migrations/2025-09-18-063125_add_billing_processor_id_to_business_profile/down.sql b/migrations/2025-09-18-063125_add_billing_processor_id_to_business_profile/down.sql new file mode 100644 index 00000000000..bdf1f660f3c --- /dev/null +++ b/migrations/2025-09-18-063125_add_billing_processor_id_to_business_profile/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE business_profile DROP COLUMN IF EXISTS billing_processor_id; \ No newline at end of file diff --git a/migrations/2025-09-18-063125_add_billing_processor_id_to_business_profile/up.sql b/migrations/2025-09-18-063125_add_billing_processor_id_to_business_profile/up.sql new file mode 100644 index 00000000000..983d782efc2 --- /dev/null +++ b/migrations/2025-09-18-063125_add_billing_processor_id_to_business_profile/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS billing_processor_id VARCHAR(64); \ No newline at end of file
2025-09-18T09:38:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> As part of the subscription, a billing processor need to be configured at profile level to route the subscription creation and other related activities. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Adding billing_processor_id in the profile table to use it during subscription operations. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create merchant account Request ``` curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1758189685", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "[email protected]", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "[email protected]", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` Response ``` { "merchant_id": "merchant_1758189675", "merchant_name": "NewAge Retailer", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "xn1iJ8FBkwGYVJbo4BIIndl2zIE8p8pNpksCA6r764i9xD8LD3WvkRNC5hq8bYON", "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": "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": null, "last_name": null, "origin_zip": null }, "merchant_tax_registration_id": null }, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true, "payment_statuses_enabled": null, "refund_statuses_enabled": null, "payout_statuses_enabled": null }, "payout_routing_algorithm": null, "sub_merchants_enabled": false, "parent_merchant_id": null, "publishable_key": "pk_dev_2250d33a4b344663846c41c8b058546c", "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_zNQexFZeBIibQLnmfMOf", "is_recon_enabled": false, "default_profile": "pro_UCU7YbjjS89XQ9vch5hi", "recon_status": "not_requested", "pm_collect_link_config": null, "product_type": "orchestration", "merchant_account_type": "standard" } ``` 2. Create API key Request ``` curl --location 'http://localhost:8080/api_keys/merchant_1758189675' \ --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" }' ``` Response ``` { "key_id": "dev_lc3LHo3Q8FWQautTIDy8", "merchant_id": "merchant_1758189675", "name": "API Key 1", "description": null, "api_key": "dev_nKpWbedawCxOo4fCSnIWHKT5lr6cxBR0qkiquexf2hZjfhcf6UGzbXAl3HFE2AJL", "created": "2025-09-18T10:02:31.552Z", "expiration": "2038-01-19T03:14:08.000Z" } ``` 3. Create billing connector Request ``` curl --location 'http://localhost:8080/account/merchant_1758189675/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nKpWbedawCxOo4fCSnIWHKT5lr6cxBR0qkiquexf2hZjfhcf6UGzbXAl3HFE2AJL' \ --data '{ "connector_type": "billing_processor", "connector_name": "chargebee", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "test_MK", "site": "" }, "business_country": "US", "business_label": "default", "connector_webhook_details": { "merchant_secret": "hyperswitch", "additional_secret": "hyperswitch" }, "metadata": { "site": "nish-test" } }' ``` Response ``` { "connector_type": "billing_processor", "connector_name": "chargebee", "connector_label": "chargebee_US_default", "merchant_connector_id": "mca_LJR3NoCsDKbYFTKnTGek", "profile_id": "pro_UCU7YbjjS89XQ9vch5hi", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "te**********************************MK" }, "payment_methods_enabled": null, "connector_webhook_details": { "merchant_secret": "hyperswitch", "additional_secret": "hyperswitch" }, "metadata": { "site": "nish-test" }, "test_mode": null, "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 } ``` 4. Update billing processor id in the profile Request ``` curl --location 'http://localhost:8080/account/merchant_1758189675/business_profile/pro_UCU7YbjjS89XQ9vch5hi' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_nKpWbedawCxOo4fCSnIWHKT5lr6cxBR0qkiquexf2hZjfhcf6UGzbXAl3HFE2AJL' \ --data '{ "billing_processor_id": "mca_LJR3NoCsDKbYFTKnTGek" }' ``` Response ``` { "merchant_id": "merchant_1758189675", "profile_id": "pro_UCU7YbjjS89XQ9vch5hi", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "xn1iJ8FBkwGYVJbo4BIIndl2zIE8p8pNpksCA6r764i9xD8LD3WvkRNC5hq8bYON", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true, "payment_statuses_enabled": null, "refund_statuses_enabled": null, "payout_statuses_enabled": null }, "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": null, "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": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "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, "is_debit_routing_enabled": false, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false, "acquirer_configs": null, "is_iframe_redirection_enabled": null, "merchant_category_code": null, "merchant_country_code": null, "dispute_polling_interval": null, "is_manual_retry_enabled": null, "always_enable_overcapture": null, "billing_processor_id": "mca_LJR3NoCsDKbYFTKnTGek" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e410af26ffffc63273f9a83ae28c982f37f47484
juspay/hyperswitch
juspay__hyperswitch-9394
Bug: Send recurrence object in case of non cit payment in nexixpay As requested by connector we need to send recurrence object in non cit payment with action as NoRecurring.
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 5a6069b4f9c..5c8fdd5e020 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -292,15 +292,15 @@ pub enum ContractType { #[serde(rename_all = "camelCase")] pub struct RecurrenceRequest { action: NexixpayRecurringAction, - contract_id: Secret<String>, - contract_type: ContractType, + contract_id: Option<Secret<String>>, + contract_type: Option<ContractType>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NexixpayNonMandatePaymentRequest { card: NexixpayCard, - recurrence: Option<RecurrenceRequest>, + recurrence: RecurrenceRequest, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -341,7 +341,7 @@ pub struct NexixpayCompleteAuthorizeRequest { operation_id: String, capture_type: Option<NexixpayCaptureType>, three_d_s_auth_data: ThreeDSAuthData, - recurrence: Option<RecurrenceRequest>, + recurrence: RecurrenceRequest, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -777,13 +777,17 @@ impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaym .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "connector_mandate_request_reference_id", })?; - Some(RecurrenceRequest { + RecurrenceRequest { action: NexixpayRecurringAction::ContractCreation, - contract_id: Secret::new(contract_id), - contract_type: ContractType::MitUnscheduled, - }) + contract_id: Some(Secret::new(contract_id)), + contract_type: Some(ContractType::MitUnscheduled), + } } else { - None + RecurrenceRequest { + action: NexixpayRecurringAction::NoRecurring, + contract_id: None, + contract_type: None, + } }; match item.router_data.request.payment_method_data { @@ -1388,13 +1392,17 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>> field_name: "connector_mandate_request_reference_id", })?, ); - Some(RecurrenceRequest { + RecurrenceRequest { action: NexixpayRecurringAction::ContractCreation, - contract_id, - contract_type: ContractType::MitUnscheduled, - }) + contract_id: Some(contract_id), + contract_type: Some(ContractType::MitUnscheduled), + } } else { - None + RecurrenceRequest { + action: NexixpayRecurringAction::NoRecurring, + contract_id: None, + contract_type: None, + } }; Ok(Self {
2025-09-15T19:46:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> As requested by connector we need to send recurrence object in connector requests of init and payments call for non cit payment with action as NoRecurring. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> One off payments are getting rejected from nexixpay as they have changed their api contract. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Payments create: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_****' \ --data-raw '{ "amount": 3545, "currency": "EUR", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4349 9401 9900 4549", "card_exp_month": "05", "card_exp_year": "26", "card_cvc": "396" } }, "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "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", "description": "Its my first payment request", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "country": "BR", "zip": "94122", "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": "BR", "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" }, "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: ``` {"payment_id":"pay_enzsqwG32eOsB0HzGN4C","merchant_id":"merchant_1757963735","status":"requires_customer_action","amount":3545,"net_amount":3545,"shipping_cost":null,"amount_capturable":3545,"amount_received":null,"connector":"nexixpay","client_secret":"pay_enzsqwG32eOsB0HzGN4C_secret_BdiC32A0XqFsV2xbrq5D","created":"2025-09-15T19:19:49.306Z","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":"on_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4549","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"434994","card_extended_bin":null,"card_exp_month":"05","card_exp_year":"26","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":"token_4Mtt2rFkwhP1VFwnqqG1","shipping":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"billing":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":[{"sku":null,"upc":null,"brand":null,"amount":3545,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Apple iphone 15","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":null,"product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":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":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_enzsqwG32eOsB0HzGN4C/merchant_1757963735/pay_enzsqwG32eOsB0HzGN4C_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":"customer123","created_at":1757963989,"expires":1757967589,"secret":"epk_"},"manual_retry_allowed":null,"connector_transaction_id":"F0Rxb8C1nzubCnlfKf","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":{"order_category":"pay"},"braintree":null,"adyen":null},"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"F0Rxb8C1nzubCnlfKf","payment_link":null,"profile_id":"pro_pNYfKwzcccCUBOwarvVW","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_QmMn98hDhgKxgBDFp64p","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-15T19:34:49.306Z","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_channel":null,"payment_method_id":null,"network_transaction_id":null,"payment_method_status":null,"updated":"2025-09-15T19:19:51.320Z","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,"is_iframe_redirection_enabled":null,"whole_connector_response":null,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` Payments retrieve request: ``` curl --location 'http://localhost:8080/payments/pay_enzsqwG32eOsB0HzGN4C?force_sync=true&expand_captures=true&expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_iQghjDyB2zimkX6J60unvxRuNIFuAFTjqwixKZX7CD70YiNg2seWOx5S1QobFeH6' ``` Payment retrieve Response: ``` {"payment_id":"pay_enzsqwG32eOsB0HzGN4C","merchant_id":"merchant_1757963735","status":"succeeded","amount":3545,"net_amount":3545,"shipping_cost":null,"amount_capturable":0,"amount_received":3545,"connector":"nexixpay","client_secret":"pay_enzsqwG32eOsB0HzGN4C_secret_BdiC32A0XqFsV2xbrq5D","created":"2025-09-15T19:19:49.306Z","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,"attempts":[{"attempt_id":"pay_enzsqwG32eOsB0HzGN4C_1","status":"charged","amount":3545,"order_tax_amount":null,"currency":"EUR","connector":"nexixpay","error_message":null,"payment_method":"card","connector_transaction_id":"F0Rxb8C1nzubCnlfKf","capture_method":"automatic","authentication_type":"three_ds","created_at":"2025-09-15T19:19:49.306Z","modified_at":"2025-09-15T19:20:21.314Z","cancellation_reason":null,"mandate_id":null,"error_code":null,"payment_token":"token_4Mtt2rFkwhP1VFwnqqG1","connector_metadata":{"psyncFlow":"Authorize","cancelOperationId":null,"threeDSAuthResult":{"authenticationValue":"AAcAAThkaAAAAA3Zl4JYdQAAAAA="},"captureOperationId":"887416293836952589","threeDSAuthResponse":"notneeded","authorizationOperationId":"887416293836952589"},"payment_experience":null,"payment_method_type":"credit","reference_id":"F0Rxb8C1nzubCnlfKf","unified_code":null,"unified_message":null,"client_source":null,"client_version":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":"4549","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"434994","card_extended_bin":null,"card_exp_month":"05","card_exp_year":"26","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":"token_4Mtt2rFkwhP1VFwnqqG1","shipping":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"billing":{"address":{"city":"San Fransico","country":"BR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":[{"sku":null,"upc":null,"brand":null,"amount":3545,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Apple iphone 15","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":null,"product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":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":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":"F0Rxb8C1nzubCnlfKf","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":{"order_category":"pay"},"braintree":null,"adyen":null},"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"F0Rxb8C1nzubCnlfKf","payment_link":null,"profile_id":"pro_pNYfKwzcccCUBOwarvVW","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_QmMn98hDhgKxgBDFp64p","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-15T19:34:49.306Z","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_channel":null,"payment_method_id":null,"network_transaction_id":null,"payment_method_status":null,"updated":"2025-09-15T19:20:21.314Z","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,"is_iframe_redirection_enabled":null,"whole_connector_response":null,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` <img width="1728" height="501" alt="image" src="https://github.com/user-attachments/assets/476b5832-518d-4587-ab10-a8763ad0e2a5" /> <img width="1728" height="501" alt="image" src="https://github.com/user-attachments/assets/079ef2bc-a681-4647-ae46-599c3f44b3d9" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ee12d44c5f13d0612dde3b6b24a412f6ddd870c8
juspay/hyperswitch
juspay__hyperswitch-9397
Bug: [FEATURE]: Implement Skrill wallet Payment Method Implement Skrill wallet Payment Method
diff --git a/Cargo.lock b/Cargo.lock index 196c7b9820b..491f77bf391 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "actix-codec" @@ -1970,6 +1970,7 @@ dependencies = [ "api_models", "common_utils", "serde", + "serde_json", "serde_with", "toml 0.8.22", "utoipa", diff --git a/crates/connector_configs/Cargo.toml b/crates/connector_configs/Cargo.toml index 08a8a149c6d..d322c891277 100644 --- a/crates/connector_configs/Cargo.toml +++ b/crates/connector_configs/Cargo.toml @@ -21,6 +21,7 @@ common_utils = { version = "0.1.0", path = "../common_utils" } # Third party crates serde = { version = "1.0.219", features = ["derive"] } +serde_json = "1.0.140" serde_with = "3.12.0" toml = "0.8.22" utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_order"] } diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index b54d9e86da8..be97726a194 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -110,7 +110,7 @@ pub struct ApiModelMetaData { pub merchant_configuration_id: Option<String>, pub tenant_id: Option<String>, pub platform_url: Option<String>, - pub account_id: Option<String>, + pub account_id: Option<serde_json::Value>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 0a521f7a864..a69ad5e278e 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -115,10 +115,19 @@ pub struct AccountIdConfigForCard { pub no_three_ds: Option<Vec<InputData>>, } +#[serde_with::skip_serializing_none] +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct AccountIdConfigForRedirect { + pub three_ds: Option<Vec<InputData>>, +} + #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct AccountIDSupportedMethods { card: HashMap<String, AccountIdConfigForCard>, + skrill: HashMap<String, AccountIdConfigForRedirect>, + interac: HashMap<String, AccountIdConfigForRedirect>, + pay_safe_card: HashMap<String, AccountIdConfigForRedirect>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 0f9fa995409..7545372876d 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6834,29 +6834,71 @@ key1 = "Password" [paysafe.connector_webhook_details] merchant_secret = "Source verification key" [[paysafe.metadata.account_id.card.USD.three_ds]] -name="account_id" +name="three_ds" label="ThreeDS account id" placeholder="Enter ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.USD.no_three_ds]] name="no_three_ds" label="Non ThreeDS account id" placeholder="Enter Non ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.EUR.three_ds]] -name="account_id" +name="three_ds" label="ThreeDS account id" placeholder="Enter ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.EUR.no_three_ds]] name="no_three_ds" label="Non ThreeDS account id" placeholder="Enter Non ThreeDS Account ID" required=true -type="Number" +type="Text" +[[paysafe.metadata.account_id.interac.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.USD.three_ds]] +name="three_ds" +label="USD" +placeholder="Enter usd Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.EUR.three_ds]] +name="three_ds" +label="EUR" +placeholder="Enter eur Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.USD.three_ds]] +name="three_ds" +label="USD" +placeholder="Enter usd Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.EUR.three_ds]] +name="three_ds" +label="EUR" +placeholder="Enter eur Account ID" +required=true +type="Text" [peachpayments] [[peachpayments.credit]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 96d473a386c..aef577cafa2 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5503,29 +5503,71 @@ key1 = "Password" [paysafe.connector_webhook_details] merchant_secret = "Source verification key" [[paysafe.metadata.account_id.card.USD.three_ds]] -name="account_id" +name="three_ds" label="ThreeDS account id" placeholder="Enter ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.USD.no_three_ds]] name="no_three_ds" label="Non ThreeDS account id" placeholder="Enter Non ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.EUR.three_ds]] -name="account_id" +name="three_ds" label="ThreeDS account id" placeholder="Enter ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.EUR.no_three_ds]] name="no_three_ds" label="Non ThreeDS account id" placeholder="Enter Non ThreeDS Account ID" required=true -type="Number" +type="Text" +[[paysafe.metadata.account_id.interac.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.USD.three_ds]] +name="three_ds" +label="USD" +placeholder="Enter usd Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.EUR.three_ds]] +name="three_ds" +label="EUR" +placeholder="Enter eur Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.USD.three_ds]] +name="three_ds" +label="USD" +placeholder="Enter usd Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.EUR.three_ds]] +name="three_ds" +label="EUR" +placeholder="Enter eur Account ID" +required=true +type="Text" [peachpayments] [[peachpayments.credit]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 45da96d5344..7748f5dd784 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6817,29 +6817,71 @@ key1 = "Password" [paysafe.connector_webhook_details] merchant_secret = "Source verification key" [[paysafe.metadata.account_id.card.USD.three_ds]] -name="account_id" +name="three_ds" label="ThreeDS account id" placeholder="Enter ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.USD.no_three_ds]] name="no_three_ds" label="Non ThreeDS account id" placeholder="Enter Non ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.EUR.three_ds]] -name="account_id" +name="three_ds" label="ThreeDS account id" placeholder="Enter ThreeDS Account ID" required=true -type="Number" +type="Text" [[paysafe.metadata.account_id.card.EUR.no_three_ds]] name="no_three_ds" label="Non ThreeDS account id" placeholder="Enter Non ThreeDS Account ID" required=true -type="Number" +type="Text" +[[paysafe.metadata.account_id.interac.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.USD.three_ds]] +name="three_ds" +label="USD" +placeholder="Enter usd Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.skrill.EUR.three_ds]] +name="three_ds" +label="EUR" +placeholder="Enter eur Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.USD.three_ds]] +name="three_ds" +label="USD" +placeholder="Enter usd Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.CAD.three_ds]] +name="three_ds" +label="CAD" +placeholder="Enter cad Account ID" +required=true +type="Text" +[[paysafe.metadata.account_id.pay_safe_card.EUR.three_ds]] +name="three_ds" +label="EUR" +placeholder="Enter eur Account ID" +required=true +type="Text" diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe.rs b/crates/hyperswitch_connectors/src/connectors/paysafe.rs index 8d463966748..df996434c78 100644 --- a/crates/hyperswitch_connectors/src/connectors/paysafe.rs +++ b/crates/hyperswitch_connectors/src/connectors/paysafe.rs @@ -975,6 +975,7 @@ static PAYSAFE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = La enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, ]; + let supported_capture_methods2 = vec![enums::CaptureMethod::Automatic]; let supported_card_network = vec![ common_enums::CardNetwork::Mastercard, @@ -1028,6 +1029,39 @@ static PAYSAFE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = La }, ); + paysafe_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Skrill, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods2.clone(), + specific_features: None, + }, + ); + + paysafe_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Interac, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods2.clone(), + specific_features: None, + }, + ); + + paysafe_supported_payment_methods.add( + enums::PaymentMethod::GiftCard, + enums::PaymentMethodType::PaySafeCard, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods2.clone(), + specific_features: None, + }, + ); + paysafe_supported_payment_methods }); diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs index 26e9d8de48d..8a091a7aec2 100644 --- a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs @@ -3,13 +3,14 @@ use std::collections::HashMap; use cards::CardNumber; use common_enums::{enums, Currency}; use common_utils::{ - pii::{IpAddress, SecretSerdeValue}, + id_type, + pii::{Email, IpAddress, SecretSerdeValue}, request::Method, types::MinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, + payment_method_data::{BankRedirectData, GiftCardData, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ @@ -56,6 +57,9 @@ pub struct PaysafeConnectorMetadataObject { #[derive(Debug, Default, Serialize, Deserialize)] pub struct PaysafePaymentMethodDetails { pub card: Option<HashMap<Currency, CardAccountId>>, + pub skrill: Option<HashMap<Currency, RedirectAccountId>>, + pub interac: Option<HashMap<Currency, RedirectAccountId>>, + pub pay_safe_card: Option<HashMap<Currency, RedirectAccountId>>, } #[derive(Debug, Default, Serialize, Deserialize)] @@ -64,6 +68,11 @@ pub struct CardAccountId { three_ds: Option<Secret<String>>, } +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct RedirectAccountId { + three_ds: Option<Secret<String>>, +} + impl TryFrom<&Option<SecretSerdeValue>> for PaysafeConnectorMetadataObject { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(meta_data: &Option<SecretSerdeValue>) -> Result<Self, Self::Error> { @@ -127,13 +136,54 @@ pub struct PaysafePaymentHandleRequest { pub return_links: Vec<ReturnLink>, pub account_id: Secret<String>, pub three_ds: Option<ThreeDs>, + pub profile: Option<PaysafeProfile>, +} + +#[derive(Debug, Serialize, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeProfile { + pub first_name: Secret<String>, + pub last_name: Secret<String>, + pub email: Email, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum PaysafePaymentMethod { - Card { card: PaysafeCard }, + Card { + card: PaysafeCard, + }, + Skrill { + skrill: SkrillWallet, + }, + Interac { + #[serde(rename = "interacEtransfer")] + interac_etransfer: InteracBankRedirect, + }, + PaysafeCard { + #[serde(rename = "paysafecard")] + pay_safe_card: PaysafeGiftCard, + }, +} + +#[derive(Debug, Serialize, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SkrillWallet { + pub consumer_id: Email, + pub country_code: Option<api_models::enums::CountryAlpha2>, +} + +#[derive(Debug, Serialize, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InteracBankRedirect { + pub consumer_id: Email, +} + +#[derive(Debug, Serialize, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeGiftCard { + pub consumer_id: id_type::CustomerId, } #[derive(Debug, Serialize)] @@ -153,9 +203,12 @@ pub enum LinkType { } #[derive(Debug, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaysafePaymentType { - #[serde(rename = "CARD")] Card, + Skrill, + InteracEtransfer, + Paysafecard, } #[derive(Debug, Serialize)] @@ -173,7 +226,7 @@ impl PaysafePaymentMethodDetails { .as_ref() .and_then(|cards| cards.get(&currency)) .and_then(|card| card.no_three_ds.clone()) - .ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig { + .ok_or(errors::ConnectorError::InvalidConnectorConfig { config: "Missing no_3ds account_id", }) } @@ -186,10 +239,49 @@ impl PaysafePaymentMethodDetails { .as_ref() .and_then(|cards| cards.get(&currency)) .and_then(|card| card.three_ds.clone()) - .ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig { + .ok_or(errors::ConnectorError::InvalidConnectorConfig { config: "Missing 3ds account_id", }) } + + pub fn get_skrill_account_id( + &self, + currency: Currency, + ) -> Result<Secret<String>, errors::ConnectorError> { + self.skrill + .as_ref() + .and_then(|wallets| wallets.get(&currency)) + .and_then(|skrill| skrill.three_ds.clone()) + .ok_or(errors::ConnectorError::InvalidConnectorConfig { + config: "Missing skrill account_id", + }) + } + + pub fn get_interac_account_id( + &self, + currency: Currency, + ) -> Result<Secret<String>, errors::ConnectorError> { + self.interac + .as_ref() + .and_then(|redirects| redirects.get(&currency)) + .and_then(|interac| interac.three_ds.clone()) + .ok_or(errors::ConnectorError::InvalidConnectorConfig { + config: "Missing interac account_id", + }) + } + + pub fn get_paysafe_gift_card_account_id( + &self, + currency: Currency, + ) -> Result<Secret<String>, errors::ConnectorError> { + self.pay_safe_card + .as_ref() + .and_then(|gift_cards| gift_cards.get(&currency)) + .and_then(|pay_safe_card| pay_safe_card.three_ds.clone()) + .ok_or(errors::ConnectorError::InvalidConnectorConfig { + config: "Missing paysafe gift card account_id", + }) + } } impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePaymentHandleRequest { @@ -268,6 +360,7 @@ impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePa return_links, account_id, three_ds: None, + profile: None, }) } _ => Err(errors::ConnectorError::NotImplemented( @@ -303,6 +396,7 @@ pub enum PaysafePaymentHandleStatus { Failed, Expired, Completed, + Error, } impl TryFrom<PaysafePaymentHandleStatus> for common_enums::AttemptStatus { @@ -310,9 +404,9 @@ impl TryFrom<PaysafePaymentHandleStatus> for common_enums::AttemptStatus { fn try_from(item: PaysafePaymentHandleStatus) -> Result<Self, Self::Error> { match item { PaysafePaymentHandleStatus::Completed => Ok(Self::Authorized), - PaysafePaymentHandleStatus::Failed | PaysafePaymentHandleStatus::Expired => { - Ok(Self::Failure) - } + PaysafePaymentHandleStatus::Failed + | PaysafePaymentHandleStatus::Expired + | PaysafePaymentHandleStatus::Error => Ok(Self::Failure), // We get an `Initiated` status, with a redirection link from the connector, which indicates that further action is required by the customer, PaysafePaymentHandleStatus::Initiated => Ok(Self::AuthenticationPending), PaysafePaymentHandleStatus::Payable | PaysafePaymentHandleStatus::Processing => { @@ -544,60 +638,118 @@ impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymen Some(enums::CaptureMethod::Automatic) | None ); let transaction_type = TransactionType::Payment; - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = PaysafeCard { - card_num: req_card.card_number.clone(), - card_expiry: PaysafeCardExpiry { - month: req_card.card_exp_month.clone(), - year: req_card.get_expiry_year_4_digit(), - }, - cvv: if req_card.card_cvc.clone().expose().is_empty() { - None - } else { - Some(req_card.card_cvc.clone()) - }, - holder_name: item.router_data.get_optional_billing_full_name(), - }; - let payment_method = PaysafePaymentMethod::Card { card: card.clone() }; - let payment_type = PaysafePaymentType::Card; - let headers = item.router_data.header_payload.clone(); - let platform = headers - .as_ref() - .and_then(|headers| headers.x_client_platform.clone()); - let device_channel = match platform { - Some(common_enums::ClientPlatform::Web) - | Some(common_enums::ClientPlatform::Unknown) - | None => DeviceChannel::Browser, - Some(common_enums::ClientPlatform::Ios) - | Some(common_enums::ClientPlatform::Android) => DeviceChannel::Sdk, - }; - let account_id = metadata.account_id.get_three_ds_account_id(currency_code)?; - let three_ds = Some(ThreeDs { - merchant_url: item.router_data.request.get_router_return_url()?, - device_channel, - message_category: ThreeDsMessageCategory::Payment, - authentication_purpose: ThreeDsAuthenticationPurpose::PaymentTransaction, - requestor_challenge_preference: ThreeDsChallengePreference::ChallengeMandated, - }); + let (payment_method, payment_type, account_id, three_ds, profile) = + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = PaysafeCard { + card_num: req_card.card_number.clone(), + card_expiry: PaysafeCardExpiry { + month: req_card.card_exp_month.clone(), + year: req_card.get_expiry_year_4_digit(), + }, + cvv: if req_card.card_cvc.clone().expose().is_empty() { + None + } else { + Some(req_card.card_cvc.clone()) + }, + holder_name: item.router_data.get_optional_billing_full_name(), + }; + let payment_method = PaysafePaymentMethod::Card { card: card.clone() }; + let payment_type = PaysafePaymentType::Card; + + let headers = item.router_data.header_payload.clone(); + let platform = headers.as_ref().and_then(|h| h.x_client_platform.clone()); + let device_channel = match platform { + Some(common_enums::ClientPlatform::Web) + | Some(common_enums::ClientPlatform::Unknown) + | None => DeviceChannel::Browser, + Some(common_enums::ClientPlatform::Ios) + | Some(common_enums::ClientPlatform::Android) => DeviceChannel::Sdk, + }; + + let account_id = metadata.account_id.get_three_ds_account_id(currency_code)?; + let three_ds = Some(ThreeDs { + merchant_url: item.router_data.request.get_router_return_url()?, + device_channel, + message_category: ThreeDsMessageCategory::Payment, + authentication_purpose: ThreeDsAuthenticationPurpose::PaymentTransaction, + requestor_challenge_preference: + ThreeDsChallengePreference::ChallengeMandated, + }); + + (payment_method, payment_type, account_id, three_ds, None) + } + + PaymentMethodData::Wallet(WalletData::Skrill(_)) => { + let payment_method = PaysafePaymentMethod::Skrill { + skrill: SkrillWallet { + consumer_id: item.router_data.get_billing_email()?, + country_code: item.router_data.get_optional_billing_country(), + }, + }; + let payment_type = PaysafePaymentType::Skrill; + let account_id = metadata.account_id.get_skrill_account_id(currency_code)?; + (payment_method, payment_type, account_id, None, None) + } + PaymentMethodData::Wallet(_) => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + ))?, + + PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => { + let payment_method = PaysafePaymentMethod::Interac { + interac_etransfer: InteracBankRedirect { + consumer_id: item.router_data.get_billing_email()?, + }, + }; + let payment_type = PaysafePaymentType::InteracEtransfer; + let account_id = metadata.account_id.get_interac_account_id(currency_code)?; + let profile = Some(PaysafeProfile { + first_name: item.router_data.get_billing_first_name()?, + last_name: item.router_data.get_billing_last_name()?, + email: item.router_data.get_billing_email()?, + }); + (payment_method, payment_type, account_id, None, profile) + } + PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + ))?, + + PaymentMethodData::GiftCard(gift_card_data) => match gift_card_data.as_ref() { + GiftCardData::PaySafeCard {} => { + let payment_method = PaysafePaymentMethod::PaysafeCard { + pay_safe_card: PaysafeGiftCard { + consumer_id: item.router_data.get_customer_id()?, + }, + }; + let payment_type = PaysafePaymentType::Paysafecard; + let account_id = metadata + .account_id + .get_paysafe_gift_card_account_id(currency_code)?; + (payment_method, payment_type, account_id, None, None) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + ))?, + }, + + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + ))?, + }; - Ok(Self { - merchant_ref_num: item.router_data.connector_request_reference_id.clone(), - amount, - settle_with_auth, - payment_method, - currency_code, - payment_type, - transaction_type, - return_links, - account_id, - three_ds, - }) - } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - ))?, - } + Ok(Self { + merchant_ref_num: item.router_data.connector_request_reference_id.clone(), + amount, + settle_with_auth, + payment_method, + currency_code, + payment_type, + transaction_type, + return_links, + account_id, + three_ds, + profile, + }) } } @@ -750,7 +902,6 @@ pub struct PaysafePaymentsResponse { pub id: String, pub merchant_ref_num: Option<String>, pub status: PaysafePaymentStatus, - pub settlements: Option<Vec<PaysafeSettlementResponse>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] 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 f61c789fe2f..e2dc44304ed 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -2268,6 +2268,13 @@ fn get_bank_redirect_required_fields( ), ]), ), + ( + enums::PaymentMethodType::Interac, + connectors(vec![( + Connector::Paysafe, + fields(vec![], vec![RequiredField::BillingEmail], vec![]), + )]), + ), ]) } @@ -2710,19 +2717,32 @@ fn get_wallet_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFi ), ( enums::PaymentMethodType::Skrill, - connectors(vec![( - Connector::Airwallex, - RequiredFieldFinal { - mandate: HashMap::new(), - non_mandate: HashMap::from([ - RequiredField::BillingUserFirstName.to_tuple(), - RequiredField::BillingUserLastName.to_tuple(), - RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), - RequiredField::BillingEmail.to_tuple(), - ]), - common: HashMap::new(), - }, - )]), + connectors(vec![ + ( + Connector::Airwallex, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + RequiredField::BillingUserFirstName.to_tuple(), + RequiredField::BillingUserLastName.to_tuple(), + RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), + RequiredField::BillingEmail.to_tuple(), + ]), + common: HashMap::new(), + }, + ), + ( + Connector::Paysafe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), + RequiredField::BillingEmail.to_tuple(), + ]), + common: HashMap::new(), + }, + ), + ]), ), ]) }
2025-09-16T06:28:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description implement Skrill, interac and paysafecard Payment Method ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? 1. Create a Skrill Payment ``` { "amount": 1500, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "profile_id": "pro_4qL65B30WQmHX25pXKmG", "authentication_type": "three_ds", "payment_method": "wallet", "payment_method_type": "skrill", "payment_method_data": { "wallet": { "skrill": {} } }, "billing": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "SG", "first_name": "박성준", "last_name": "박성준" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` Response ``` { "payment_id": "pay_5xoMCjQvR0AnUF37kl6v", "merchant_id": "merchant_1757942854", "status": "requires_customer_action", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 1500, "amount_received": null, "connector": "paysafe", "client_secret": "pay_5xoMCjQvR0AnUF37kl6v_secret_Co7z6eH0h93pHyicLKJp", "created": "2025-09-16T06:09:53.680Z", "currency": "USD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "박성준", "last_name": "박성준", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "박성준", "last_name": "박성준", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_5xoMCjQvR0AnUF37kl6v/merchant_1757942854/pay_5xoMCjQvR0AnUF37kl6v_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "skrill", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "aaaa", "created_at": 1758002993, "expires": 1758006593, "secret": "epk_6eec4bbcf95a434a8b65171dca1d86da" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_4qL65B30WQmHX25pXKmG", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2zxP3MvnLEpDi16Ay49j", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-16T06:24:53.680Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-16T06:09:56.298Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` Complete Payment using redirection 2. Do psync ``` curl --location 'http://localhost:8080/payments/pay_biJy45vN8GAgHdotUaAm?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_XE1bY6wAFDqmx67zzp7ywkodIuZnJ1bnzq7BmJ6jcULVA5z454A0vA5D9jR2uaFL' ``` Response ``` { "payment_id": "pay_biJy45vN8GAgHdotUaAm", "merchant_id": "merchant_1757942854", "status": "succeeded", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1500, "connector": "paysafe", "client_secret": "pay_biJy45vN8GAgHdotUaAm_secret_wzBdMh7jy1lQLteolVik", "created": "2025-09-16T06:11:55.151Z", "currency": "USD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1091", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "박성준", "last_name": "박성준", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "박성준", "last_name": "박성준", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "f7b13a78-971f-484f-bf2e-b7696cae27e4", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_4qL65B30WQmHX25pXKmG", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2zxP3MvnLEpDi16Ay49j", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-16T06:26:55.151Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-16T06:12:52.541Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` _________________________________________ 1. Create a Interac Payment ``` { "amount": 1500, "currency": "CAD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "profile_id": "pro_ZOeeFgbR94MvAzeqRgCP", "authentication_type": "three_ds", "payment_method": "bank_redirect", "payment_method_type": "interac", "payment_method_data": { "bank_redirect": { "interac": {} } }, "billing": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "SG", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` Response ``` { "payment_id": "pay_z7YQYcZmsvJqgvaULlib", "merchant_id": "merchant_1758109811", "status": "requires_customer_action", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 1500, "amount_received": null, "connector": "paysafe", "client_secret": "pay_z7YQYcZmsvJqgvaULlib_secret_pP5mHo1dYDNdpTaEvzJM", "created": "2025-09-17T12:14:15.417Z", "currency": "CAD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_z7YQYcZmsvJqgvaULlib/merchant_1758109811/pay_z7YQYcZmsvJqgvaULlib_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "interac", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "aaaa", "created_at": 1758111255, "expires": 1758114855, "secret": "epk_a1d811edc6eb473e91d84edd854bc78f" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_ZOeeFgbR94MvAzeqRgCP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RgaQGT7EpJ4ktWrgTjiW", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-17T12:29:15.417Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-17T12:14:16.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": null, "card_discovery": null, "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` Complete the payment using redirection 2. Do psync We will get `succeeded` status ____________________________________ 1. Create Paysafe gift card payment ``` { "amount": 1500, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "profile_id": "pro_ZOeeFgbR94MvAzeqRgCP", "authentication_type": "three_ds", "payment_method": "gift_card", "payment_method_type": "pay_safe_card", "payment_method_data": { "gift_card": { "pay_safe_card": {} } }, "billing": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "SG", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" } } ``` Response ``` { "payment_id": "pay_e1mvzY3QHPNkUoq95Y3r", "merchant_id": "merchant_1758109811", "status": "requires_customer_action", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 1500, "amount_received": null, "connector": "paysafe", "client_secret": "pay_e1mvzY3QHPNkUoq95Y3r_secret_GeqxmczpZ6Rl3WAa2qye", "created": "2025-09-17T12:15:54.727Z", "currency": "USD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "gift_card", "payment_method_data": { "gift_card": { "pay_safe_card": {} }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_e1mvzY3QHPNkUoq95Y3r/merchant_1758109811/pay_e1mvzY3QHPNkUoq95Y3r_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pay_safe_card", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "aaaa", "created_at": 1758111354, "expires": 1758114954, "secret": "epk_f8d75c19c2af479ebc9f5466bea7156b" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_ZOeeFgbR94MvAzeqRgCP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RgaQGT7EpJ4ktWrgTjiW", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-17T12:30:54.726Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-17T12:15:56.032Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` Complete payment using redirection 2. Do psync , Response ``` { "payment_id": "pay_e1mvzY3QHPNkUoq95Y3r", "merchant_id": "merchant_1758109811", "status": "succeeded", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1500, "connector": "paysafe", "client_secret": "pay_e1mvzY3QHPNkUoq95Y3r_secret_GeqxmczpZ6Rl3WAa2qye", "created": "2025-09-17T12:15:54.727Z", "currency": "USD", "customer_id": "aaaa", "customer": { "id": "aaaa", "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": "gift_card", "payment_method_data": { "gift_card": { "pay_safe_card": {} }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pay_safe_card", "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": "16591c55-a1d0-48b3-bd5f-0b86fe514be8", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_ZOeeFgbR94MvAzeqRgCP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RgaQGT7EpJ4ktWrgTjiW", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-17T12:30:54.726Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-17T12:16:06.859Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
15406557c11041bab6358f2b4b916d7333fc0a0f
juspay/hyperswitch
juspay__hyperswitch-9392
Bug: Fix bugs in peachpayments and add Cypress test for Peachpayments Fix bugs in peachpayments and add Cypress test for Peachpayments
diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs index a5e34b416ac..9b1776bf056 100644 --- a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs @@ -16,7 +16,6 @@ use hyperswitch_interfaces::{ }; use masking::Secret; use serde::{Deserialize, Serialize}; -use strum::Display; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use crate::{ @@ -70,68 +69,78 @@ pub struct EcommerceCardPaymentOnlyTransactionData { pub routing: Routing, pub card: CardDetails, pub amount: AmountDetails, - #[serde(skip_serializing_if = "Option::is_none")] - pub three_ds_data: Option<ThreeDSData>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde[rename_all = "camelCase"]] pub struct MerchantInformation { - pub client_merchant_reference_id: String, - pub name: String, - pub mcc: String, + pub client_merchant_reference_id: Secret<String>, + pub name: Secret<String>, + pub mcc: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option<String>, + pub phone: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<String>, + pub email: Option<pii::Email>, #[serde(skip_serializing_if = "Option::is_none")] - pub mobile: Option<String>, + pub mobile: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option<String>, + pub address: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option<String>, + pub city: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub postal_code: Option<String>, + pub postal_code: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub region_code: Option<String>, + pub region_code: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub merchant_type: Option<String>, + pub merchant_type: Option<MerchantType>, #[serde(skip_serializing_if = "Option::is_none")] - pub website_url: Option<String>, + pub website_url: Option<url::Url>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "lowercase"]] +pub enum MerchantType { + Standard, + Sub, + Iso, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde[rename_all = "camelCase"]] pub struct Routing { - pub route: String, - pub mid: String, - pub tid: String, + pub route: Route, + pub mid: Secret<String>, + pub tid: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] - pub visa_payment_facilitator_id: Option<String>, + pub visa_payment_facilitator_id: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub master_card_payment_facilitator_id: Option<String>, + pub master_card_payment_facilitator_id: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub sub_mid: Option<String>, + pub sub_mid: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub amex_id: Option<String>, + pub amex_id: Option<Secret<String>>, } -#[derive(Debug, Serialize, PartialEq)] -#[serde[rename_all = "camelCase"]] -pub struct CardDetails { - pub pan: CardNumber, - #[serde(skip_serializing_if = "Option::is_none")] - pub cardholder_name: Option<Secret<String>>, - pub expiry_year: Secret<String>, - pub expiry_month: Secret<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub cvv: Option<Secret<String>>, +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "snake_case"]] +pub enum Route { + ExipayEmulator, + AbsaBase24, + NedbankPostbridge, + AbsaPostbridgeEcentric, + PostbridgeDirecttransact, + PostbridgeEfficacy, + FiservLloyds, + NfsIzwe, + AbsaHpsZambia, + EcentricEcommerce, + UnitTestEmptyConfig, } #[derive(Debug, Serialize, PartialEq)] #[serde[rename_all = "camelCase"]] -pub struct RefundCardDetails { - pub pan: Secret<String>, +pub struct CardDetails { + pub pan: CardNumber, #[serde(skip_serializing_if = "Option::is_none")] pub cardholder_name: Option<Secret<String>>, pub expiry_year: Secret<String>, @@ -145,21 +154,8 @@ pub struct RefundCardDetails { pub struct AmountDetails { pub amount: MinorUnit, pub currency_code: String, -} - -#[derive(Debug, Serialize, PartialEq)] -#[serde[rename_all = "camelCase"]] -pub struct ThreeDSData { - #[serde(skip_serializing_if = "Option::is_none")] - pub cavv: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub tavv: Option<Secret<String>>, - pub eci: String, - pub ds_trans_id: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub xid: Option<String>, - pub authentication_status: AuthenticationStatus, - pub three_ds_version: String, + pub display_amount: Option<String>, } // Confirm Transaction Request (for capture) @@ -199,6 +195,7 @@ impl TryFrom<&PeachpaymentsRouterData<&PaymentsCaptureRouterData>> for Peachpaym let amount = AmountDetails { amount: amount_in_cents, currency_code: item.router_data.request.currency.to_string(), + display_amount: None, }; let confirmation_data = EcommerceCardPaymentOnlyConfirmationData { amount }; @@ -271,57 +268,40 @@ impl TryFrom<&PaymentsCancelRouterData> for PeachpaymentsVoidRequest { } } -#[derive(Debug, Serialize, PartialEq)] -pub enum AuthenticationStatus { - Y, // Fully authenticated - A, // Attempted authentication / liability shift - N, // Not authenticated / failed -} - -impl From<&str> for AuthenticationStatus { - fn from(eci: &str) -> Self { - match eci { - "05" | "06" => Self::Y, - "07" => Self::A, - _ => Self::N, - } - } -} - #[derive(Debug, Serialize, Deserialize)] pub struct PeachPaymentsConnectorMetadataObject { - pub client_merchant_reference_id: String, - pub name: String, - pub mcc: String, + pub client_merchant_reference_id: Secret<String>, + pub name: Secret<String>, + pub mcc: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option<String>, + pub phone: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<String>, + pub email: Option<pii::Email>, #[serde(skip_serializing_if = "Option::is_none")] - pub mobile: Option<String>, + pub mobile: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option<String>, + pub address: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option<String>, + pub city: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub postal_code: Option<String>, + pub postal_code: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub region_code: Option<String>, + pub region_code: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub merchant_type: Option<String>, + pub merchant_type: Option<MerchantType>, #[serde(skip_serializing_if = "Option::is_none")] - pub website_url: Option<String>, - pub route: String, - pub mid: String, - pub tid: String, + pub website_url: Option<url::Url>, + pub route: Route, + pub mid: Secret<String>, + pub tid: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] - pub visa_payment_facilitator_id: Option<String>, + pub visa_payment_facilitator_id: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub master_card_payment_facilitator_id: Option<String>, + pub master_card_payment_facilitator_id: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub sub_mid: Option<String>, + pub sub_mid: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] - pub amex_id: Option<String>, + pub amex_id: Option<Secret<String>>, } impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>> @@ -379,55 +359,14 @@ impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>> let amount = AmountDetails { amount: amount_in_cents, currency_code: item.router_data.request.currency.to_string(), + display_amount: None, }; - // Extract 3DS data if available - let three_ds_data = item - .router_data - .request - .authentication_data - .as_ref() - .and_then(|auth_data| { - // Only include 3DS data if we have essential fields (ECI is most critical) - if let Some(eci) = &auth_data.eci { - let ds_trans_id = auth_data - .ds_trans_id - .clone() - .or_else(|| auth_data.threeds_server_transaction_id.clone())?; - - // Determine authentication status based on ECI value - let authentication_status = eci.as_str().into(); - - // Convert message version to string, handling None case - let three_ds_version = auth_data.message_version.as_ref().map(|v| { - let version_str = v.to_string(); - let mut parts = version_str.split('.'); - match (parts.next(), parts.next()) { - (Some(major), Some(minor)) => format!("{}.{}", major, minor), - _ => v.to_string(), // fallback if format unexpected - } - })?; - - Some(ThreeDSData { - cavv: Some(auth_data.cavv.clone()), - tavv: None, // Network token field - not available in Hyperswitch AuthenticationData - eci: eci.clone(), - ds_trans_id, - xid: None, // Legacy 3DS 1.x/network token field - not available in Hyperswitch AuthenticationData - authentication_status, - three_ds_version, - }) - } else { - None - } - }); - let ecommerce_data = EcommerceCardPaymentOnlyTransactionData { merchant_information, routing, card, amount, - three_ds_data, }; // Generate current timestamp for sendDateTime (ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ) @@ -469,18 +408,16 @@ impl TryFrom<&ConnectorAuthType> for PeachpaymentsAuthType { } // Card Gateway API Response #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] +#[serde(rename_all = "snake_case")] pub enum PeachpaymentsPaymentStatus { Successful, Pending, Authorized, Approved, - #[serde(rename = "approved_confirmed")] ApprovedConfirmed, Declined, Failed, Reversed, - #[serde(rename = "threeds_required")] ThreedsRequired, Voided, } @@ -509,9 +446,8 @@ impl From<PeachpaymentsPaymentStatus> for common_enums::AttemptStatus { #[serde[rename_all = "camelCase"]] pub struct PeachpaymentsPaymentsResponse { pub transaction_id: String, - pub response_code: ResponseCode, + pub response_code: Option<ResponseCode>, pub transaction_result: PeachpaymentsPaymentStatus, - #[serde(skip_serializing_if = "Option::is_none")] pub ecommerce_card_payment_only_transaction_data: Option<EcommerceCardPaymentOnlyResponseData>, } @@ -520,24 +456,26 @@ pub struct PeachpaymentsPaymentsResponse { #[serde[rename_all = "camelCase"]] pub struct PeachpaymentsConfirmResponse { pub transaction_id: String, - pub response_code: ResponseCode, + pub response_code: Option<ResponseCode>, pub transaction_result: PeachpaymentsPaymentStatus, - #[serde(skip_serializing_if = "Option::is_none")] pub authorization_code: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "camelCase"]] #[serde(untagged)] pub enum ResponseCode { Text(String), Structured { - value: ResponseCodeValue, + value: String, description: String, + terminal_outcome_string: Option<String>, + receipt_string: Option<String>, }, } impl ResponseCode { - pub fn value(&self) -> Option<&ResponseCodeValue> { + pub fn value(&self) -> Option<&String> { match self { Self::Structured { value, .. } => Some(value), _ => None, @@ -559,33 +497,48 @@ impl ResponseCode { } } -#[derive(Debug, Display, Clone, Serialize, Deserialize, PartialEq)] -pub enum ResponseCodeValue { - #[serde(rename = "00", alias = "08")] - Success, -} - #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "camelCase"]] pub struct EcommerceCardPaymentOnlyResponseData { - pub card: Option<CardResponseData>, pub amount: Option<AmountDetails>, - pub stan: Option<String>, - pub rrn: Option<String>, - #[serde(rename = "approvalCode")] + pub stan: Option<Secret<String>>, + pub rrn: Option<Secret<String>>, pub approval_code: Option<String>, - #[serde(rename = "merchantAdviceCode")] pub merchant_advice_code: Option<String>, pub description: Option<String>, + pub trace_id: Option<String>, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[serde[rename_all = "camelCase"]] -pub struct CardResponseData { - pub bin_number: Option<String>, - pub masked_pan: Option<String>, - pub cardholder_name: Option<String>, - pub expiry_month: Option<String>, - pub expiry_year: Option<String>, +fn is_payment_success(value: Option<&String>) -> bool { + if let Some(val) = value { + val == "00" || val == "08" || val == "X94" + } else { + false + } +} + +fn get_error_code(response_code: Option<&ResponseCode>) -> String { + response_code + .and_then(|code| code.value()) + .map(|val| val.to_string()) + .unwrap_or( + response_code + .and_then(|code| code.as_text()) + .map(|text| text.to_string()) + .unwrap_or(NO_ERROR_CODE.to_string()), + ) +} + +fn get_error_message(response_code: Option<&ResponseCode>) -> String { + response_code + .and_then(|code| code.description()) + .map(|desc| desc.to_string()) + .unwrap_or( + response_code + .and_then(|code| code.as_text()) + .map(|text| text.to_string()) + .unwrap_or(NO_ERROR_MESSAGE.to_string()), + ) } impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>> @@ -598,20 +551,15 @@ impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, Payme let status = common_enums::AttemptStatus::from(item.response.transaction_result); // Check if it's an error response - let response = if item.response.response_code.value() != Some(&ResponseCodeValue::Success) { + let response = if !is_payment_success( + item.response + .response_code + .as_ref() + .and_then(|code| code.value()), + ) { Err(ErrorResponse { - code: item - .response - .response_code - .value() - .map(|val| val.to_string()) - .unwrap_or(NO_ERROR_CODE.to_string()), - message: item - .response - .response_code - .description() - .map(|desc| desc.to_string()) - .unwrap_or(NO_ERROR_MESSAGE.to_string()), + code: get_error_code(item.response.response_code.as_ref()), + message: get_error_message(item.response.response_code.as_ref()), reason: item .response .ecommerce_card_payment_only_transaction_data @@ -658,20 +606,15 @@ impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsConfirmResponse, T, Paymen let status = common_enums::AttemptStatus::from(item.response.transaction_result); // Check if it's an error response - let response = if item.response.response_code.value() != Some(&ResponseCodeValue::Success) { + let response = if !is_payment_success( + item.response + .response_code + .as_ref() + .and_then(|code| code.value()), + ) { Err(ErrorResponse { - code: item - .response - .response_code - .value() - .map(|val| val.to_string()) - .unwrap_or(NO_ERROR_CODE.to_string()), - message: item - .response - .response_code - .description() - .map(|desc| desc.to_string()) - .unwrap_or(NO_ERROR_MESSAGE.to_string()), + code: get_error_code(item.response.response_code.as_ref()), + message: get_error_message(item.response.response_code.as_ref()), reason: None, status_code: item.http_code, attempt_status: Some(status), @@ -720,6 +663,7 @@ impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>> let amount = AmountDetails { amount: amount_in_cents, currency_code: item.router_data.request.currency.to_string(), + display_amount: None, }; let confirmation_data = EcommerceCardPaymentOnlyConfirmationData { amount }; 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 32a1c175ea0..f61c789fe2f 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1538,6 +1538,10 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { ), (Connector::Paypal, fields(vec![], card_basic(), vec![])), (Connector::Payu, fields(vec![], card_basic(), vec![])), + ( + Connector::Peachpayments, + fields(vec![], vec![], card_with_name()), + ), ( Connector::Powertranz, fields(vec![], card_with_name(), vec![]),
2025-09-15T16:40:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9392) ## Description <!-- Describe your changes in detail --> Fixed bugs and added cypress test 1. Made sensitive informations as Secret. 2. Resolved Deserialization error in Payments Response 3. Removed unnecessary structs ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 5. `crates/router/src/configs` 6. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Test 1. Previously error response from connector end was getting deserialization error but now it's getting deserialized Payments - Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_4XwGvSX1WUNBozVTSoR0qBIPamQg9lArgmef44Z4m5onvvCWRQwGtm7vlkzprgCe' \ --data-raw '{ "amount": 4510, "currency": "USD", "confirm": true, "capture_method": "manual", "authentication_type": "no_three_ds", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "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" }' ``` Response: ``` { "payment_id": "pay_nXdonksTZgNzS3TukSiC", "merchant_id": "merchant_1757951892", "status": "failed", "amount": 4510, "net_amount": 4510, "shipping_cost": null, "amount_capturable": 4510, "amount_received": null, "connector": "peachpayments", "client_secret": "pay_nXdonksTZgNzS3TukSiC_secret_SorQgwmawwbNSaAxbZHB", "created": "2025-09-15T17:02:32.989Z", "currency": "USD", "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": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "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": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": 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": "10", "error_message": "Approved for partial amount", "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": 1757955752, "expires": 1757959352, "secret": "epk_aeab9e4bf1b14c6da933533a5f1b0d51" }, "manual_retry_allowed": null, "connector_transaction_id": "0b8298ce-34a6-45e4-baf2-1e44edd98076", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_ddJMerdREreozAswfmdi", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_i4R4BSvIXZXfZv4ieVIH", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-15T17:17:32.989Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-15T17:02:34.974Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": { "network_advice_code": null } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
8ed3f7dbf27e939a72957fb5751abbf61bd642c0
juspay/hyperswitch
juspay__hyperswitch-9385
Bug: CI DB Migration consistency checks failing after diesel_cli 2.3.0 update After the release of diesel_cli version `2.3.0`, the CI checks for DB migration consistency are failing due to a formatting difference in the output. diesel_cli version 2.3.0 expects to call rustfmt to format its output. If rustfmt is not installed on the system it will give an error. Need to add a step to install rustfmt to fix the workflow
2025-09-15T11:55:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> - `diesel_cli` version `2.3.0` expects to call `rustfmt` to format its output. If `rustfmt` is not installed on the system it will give an error. - Added a step to install `rustfmt` to fix the workflow ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #9385 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Verified CI checks ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
4ce1c8c284d8cfa41671ca70c0aecdf145584906
juspay/hyperswitch
juspay__hyperswitch-9381
Bug: [FIX]: fix wasm for paysafe connector fix account_id metadata structure of wasm
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index dfede98f1e4..0a521f7a864 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -108,6 +108,19 @@ pub struct ConfigMerchantAdditionalDetails { pub plusgiro: Option<Vec<InputData>>, } +#[serde_with::skip_serializing_none] +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct AccountIdConfigForCard { + pub three_ds: Option<Vec<InputData>>, + pub no_three_ds: Option<Vec<InputData>>, +} + +#[serde_with::skip_serializing_none] +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct AccountIDSupportedMethods { + card: HashMap<String, AccountIdConfigForCard>, +} + #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConfigMetadata { @@ -149,7 +162,7 @@ pub struct ConfigMetadata { pub proxy_url: Option<InputData>, pub shop_name: Option<InputData>, pub merchant_funding_source: Option<InputData>, - pub account_id: Option<InputData>, + pub account_id: Option<AccountIDSupportedMethods>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index a5de72b6e24..0f9fa995409 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6833,12 +6833,30 @@ api_key = "Username" key1 = "Password" [paysafe.connector_webhook_details] merchant_secret = "Source verification key" -[paysafe.metadata.account_id] +[[paysafe.metadata.account_id.card.USD.three_ds]] name="account_id" -label="Payment Method Account ID" -placeholder="Enter Account ID" +label="ThreeDS account id" +placeholder="Enter ThreeDS Account ID" required=true -type="Text" +type="Number" +[[paysafe.metadata.account_id.card.USD.no_three_ds]] +name="no_three_ds" +label="Non ThreeDS account id" +placeholder="Enter Non ThreeDS Account ID" +required=true +type="Number" +[[paysafe.metadata.account_id.card.EUR.three_ds]] +name="account_id" +label="ThreeDS account id" +placeholder="Enter ThreeDS Account ID" +required=true +type="Number" +[[paysafe.metadata.account_id.card.EUR.no_three_ds]] +name="no_three_ds" +label="Non ThreeDS account id" +placeholder="Enter Non ThreeDS Account ID" +required=true +type="Number" [peachpayments] [[peachpayments.credit]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 3515ff2c58b..96d473a386c 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5502,12 +5502,30 @@ api_key = "Username" key1 = "Password" [paysafe.connector_webhook_details] merchant_secret = "Source verification key" -[paysafe.metadata.account_id] +[[paysafe.metadata.account_id.card.USD.three_ds]] name="account_id" -label="Payment Method Account ID" -placeholder="Enter Account ID" +label="ThreeDS account id" +placeholder="Enter ThreeDS Account ID" required=true -type="Text" +type="Number" +[[paysafe.metadata.account_id.card.USD.no_three_ds]] +name="no_three_ds" +label="Non ThreeDS account id" +placeholder="Enter Non ThreeDS Account ID" +required=true +type="Number" +[[paysafe.metadata.account_id.card.EUR.three_ds]] +name="account_id" +label="ThreeDS account id" +placeholder="Enter ThreeDS Account ID" +required=true +type="Number" +[[paysafe.metadata.account_id.card.EUR.no_three_ds]] +name="no_three_ds" +label="Non ThreeDS account id" +placeholder="Enter Non ThreeDS Account ID" +required=true +type="Number" [peachpayments] [[peachpayments.credit]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 9cfb45cf6db..45da96d5344 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6816,12 +6816,30 @@ api_key = "Username" key1 = "Password" [paysafe.connector_webhook_details] merchant_secret = "Source verification key" -[paysafe.metadata.account_id] +[[paysafe.metadata.account_id.card.USD.three_ds]] name="account_id" -label="Payment Method Account ID" -placeholder="Enter Account ID" +label="ThreeDS account id" +placeholder="Enter ThreeDS Account ID" required=true -type="Text" +type="Number" +[[paysafe.metadata.account_id.card.USD.no_three_ds]] +name="no_three_ds" +label="Non ThreeDS account id" +placeholder="Enter Non ThreeDS Account ID" +required=true +type="Number" +[[paysafe.metadata.account_id.card.EUR.three_ds]] +name="account_id" +label="ThreeDS account id" +placeholder="Enter ThreeDS Account ID" +required=true +type="Number" +[[paysafe.metadata.account_id.card.EUR.no_three_ds]] +name="no_three_ds" +label="Non ThreeDS account id" +placeholder="Enter Non ThreeDS Account ID" +required=true +type="Number"
2025-09-15T09:17:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Wasm changes for paysafe card 3ds ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <img width="656" height="532" alt="Screenshot 2025-09-15 at 4 48 08 PM" src="https://github.com/user-attachments/assets/3f8b0d3c-22b6-4fb1-a94c-d4221d8ed035" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
655b374feca2d53cdd4598eae2c8646aa3c092e1
juspay/hyperswitch
juspay__hyperswitch-9383
Bug: [BUG] update adyenplatform's error mapping for payout failures ### Bug Description Adyen Platform connector has two main issues: 1. Error responses do not include valuable error details from the `detail` field when `invalid_fields` is not present 2. Improper use of `ApiErrorResponse::PayoutFailed` in core payout logic causes incorrect error handling patterns in the API response ### Expected Behavior - When Adyen returns error responses with meaningful information in the `detail` field (but no `invalid_fields`), the error message should include both the title and detail - Payout errors should follow proper pre-connector vs post-connector error handling patterns, with connector-specific errors being handled by the connector's error response mapping ### Actual Behavior - Error responses only include the `title` field, missing valuable context from the `detail` field - Core payout logic throws `PayoutFailed` errors after connector calls, which bypasses proper connector error handling and results in generic error messages instead of connector-specific error details ### Steps To Reproduce - Create a payout request that triggers an Adyen error with `detail` field but no `invalid_fields` (invalid currency / amount etc.) - Observe that only the title is included in the error message - Notice that some error scenarios result in generic `PayoutFailed` errors instead of detailed connector error responses ### 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/adyenplatform.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs index 71feb122d17..c20d50d974b 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs @@ -115,10 +115,24 @@ impl ConnectorCommon for Adyenplatform { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let message = if let Some(invalid_fields) = &response.invalid_fields { + match serde_json::to_string(invalid_fields) { + Ok(invalid_fields_json) => format!( + "{}\nInvalid fields: {}", + response.title, invalid_fields_json + ), + Err(_) => response.title.clone(), + } + } else if let Some(detail) = &response.detail { + format!("{}\nDetail: {}", response.title, detail) + } else { + response.title.clone() + }; + Ok(ErrorResponse { status_code: res.status_code, code: response.error_code, - message: response.title, + message, reason: response.detail, attempt_status: None, connector_transaction_id: None, diff --git a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs index ec654971e41..2f49d297569 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs @@ -206,7 +206,7 @@ pub enum AdyenTransactionDirection { Outgoing, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, Serialize, Deserialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum AdyenTransferStatus { Authorised, @@ -582,10 +582,27 @@ impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> for Payouts let response: AdyenTransferResponse = item.response; let status = enums::PayoutStatus::from(response.status); - let error_code = match status { - enums::PayoutStatus::Ineligible => Some(response.reason), - _ => None, - }; + if matches!(status, enums::PayoutStatus::Failed) { + return Ok(Self { + response: Err(hyperswitch_domain_models::router_data::ErrorResponse { + code: response.status.to_string(), + message: if !response.reason.is_empty() { + response.reason + } else { + response.status.to_string() + }, + reason: None, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(response.id), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, + }), + ..item.data + }); + } Ok(Self { response: Ok(types::PayoutsResponseData { @@ -593,7 +610,7 @@ impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> for Payouts connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, - error_code, + error_code: None, error_message: None, }), ..item.data @@ -605,8 +622,7 @@ impl From<AdyenTransferStatus> for enums::PayoutStatus { fn from(adyen_status: AdyenTransferStatus) -> Self { match adyen_status { AdyenTransferStatus::Authorised => Self::Initiated, - AdyenTransferStatus::Refused => Self::Ineligible, - AdyenTransferStatus::Error => Self::Failed, + AdyenTransferStatus::Error | AdyenTransferStatus::Refused => Self::Failed, } } } diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 491957045c7..714fafe8d5a 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -705,14 +705,6 @@ pub async fn payouts_fulfill_core( .await .attach_printable("Payout fulfillment failed for given Payout request")?; - if helpers::is_payout_err_state(status) { - return Err(report!(errors::ApiErrorResponse::PayoutFailed { - data: Some( - serde_json::json!({"payout_status": status.to_string(), "error_message": payout_attempt.error_message, "error_code": payout_attempt.error_code}) - ), - })); - } - trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } @@ -1324,9 +1316,65 @@ pub async fn create_recipient( .attach_printable("Error updating payouts in db")?; } } - Err(err) => Err(errors::ApiErrorResponse::PayoutFailed { - data: serde_json::to_value(err).ok(), - })?, + Err(err) => { + let status = storage_enums::PayoutStatus::Failed; + let (error_code, error_message) = (Some(err.code), Some(err.message)); + let (unified_code, unified_message) = helpers::get_gsm_record( + state, + error_code.clone(), + error_message.clone(), + payout_data.payout_attempt.connector.clone(), + consts::PAYOUT_FLOW_STR, + ) + .await + .map_or( + ( + Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()), + Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()), + ), + |gsm| (gsm.unified_code, gsm.unified_message), + ); + let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { + connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), + status, + error_code, + error_message, + is_eligible: None, + unified_code: unified_code + .map(UnifiedCode::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_code", + })?, + unified_message: unified_message + .map(UnifiedMessage::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_message", + })?, + }; + let db = &*state.store; + payout_data.payout_attempt = db + .update_payout_attempt( + &payout_data.payout_attempt, + updated_payout_attempt, + &payout_data.payouts, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error updating payout_attempt in db")?; + payout_data.payouts = db + .update_payout( + &payout_data.payouts, + storage::PayoutsUpdate::StatusUpdate { status }, + &payout_data.payout_attempt, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error updating payouts in db")?; + } } } Ok(()) @@ -1371,10 +1419,8 @@ pub async fn complete_payout_eligibility( .is_eligible .unwrap_or(state.conf.payouts.payout_eligibility), || { - Err(report!(errors::ApiErrorResponse::PayoutFailed { - data: Some(serde_json::json!({ - "message": "Payout method data is invalid" - })) + Err(report!(errors::ApiErrorResponse::InvalidRequestData { + message: "Payout method data is invalid".to_string(), }) .attach_printable("Payout data provided is invalid")) }, @@ -1454,13 +1500,6 @@ pub async fn check_payout_eligibility( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; - if helpers::is_payout_err_state(status) { - return Err(report!(errors::ApiErrorResponse::PayoutFailed { - data: Some( - serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()}) - ), - })); - } } Err(err) => { let status = storage_enums::PayoutStatus::Failed; @@ -1676,13 +1715,6 @@ pub async fn create_payout( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; - if helpers::is_payout_err_state(status) { - return Err(report!(errors::ApiErrorResponse::PayoutFailed { - data: Some( - serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()}) - ), - })); - } } Err(err) => { let status = storage_enums::PayoutStatus::Failed; @@ -2407,13 +2439,7 @@ pub async fn fulfill_payout( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; - if helpers::is_payout_err_state(status) { - return Err(report!(errors::ApiErrorResponse::PayoutFailed { - data: Some( - serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()}) - ), - })); - } else if payout_data.payouts.recurring + if payout_data.payouts.recurring && payout_data.payouts.payout_method_id.clone().is_none() { let payout_method_data = payout_data
2025-09-15T11:51:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR fixes two critical issues in Adyen Platform connector and payout core flow error handling: 1. **Enhanced error message construction**: Modified `build_error_response` in `crates/hyperswitch_connectors/src/connectors/adyenplatform.rs` to include the `detail` field when `invalid_fields` is not present. This provides users with comprehensive error information, especially for business logic errors where Adyen provides detailed explanations. 2. **Fixed improper PayoutFailed usage**: Removed multiple instances of `PayoutFailed` from core payouts flow that were being thrown after connector calls. This was bypassing proper connector error handling and preventing detailed error messages from reaching the API response. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## 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. --> This PR allows mapping the right error codes and messages from Adyenplatform to HyperSwitch's payout API response in case of failures. **Solution**: This change ensures that all available error information from Adyen is properly communicated to users, improving the debugging experience and reducing support overhead. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <details> <summary>1. Create a payout in an account without any funds</summary> cURL (AUD has 0 balance) curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_7fXFUFajfCYtS5aKrQXJMyIiBLr2gw3Y862wqkp6qXHpl88H0hQaEr89xAnvsxvp' \ --data-raw '{"amount":1,"currency":"AUD","profile_id":"pro_E9Z7dCKDd54NaVYCFFhF","customer":{"id":"cus_X7urM1AQqvpECo6G5XkW","name":"New Name"},"connector":["adyenplatform"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111111111111111","expiry_month":"01","expiry_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","city":"San Fransico","state":"CA","country":"IT","first_name":"John","last_name":"Doe"},"email":"[email protected]"},"recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_cX5OwgVAuqaHJkF9zxeu","merchant_id":"merchant_1757926554","merchant_order_reference_id":null,"amount":1,"currency":"AUD","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":"JP Morgan","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"INDIA","bank_code":"JP_JPM","last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"01","card_exp_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":null,"zip":null,"state":"CA","first_name":"John","last_name":"Doe","origin_zip":null},"phone":null,"email":"[email protected]"},"auto_fulfill":true,"customer_id":"cus_X7urM1AQqvpECo6G5XkW","customer":{"id":"cus_X7urM1AQqvpECo6G5XkW","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_cX5OwgVAuqaHJkF9zxeu_secret_eIw5TJyjUYBydBp3Aa5c","return_url":null,"business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_m86KCMmTaeQ2mTtSgfRA","status":"failed","error_message":"notEnoughBalance","error_code":"Refused","profile_id":"pro_E9Z7dCKDd54NaVYCFFhF","created":"2025-09-15T11:55:40.044Z","connector_transaction_id":null,"priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":"UE_9000","unified_message":"Something went wrong","payout_method_id":null} Expectation - Payout must fail - error_message and error_code must be populated </details> <details> <summary>2. Create a payout using invalid transfer details</summary> cURL (Invalid postcode) curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_7fXFUFajfCYtS5aKrQXJMyIiBLr2gw3Y862wqkp6qXHpl88H0hQaEr89xAnvsxvp' \ --data-raw '{"amount":1,"currency":"EUR","profile_id":"pro_E9Z7dCKDd54NaVYCFFhF","customer":{"id":"cus_X7urM1AQqvpECo6G5XkW","name":"New Name"},"connector":["adyenplatform"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111111111111111","expiry_month":"01","expiry_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","city":"San Fransico","state":"CA","zip":"123","country":"IT","first_name":"John","last_name":"Doe"},"email":"[email protected]"},"recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_lAUUuhWCoj1qVo9jwHeQ","merchant_id":"merchant_1757926554","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":"JP Morgan","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"INDIA","bank_code":"JP_JPM","last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"01","card_exp_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":null,"zip":"123","state":"CA","first_name":"John","last_name":"Doe","origin_zip":null},"phone":null,"email":"[email protected]"},"auto_fulfill":true,"customer_id":"cus_X7urM1AQqvpECo6G5XkW","customer":{"id":"cus_X7urM1AQqvpECo6G5XkW","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_lAUUuhWCoj1qVo9jwHeQ_secret_Bl8J3MXCywJd0j2EzzGk","return_url":null,"business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_m86KCMmTaeQ2mTtSgfRA","status":"failed","error_message":"Invalid transfer information provided\nInvalid fields: [{\"name\":\"counterparty.cardHolder.address.postalCode\",\"value\":\"123\",\"message\":\"Not valid for IT. Allowed formats: NNNNN.\"}]","error_code":"30_081","profile_id":"pro_E9Z7dCKDd54NaVYCFFhF","created":"2025-09-15T11:57:20.960Z","connector_transaction_id":null,"priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":"UE_9000","unified_message":"Something went wrong","payout_method_id":null} cURL (Invalid expiry) curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_7fXFUFajfCYtS5aKrQXJMyIiBLr2gw3Y862wqkp6qXHpl88H0hQaEr89xAnvsxvp' \ --data-raw '{"amount":1,"currency":"EUR","profile_id":"pro_E9Z7dCKDd54NaVYCFFhF","customer":{"id":"cus_X7urM1AQqvpECo6G5XkW","name":"New Name"},"connector":["adyenplatform"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111111111111111","expiry_month":"01","expiry_year":"2024","card_holder_name":"John Doe"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","city":"San Fransico","state":"CA","country":"IT","first_name":"John","last_name":"Doe"},"email":"[email protected]"},"recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_ME3BMSySpDKtX5tsZI7S","merchant_id":"merchant_1757926554","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":"JP Morgan","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"INDIA","bank_code":"JP_JPM","last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"01","card_exp_year":"2024","card_holder_name":"John Doe"}},"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":null,"zip":null,"state":"CA","first_name":"John","last_name":"Doe","origin_zip":null},"phone":null,"email":"[email protected]"},"auto_fulfill":true,"customer_id":"cus_X7urM1AQqvpECo6G5XkW","customer":{"id":"cus_X7urM1AQqvpECo6G5XkW","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_ME3BMSySpDKtX5tsZI7S_secret_T2I0yoRxYatQobkNfApR","return_url":null,"business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_m86KCMmTaeQ2mTtSgfRA","status":"failed","error_message":"Invalid transfer information provided\nInvalid fields: [{\"name\":\"counterparty.cardIdentification.expiryYear\",\"value\":\"2024\",\"message\":\"Expiry date must be in the future\"},{\"name\":\"counterparty.cardIdentification.expiryMonth\",\"value\":\"01\",\"message\":\"Expiry date must be in the future\"}]","error_code":"30_081","profile_id":"pro_E9Z7dCKDd54NaVYCFFhF","created":"2025-09-15T11:58:19.648Z","connector_transaction_id":null,"priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":"UE_9000","unified_message":"Something went wrong","payout_method_id":null} cURL (Invalid state) curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_7fXFUFajfCYtS5aKrQXJMyIiBLr2gw3Y862wqkp6qXHpl88H0hQaEr89xAnvsxvp' \ --data-raw '{"amount":1,"currency":"EUR","profile_id":"pro_E9Z7dCKDd54NaVYCFFhF","customer":{"id":"cus_X7urM1AQqvpECo6G5XkW","name":"New Name"},"connector":["adyenplatform"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111111111111111","expiry_month":"03","expiry_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","city":"San Fransico","state":"CA","country":"AU","first_name":"John","last_name":"Doe"},"email":"[email protected]"},"recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_7s7zCL1wMqTmSk304LJg","merchant_id":"merchant_1757926554","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":"JP Morgan","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"INDIA","bank_code":"JP_JPM","last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"city":"San Fransico","country":"AU","line1":"1467","line2":"Harrison Street","line3":null,"zip":null,"state":"CA","first_name":"John","last_name":"Doe","origin_zip":null},"phone":null,"email":"[email protected]"},"auto_fulfill":true,"customer_id":"cus_X7urM1AQqvpECo6G5XkW","customer":{"id":"cus_X7urM1AQqvpECo6G5XkW","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_7s7zCL1wMqTmSk304LJg_secret_AlVXYS4afLwAvtoiuA12","return_url":null,"business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_m86KCMmTaeQ2mTtSgfRA","status":"failed","error_message":"Invalid transfer information provided\nInvalid fields: [{\"name\":\"counterparty.cardHolder.address.stateOrProvince\",\"value\":\"CA\",\"message\":\"Not valid for AU. Allowed values: [VIC, ACT, NSW, NT, TAS, QL... For full list visit documentation.\"}]","error_code":"30_081","profile_id":"pro_E9Z7dCKDd54NaVYCFFhF","created":"2025-09-15T11:59:00.645Z","connector_transaction_id":null,"priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":"UE_9000","unified_message":"Something went wrong","payout_method_id":null} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0e30fb6b5562bd641df6f0229d09e4311df8900e
juspay/hyperswitch
juspay__hyperswitch-9375
Bug: [BUG]: [TSYS] Payments Failing Across All Flows ### Feature Description/Summary TSYS (Total System Services) is a global payment processing platform that provides payment gateway services for merchants, payment facilitators, and acquirers. It enables businesses to accept credit and debit card payments securely across multiple channels (e-commerce, in-store, mobile, etc.). The gateway facilitates authorization, capture, settlement, and reporting while ensuring compliance with industry security standards such as PCI DSS. ### Context While attempting to process payments across all available flows using the TSYS gateway, we are consistently running into the following error response from their API in our current Hyperswitch integration: ``` SaleResponse(ErrorResponse(TsysErrorResponse { status: Fail, response_code: "F9901", response_message: "Invalid content was found starting with element 'orderNumber'. One of '{paymentFacilitatorIdentifier, paymentFacilitatorName, subMerchantIdentifier, subMerchantName, subMerchantCountryCode, subMerchantStateCode, subMerchantCity, subMerchantPostalCode, subMerchantEmailID, subMerchantPhone, isRecurring, isoIdentifier, registeredUserIndicator, laneID, authorizationIndicator, splitTenderPayment, splitTenderID, customerDetails, industryType, merchantCategoryCode, customFieldDetails, IVRMid, IVRVnumber, recipientDetails, acquirerInternalReferenceNumber, acceptorStreetAddress, serviceLocationCity, serviceLocationGeoCoordinates, skipDuplicateCheck}' is expected., " })) ``` ### Starter Tasks - Go ahead to the connector documentation and attempt to hit the connector's direct cURLs and make a happy case. - Identify the current integration issue in Hyperswitch by comparing the connector's request body and make relevant changes in the Hyperswitch codebase. ### Implementation Hints - You can go to `crates/hyperswitch_connectors/src/connectors/tsys.rs` and `crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs` and make relevant changes according to what's gone in the current integration. - Head to this documentation to get some clarity about the request and response schemas : [URL](https://www.google.com/url?q=https://developerportal.transit-pass.com/developerportal/resources/dist/%23/api-specs/.%252Fassets%252Fbuild%252Fapi%252FAPI3.0%252FCreditServices%252FAuth%252Findex.html%2523auth&sa=D&source=editors&ust=1757917256458963&usg=AOvVaw0Yt5vvn4-D6Z0T09ock1aK) ### Acceptance Criteria - [ ] Request and Response body added for each of the flows where integrity check is applied. - [ ] All the required GitHub checks passing - [ ] Formatted the code using `cargo +nightly fmt --all` ### How to Test it - Create a Merchant Account in local - Create an API Key - Add the connector - Tsys - Test out the flows ### Mentor Contact - Tag @bsayak03 [Sayak Bhattacharya] in the comments if you have any doubts/queries ### Resources Here is the connector documentation link : [URL](https://www.google.com/url?q=https://developerportal.transit-pass.com/developerportal/resources/dist/%23/api-specs/.%252Fassets%252Fbuild%252Fapi%252FAPI3.0%252FCreditServices%252FAuth%252Findex.html%2523auth&sa=D&source=editors&ust=1757917256458963&usg=AOvVaw0Yt5vvn4-D6Z0T09ock1aK) ### Pre-Flight #### 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) ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs index 6088f9ef9ca..be289fa12f1 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs @@ -52,12 +52,12 @@ pub struct TsysPaymentAuthSaleRequest { card_number: cards::CardNumber, expiration_date: Secret<String>, cvv2: Secret<String>, + order_number: String, terminal_capability: String, terminal_operating_environment: String, cardholder_authentication_method: String, #[serde(rename = "developerID")] developer_id: Secret<String>, - order_number: String, } impl TryFrom<&TsysRouterData<&types::PaymentsAuthorizeRouterData>> for TsysPaymentsRequest { @@ -80,11 +80,11 @@ impl TryFrom<&TsysRouterData<&types::PaymentsAuthorizeRouterData>> for TsysPayme expiration_date: ccard .get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?, cvv2: ccard.card_cvc, + order_number: item.connector_request_reference_id.clone(), terminal_capability: "ICC_CHIP_READ_ONLY".to_string(), terminal_operating_environment: "ON_MERCHANT_PREMISES_ATTENDED".to_string(), cardholder_authentication_method: "NOT_AUTHENTICATED".to_string(), developer_id: connector_auth.developer_id, - order_number: item.connector_request_reference_id.clone(), }; if item.request.is_auto_capture()? { Ok(Self::Sale(auth_data))
2025-09-27T09:26:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR fixes the request body order of the TSYS contract for the auth request ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context fixes #9375 ## How did you test it? Unfortunately, I'm not able to test this changes against an actual sandbox as I've been in touch with TYSY and they only provide test credentials for certification purpose. Also [this](https://github.com/juspay/hyperswitch/pull/5758) PR mention that there are not test credential for this project. I was able to reproduce mentioned in the issue by using the Sandbox inside the developer portal: <img width="619" height="358" alt="image" src="https://github.com/user-attachments/assets/55f1e712-1da1-4d3e-88ae-acc6dfbd0053" /> That's because orderNumber is the wrong group as per API specification and should be placed in a different order. If we try to put (as in the PR) right after cvv2, the request is successful: <img width="619" height="358" alt="image" src="https://github.com/user-attachments/assets/5afd2cac-7cc3-4f0d-b77b-646035b136d0" /> 1. Automatic Capture cURL: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_St9F0EWAvKEY3O3Vz020jZDJSFETJGc5E1sB0gnr9MOFBUJdHbSZDBCPnAybRQdu' \ --data-raw '{ "amount": 2500, "currency": "AED", "connector": ["tsys"], "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": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4002400000000002", "card_exp_month": "12", "card_exp_year": "2028", "card_holder_name": "Max Mustermann", "card_cvc": "999" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "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", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "109.71.40.0" } }' ``` Response: ``` { "payment_id": "pay_aodxpaq2y4Ux6byzMXuZ", "merchant_id": "merchant_1758787422", "status": "succeeded", "amount": 2500, "net_amount": 2500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 2500, "connector": "tsys", "client_secret": "pay_aodxpaq2y4Ux6byzMXuZ_secret_RUgsjBM6VI0x5aRN5PIB", "created": "2025-09-27T13:25:14.335Z", "currency": "AED", "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": "0002", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400240", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2028", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": null, "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": null, "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "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": "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": "abcdef", "created_at": 1758979514, "expires": 1758983114, "secret": "epk_7f24c06f2f3e4a4dbd0e0a2147afc80f" }, "manual_retry_allowed": null, "connector_transaction_id": "66177209", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "66177209", "payment_link": null, "profile_id": "pro_xiKo4uRjNEP5wLuam7Df", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_0iYQCYGnXC9WMGhRyb5O", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-27T13:40:14.335Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "109.71.40.0", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-27T13:25:16.190Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 2. PSync: cURL: ``` curl --location 'http://localhost:8080/payments/pay_aodxpaq2y4Ux6byzMXuZ?force_sync=true&expand_captures=true&expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_St9F0EWAvKEY3O3Vz020jZDJSFETJGc5E1sB0gnr9MOFBUJdHbSZDBCPnAybRQdu' \ --data '' ``` Response: ``` { "payment_id": "pay_aodxpaq2y4Ux6byzMXuZ", "merchant_id": "merchant_1758787422", "status": "succeeded", "amount": 2500, "net_amount": 2500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 2500, "connector": "tsys", "client_secret": "pay_aodxpaq2y4Ux6byzMXuZ_secret_RUgsjBM6VI0x5aRN5PIB", "created": "2025-09-27T13:25:14.335Z", "currency": "AED", "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, "attempts": [ { "attempt_id": "pay_aodxpaq2y4Ux6byzMXuZ_1", "status": "charged", "amount": 2500, "order_tax_amount": null, "currency": "AED", "connector": "tsys", "error_message": null, "payment_method": "card", "connector_transaction_id": "66177209", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-09-27T13:25:14.335Z", "modified_at": "2025-09-27T13:25:16.189Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "credit", "reference_id": "66177209", "unified_code": null, "unified_message": null, "client_source": null, "client_version": 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": "400240", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2028", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": null, "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": null, "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "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": "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": null, "manual_retry_allowed": null, "connector_transaction_id": "66177209", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "66177209", "payment_link": null, "profile_id": "pro_xiKo4uRjNEP5wLuam7Df", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_0iYQCYGnXC9WMGhRyb5O", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-27T13:40:14.335Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "109.71.40.0", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-27T13:25:16.190Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 3. Manual Capture: Authorize : cURL: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_St9F0EWAvKEY3O3Vz020jZDJSFETJGc5E1sB0gnr9MOFBUJdHbSZDBCPnAybRQdu' \ --data-raw '{ "amount": 2500, "currency": "AED", "connector": ["tsys"], "confirm": true, "capture_method": "manual", "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": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4002400000000002", "card_exp_month": "12", "card_exp_year": "2028", "card_holder_name": "Max Mustermann", "card_cvc": "999" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "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", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "109.71.40.0" } }' ``` Response: ``` { "payment_id": "pay_rOaIbbJ3CsOgmil9s9IS", "merchant_id": "merchant_1758787422", "status": "requires_capture", "amount": 2500, "net_amount": 2500, "shipping_cost": null, "amount_capturable": 2500, "amount_received": null, "connector": "tsys", "client_secret": "pay_rOaIbbJ3CsOgmil9s9IS_secret_99HOxs5GrYWGrG1mw5Tv", "created": "2025-09-27T13:26:45.316Z", "currency": "AED", "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": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0002", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400240", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2028", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": null, "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": null, "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "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": "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": "abcdef", "created_at": 1758979605, "expires": 1758983205, "secret": "epk_39df53c34971433e93b98adc2bddecb8" }, "manual_retry_allowed": null, "connector_transaction_id": "66177225", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "66177225", "payment_link": null, "profile_id": "pro_xiKo4uRjNEP5wLuam7Df", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_0iYQCYGnXC9WMGhRyb5O", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-27T13:41:45.316Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "109.71.40.0", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-27T13:26:46.101Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` Capture: cURL: ``` curl --location 'http://localhost:8080/payments/pay_rOaIbbJ3CsOgmil9s9IS/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_St9F0EWAvKEY3O3Vz020jZDJSFETJGc5E1sB0gnr9MOFBUJdHbSZDBCPnAybRQdu' \ --data '{ "amount_to_capture": 2500, "statement_descriptor_name": "Joseph", "statement_descriptor_prefix" :"joseph", "statement_descriptor_suffix": "JS" }' ``` Response: ``` { "payment_id": "pay_rOaIbbJ3CsOgmil9s9IS", "merchant_id": "merchant_1758787422", "status": "succeeded", "amount": 2500, "net_amount": 2500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 2500, "connector": "tsys", "client_secret": "pay_rOaIbbJ3CsOgmil9s9IS_secret_99HOxs5GrYWGrG1mw5Tv", "created": "2025-09-27T13:26:45.316Z", "currency": "AED", "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": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0002", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400240", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2028", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": null, "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": null, "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "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": "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": null, "manual_retry_allowed": null, "connector_transaction_id": "66177225", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "66177225", "payment_link": null, "profile_id": "pro_xiKo4uRjNEP5wLuam7Df", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_0iYQCYGnXC9WMGhRyb5O", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-27T13:41:45.316Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "109.71.40.0", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-27T13:27:27.022Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "request_extended_authorization": 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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 4. Refunds Create: cURL: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_St9F0EWAvKEY3O3Vz020jZDJSFETJGc5E1sB0gnr9MOFBUJdHbSZDBCPnAybRQdu' \ --data '{ "payment_id": "pay_rOaIbbJ3CsOgmil9s9IS", "amount": 2500, "reason": "RETURN", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ' ``` Response: ``` { "refund_id": "ref_xC1sQ292UR5lKLCc9qpL", "payment_id": "pay_rOaIbbJ3CsOgmil9s9IS", "amount": 2500, "currency": "AED", "status": "succeeded", "reason": "RETURN", "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-09-27T13:28:22.276Z", "updated_at": "2025-09-27T13:28:23.380Z", "connector": "tsys", "profile_id": "pro_xiKo4uRjNEP5wLuam7Df", "merchant_connector_id": "mca_0iYQCYGnXC9WMGhRyb5O", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` 5. RSync cURL: ``` curl --location 'http://localhost:8080/refunds/ref_xC1sQ292UR5lKLCc9qpL?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_St9F0EWAvKEY3O3Vz020jZDJSFETJGc5E1sB0gnr9MOFBUJdHbSZDBCPnAybRQdu' ``` Response: ``` { "refund_id": "ref_xC1sQ292UR5lKLCc9qpL", "payment_id": "pay_rOaIbbJ3CsOgmil9s9IS", "amount": 2500, "currency": "AED", "status": "succeeded", "reason": "RETURN", "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-09-27T13:28:22.276Z", "updated_at": "2025-09-27T13:29:38.380Z", "connector": "tsys", "profile_id": "pro_xiKo4uRjNEP5wLuam7Df", "merchant_connector_id": "mca_0iYQCYGnXC9WMGhRyb5O", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
e45bad38d602634c1bf9019978545f28ba19db23
juspay/hyperswitch
juspay__hyperswitch-9371
Bug: Add acknowledgement in adyen for incoming webhooks We need to send status 200 for incoming webhooks in adyen because of below issue: 1. Merchant has added two webhook endpoints in connector account for the two mca_ids in hyperswitch. This makes connector to send webhooks to both the endpoints and this causes webhook authentication failure for mca endpoint to which payment doesnt belongs. 2. This scenario makes the status of webhook endpoint as failing and connector stops sending webhook to this endpoint for a particular payment resource.
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 5004ef0624f..29366bfc88b 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -567,7 +567,7 @@ impl Connector { } pub fn should_acknowledge_webhook_for_resource_not_found_errors(self) -> bool { - matches!(self, Self::Adyenplatform) + matches!(self, Self::Adyenplatform | Self::Adyen) } /// Validates if dummy connector can be created diff --git a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs index 35636889d71..ec654971e41 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs @@ -49,6 +49,7 @@ pub struct AdyenTransferRequest { pub enum AdyenPayoutMethod { Bank, Card, + PlatformPayment, } #[derive(Debug, Serialize)] @@ -726,7 +727,7 @@ pub fn get_adyen_webhook_event( AdyenplatformWebhookStatus::Booked => match category { Some(AdyenPayoutMethod::Card) => webhooks::IncomingWebhookEvent::PayoutSuccess, Some(AdyenPayoutMethod::Bank) => webhooks::IncomingWebhookEvent::PayoutProcessing, - None => webhooks::IncomingWebhookEvent::PayoutProcessing, + _ => webhooks::IncomingWebhookEvent::PayoutProcessing, }, AdyenplatformWebhookStatus::Pending => webhooks::IncomingWebhookEvent::PayoutProcessing, AdyenplatformWebhookStatus::Failed => webhooks::IncomingWebhookEvent::PayoutFailure,
2025-09-15T04:32:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add acknowledgement in adyen for incoming webhooks by sending status 200. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create two profiles having same adyen account, both the profiles should return 200 to webhooks even if it doesnt belongs to them. here i made two profiles: ``` pro_JcW9GqodbWptCntfDiiJ : mca_kAzlkhIkGnErSSc3L6Xr pro_4vFskA1mTL8nf81s9Fzq : mca_4F3FOjPSWuvclkKoiG06 ``` Making below payments API: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_**' \ --data-raw '{ "amount": 700, "currency": "USD", "confirm": true, "customer_id":"StripeCustomer", "payment_link": false, "capture_on": "2029-09-10T10:11:12Z", "amount_to_capture": 700, "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "30", "card_cvc": "737" }, "billing": { "address": { "line1": "1467", "line2": "CA", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } } }, "payment_method": "card", "payment_method_type": "credit", "profile_id": "pro_JcW9GqodbWptCntfDiiJ", "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-GB", "screen_height": 720, "screen_width": 1280, "time_zone": -330, "ip_address": "208.127.127.193", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "order_details": [ { "product_name": "Tea", "quantity": 1, "amount": 110, "product_img_link": "https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg" }, { "product_name": "Tea", "quantity": 1, "amount": 110, "product_img_link": "https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg" }, { "product_name": "Tea", "quantity": 1, "amount": 110, "product_img_link": "https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg" } ] }' ``` Response: ``` {"payment_id":"pay_MGlcQq5UaVDvYSXAY6Xn","merchant_id":"merchant_1757925069","status":"succeeded","amount":700,"net_amount":700,"shipping_cost":null,"amount_capturable":0,"amount_received":700,"connector":"adyen","client_secret":"pay_MGlcQq5UaVDvYSXAY6Xn_secret_80ZstwkCzm9TyJVSzWLP","created":"2025-09-15T17:15:06.446Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","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":null,"off_session":null,"capture_on":null,"capture_method":null,"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":"30","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"CA","line3":null,"zip":"94122","state":"California","first_name":null,"last_name":null,"origin_zip":null},"phone":null,"email":null}},"payment_token":null,"shipping":null,"billing":null,"order_details":[{"sku":null,"upc":null,"brand":null,"amount":110,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Tea","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":"https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg","product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":null},{"sku":null,"upc":null,"brand":null,"amount":110,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Tea","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":"https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg","product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":null},{"sku":null,"upc":null,"brand":null,"amount":110,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Tea","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":"https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg","product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":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":"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":1757956506,"expires":1757960106,"secret":"epk_"},"manual_retry_allowed":false,"connector_transaction_id":"MW2KB77642TBJWT5","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_MGlcQq5UaVDvYSXAY6Xn_1","payment_link":null,"profile_id":"pro_JcW9GqodbWptCntfDiiJ","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_kAzlkhIkGnErSSc3L6Xr","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-15T17:30:06.446Z","fingerprint":null,"browser_info":{"language":"en-GB","time_zone":-330,"ip_address":"208.127.127.193","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0","color_depth":24,"java_enabled":true,"screen_width":1280,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":720,"java_script_enabled":true},"payment_channel":null,"payment_method_id":null,"network_transaction_id":"596288259500941","payment_method_status":null,"updated":"2025-09-15T17:15:07.684Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} ``` Refund: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_OvYaTu43QFXUxM2Xs1KHS7YkWRkkh5nXp7x2BENotNMBzwCWVA0Yeug0f12ofDsB' \ --data '{ "payment_id": "pay_MGlcQq5UaVDvYSXAY6Xn", "amount": 700, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` {"refund_id":"ref_aZfW2HjCEJKhRgsZguPr","payment_id":"pay_MGlcQq5UaVDvYSXAY6Xn","amount":700,"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-09-15T17:16:30.637Z","updated_at":"2025-09-15T17:16:31.861Z","connector":"adyen","profile_id":"pro_JcW9GqodbWptCntfDiiJ","merchant_connector_id":"mca_kAzlkhIkGnErSSc3L6Xr","split_refunds":null,"issuer_error_code":null,"issuer_error_message":null} ``` <img width="1888" height="127" alt="image" src="https://github.com/user-attachments/assets/562ef85f-f9c0-404e-b159-caa5ecfb06cb" /> <img width="1888" height="127" alt="image (1)" src="https://github.com/user-attachments/assets/de279cc0-5609-4e44-9396-98c3ab730b60" /> <img width="1888" height="127" alt="image (2)" src="https://github.com/user-attachments/assets/f3683d5e-c866-4fd7-9f9e-75c214f8267e" /> <img width="1888" height="127" alt="image" src="https://github.com/user-attachments/assets/c49f8495-f628-497e-baaa-e7c51957eb10" /> <img width="3456" height="2234" alt="image (6)" src="https://github.com/user-attachments/assets/5a0918e2-2cea-4bda-a135-63a637041079" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b69ed06959c9d9d2bb139465aa75e5d2a66b5a16
juspay/hyperswitch
juspay__hyperswitch-9391
Bug: [BUILD] Bump MSRV to 1.85 Superposition has dependencies on the `askama` crate, which now requires a minimum Rust version of 1.81. Our current setup is still on 1.80, so builds fail until we upgrade the toolchain.
diff --git a/.deepsource.toml b/.deepsource.toml index 8d0b3c501af..5db492d68c3 100644 --- a/.deepsource.toml +++ b/.deepsource.toml @@ -13,4 +13,4 @@ name = "rust" enabled = true [analyzers.meta] -msrv = "1.80.0" +msrv = "1.85.0" diff --git a/Cargo.toml b/Cargo.toml index acd8edf0b1c..9ab0490f014 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ resolver = "2" members = ["crates/*"] package.edition = "2021" -package.rust-version = "1.80.0" +package.rust-version = "1.85.0" package.license = "Apache-2.0" [workspace.dependencies] diff --git a/INSTALL_dependencies.sh b/INSTALL_dependencies.sh index bc7d502b357..8e21bf119b2 100755 --- a/INSTALL_dependencies.sh +++ b/INSTALL_dependencies.sh @@ -9,7 +9,7 @@ if [[ "${TRACE-0}" == "1" ]]; then set -o xtrace fi -RUST_MSRV="1.80.0" +RUST_MSRV="1.85.0" _DB_NAME="hyperswitch_db" _DB_USER="db_user" _DB_PASS="db_password" diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index f3bda521c5b..7fda0151445 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -26,7 +26,7 @@ pub async fn msearch_results( && req .filters .as_ref() - .map_or(true, |filters| filters.is_all_none()) + .is_none_or(|filters| filters.is_all_none()) { return Err(OpenSearchError::BadRequestError( "Both query and filters are empty".to_string(), @@ -232,7 +232,7 @@ pub async fn search_results( && search_req .filters .as_ref() - .map_or(true, |filters| filters.is_all_none()) + .is_none_or(|filters| filters.is_all_none()) { return Err(OpenSearchError::BadRequestError( "Both query and filters are empty".to_string(), diff --git a/crates/euclid/src/backend/vir_interpreter.rs b/crates/euclid/src/backend/vir_interpreter.rs index 7181e501fa7..67f59594bb0 100644 --- a/crates/euclid/src/backend/vir_interpreter.rs +++ b/crates/euclid/src/backend/vir_interpreter.rs @@ -42,7 +42,7 @@ where fn eval_statement(stmt: &vir::ValuedIfStatement, ctx: &types::Context) -> bool { if Self::eval_condition(&stmt.condition, ctx) { { - stmt.nested.as_ref().map_or(true, |nested_stmts| { + stmt.nested.as_ref().is_none_or(|nested_stmts| { nested_stmts.iter().any(|s| Self::eval_statement(s, ctx)) }) } diff --git a/crates/euclid/src/dssa/state_machine.rs b/crates/euclid/src/dssa/state_machine.rs index 93d394eece9..bce27ebc5f8 100644 --- a/crates/euclid/src/dssa/state_machine.rs +++ b/crates/euclid/src/dssa/state_machine.rs @@ -424,7 +424,7 @@ impl<'a> ProgramStateMachine<'a> { pub fn is_finished(&self) -> bool { self.current_rule_machine .as_ref() - .map_or(true, |rsm| rsm.is_finished()) + .is_none_or(|rsm| rsm.is_finished()) && self.rule_machines.is_empty() } @@ -449,7 +449,7 @@ impl<'a> ProgramStateMachine<'a> { if self .current_rule_machine .as_ref() - .map_or(true, |rsm| rsm.is_finished()) + .is_none_or(|rsm| rsm.is_finished()) { self.current_rule_machine = self.rule_machines.pop(); context.clear(); diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs index a4f49f1e843..5ba75893787 100644 --- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs @@ -392,14 +392,16 @@ impl FlattenedPaymentMethodsEnabled { let request_payment_methods_enabled = payment_method.payment_method_subtypes.unwrap_or_default(); let length = request_payment_methods_enabled.len(); - request_payment_methods_enabled.into_iter().zip( - std::iter::repeat(( - connector, - merchant_connector_id.clone(), - payment_method.payment_method_type, + request_payment_methods_enabled + .into_iter() + .zip(std::iter::repeat_n( + ( + connector, + merchant_connector_id.clone(), + payment_method.payment_method_type, + ), + length, )) - .take(length), - ) }) }, ) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 980e1e83432..322557129d4 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3988,9 +3988,8 @@ fn filter_installment_based( payment_method: &RequestPaymentMethodTypes, installment_payment_enabled: Option<bool>, ) -> bool { - installment_payment_enabled.map_or(true, |enabled| { - payment_method.installment_payment_enabled == Some(enabled) - }) + installment_payment_enabled + .is_none_or(|enabled| payment_method.installment_payment_enabled == Some(enabled)) } fn filter_pm_card_network_based( @@ -4016,16 +4015,14 @@ fn filter_pm_based_on_allowed_types( allowed_types: Option<&Vec<api_enums::PaymentMethodType>>, payment_method_type: api_enums::PaymentMethodType, ) -> bool { - allowed_types.map_or(true, |pm| pm.contains(&payment_method_type)) + allowed_types.is_none_or(|pm| pm.contains(&payment_method_type)) } fn filter_recurring_based( payment_method: &RequestPaymentMethodTypes, recurring_enabled: Option<bool>, ) -> bool { - recurring_enabled.map_or(true, |enabled| { - payment_method.recurring_enabled == Some(enabled) - }) + recurring_enabled.is_none_or(|enabled| payment_method.recurring_enabled == Some(enabled)) } #[cfg(feature = "v1")] diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index 61a8f71a1f3..36a8120fd18 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -547,9 +547,9 @@ fn filter_country_based( address: Option<&hyperswitch_domain_models::address::AddressDetails>, pm: &common_types::payment_methods::RequestPaymentMethodTypes, ) -> bool { - address.map_or(true, |address| { - address.country.as_ref().map_or(true, |country| { - pm.accepted_countries.as_ref().map_or(true, |ac| match ac { + address.is_none_or(|address| { + address.country.as_ref().is_none_or(|country| { + pm.accepted_countries.as_ref().is_none_or(|ac| match ac { common_types::payment_methods::AcceptedCountries::EnableOnly(acc) => { acc.contains(country) } @@ -568,7 +568,7 @@ fn filter_currency_based( currency: common_enums::Currency, pm: &common_types::payment_methods::RequestPaymentMethodTypes, ) -> bool { - pm.accepted_currencies.as_ref().map_or(true, |ac| match ac { + pm.accepted_currencies.as_ref().is_none_or(|ac| match ac { common_types::payment_methods::AcceptedCurrencies::EnableOnly(acc) => { acc.contains(&currency) } @@ -641,9 +641,7 @@ fn filter_recurring_based( payment_method: &common_types::payment_methods::RequestPaymentMethodTypes, recurring_enabled: Option<bool>, ) -> bool { - recurring_enabled.map_or(true, |enabled| { - payment_method.recurring_enabled == Some(enabled) - }) + recurring_enabled.is_none_or(|enabled| payment_method.recurring_enabled == Some(enabled)) } // filter based on valid amount range of payment method type @@ -704,7 +702,7 @@ fn filter_allowed_payment_method_types_based( allowed_types: Option<&Vec<api_models::enums::PaymentMethodType>>, payment_method_type: api_models::enums::PaymentMethodType, ) -> bool { - allowed_types.map_or(true, |pm| pm.contains(&payment_method_type)) + allowed_types.is_none_or(|pm| pm.contains(&payment_method_type)) } // filter based on card networks diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index e4ce038b3bd..5e0f0eb1b81 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -960,7 +960,7 @@ pub async fn perform_cgraph_filtering( .change_context(errors::RoutingError::KgraphAnalysisError)?; let filter_eligible = - eligible_connectors.map_or(true, |list| list.contains(&routable_connector)); + eligible_connectors.is_none_or(|list| list.contains(&routable_connector)); if cgraph_eligible && filter_eligible { final_selection.push(choice); diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index cbd49a14391..25388c13816 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -507,9 +507,9 @@ pub async fn list_roles_with_info( .into_iter() .filter_map(|role_info| { let is_lower_entity = user_role_entity >= role_info.get_entity_type(); - let request_filter = request.entity_type.map_or(true, |entity_type| { - entity_type == role_info.get_entity_type() - }); + let request_filter = request + .entity_type + .is_none_or(|entity_type| entity_type == role_info.get_entity_type()); (is_lower_entity && request_filter).then_some({ let permission_groups = role_info.get_permission_groups(); @@ -539,9 +539,9 @@ pub async fn list_roles_with_info( .into_iter() .filter_map(|role_info| { let is_lower_entity = user_role_entity >= role_info.get_entity_type(); - let request_filter = request.entity_type.map_or(true, |entity_type| { - entity_type == role_info.get_entity_type() - }); + let request_filter = request + .entity_type + .is_none_or(|entity_type| entity_type == role_info.get_entity_type()); (is_lower_entity && request_filter).then_some(role_api::RoleInfoResponseNew { role_id: role_info.get_role_id().to_string(), diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index b248955de4d..44322d4384d 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -2373,7 +2373,7 @@ async fn update_connector_mandate_details( .clone() .get_required_value("merchant_connector_id")?; - if mandate_details.payments.as_ref().map_or(true, |payments| { + if mandate_details.payments.as_ref().is_none_or(|payments| { !payments.0.contains_key(&merchant_connector_account_id) }) { // Update the payment attempt to maintain consistency across tables. diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs index 6ba8a72f5c6..02877131c99 100644 --- a/crates/router/src/db/dispute.rs +++ b/crates/router/src/db/dispute.rs @@ -263,38 +263,38 @@ impl DisputeInterface for MockDb { && dispute_constraints .dispute_id .as_ref() - .map_or(true, |id| &dispute.dispute_id == id) + .is_none_or(|id| &dispute.dispute_id == id) && dispute_constraints .payment_id .as_ref() - .map_or(true, |id| &dispute.payment_id == id) + .is_none_or(|id| &dispute.payment_id == id) && dispute_constraints .profile_id .as_ref() - .map_or(true, |profile_ids| { + .is_none_or(|profile_ids| { dispute .profile_id .as_ref() - .map_or(true, |id| profile_ids.contains(id)) + .is_none_or(|id| profile_ids.contains(id)) }) && dispute_constraints .dispute_status .as_ref() - .map_or(true, |statuses| statuses.contains(&dispute.dispute_status)) + .is_none_or(|statuses| statuses.contains(&dispute.dispute_status)) && dispute_constraints .dispute_stage .as_ref() - .map_or(true, |stages| stages.contains(&dispute.dispute_stage)) - && dispute_constraints.reason.as_ref().map_or(true, |reason| { + .is_none_or(|stages| stages.contains(&dispute.dispute_stage)) + && dispute_constraints.reason.as_ref().is_none_or(|reason| { dispute .connector_reason .as_ref() - .map_or(true, |d_reason| d_reason == reason) + .is_none_or(|d_reason| d_reason == reason) }) && dispute_constraints .connector .as_ref() - .map_or(true, |connectors| { + .is_none_or(|connectors| { connectors .iter() .any(|connector| dispute.connector.as_str() == *connector) @@ -302,13 +302,11 @@ impl DisputeInterface for MockDb { && dispute_constraints .merchant_connector_id .as_ref() - .map_or(true, |id| { - dispute.merchant_connector_id.as_ref() == Some(id) - }) + .is_none_or(|id| dispute.merchant_connector_id.as_ref() == Some(id)) && dispute_constraints .currency .as_ref() - .map_or(true, |currencies| { + .is_none_or(|currencies| { currencies.iter().any(|currency| { dispute .dispute_currency @@ -316,16 +314,13 @@ impl DisputeInterface for MockDb { .unwrap_or(dispute.currency.as_str() == currency.to_string()) }) }) - && dispute_constraints - .time_range - .as_ref() - .map_or(true, |range| { - let dispute_time = dispute.created_at; - dispute_time >= range.start_time - && range - .end_time - .map_or(true, |end_time| dispute_time <= end_time) - }) + && dispute_constraints.time_range.as_ref().is_none_or(|range| { + let dispute_time = dispute.created_at; + dispute_time >= range.start_time + && range + .end_time + .is_none_or(|end_time| dispute_time <= end_time) + }) }) .skip(offset_usize) .take(limit_usize) @@ -428,15 +423,13 @@ impl DisputeInterface for MockDb { && time_range .end_time .as_ref() - .map(|received_end_time| received_end_time >= &d.created_at) - .unwrap_or(true) + .is_none_or(|received_end_time| received_end_time >= &d.created_at) && profile_id_list .as_ref() .zip(d.profile_id.as_ref()) - .map(|(received_profile_list, received_profile_id)| { + .is_none_or(|(received_profile_list, received_profile_id)| { received_profile_list.contains(received_profile_id) }) - .unwrap_or(true) }) .cloned() .collect::<Vec<storage::Dispute>>(); diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 1896a8f8a92..6f181ba2011 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -1405,13 +1405,13 @@ impl RefundInterface for MockDb { refund_details .payment_id .clone() - .map_or(true, |id| id == refund.payment_id) + .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() - .map_or(true, |id| id == refund.refund_id) + .is_none_or(|id| id == refund.refund_id) }) .filter(|refund| { refund.profile_id.as_ref().is_some_and(|profile_id| { @@ -1432,15 +1432,11 @@ impl RefundInterface for MockDb { }) }) .filter(|refund| { - refund_details - .amount_filter - .as_ref() - .map_or(true, |amount| { - refund.refund_amount - >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) - && refund.refund_amount - <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) - }) + refund_details.amount_filter.as_ref().is_none_or(|amount| { + refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) + && refund.refund_amount + <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) + }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) @@ -1513,13 +1509,13 @@ impl RefundInterface for MockDb { refund_details .payment_id .clone() - .map_or(true, |id| id == refund.payment_id) + .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() - .map_or(true, |id| id == refund.id) + .is_none_or(|id| id == refund.id) }) .filter(|refund| { refund @@ -1541,15 +1537,11 @@ impl RefundInterface for MockDb { }) }) .filter(|refund| { - refund_details - .amount_filter - .as_ref() - .map_or(true, |amount| { - refund.refund_amount - >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) - && refund.refund_amount - <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) - }) + refund_details.amount_filter.as_ref().is_none_or(|amount| { + refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) + && refund.refund_amount + <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) + }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) @@ -1720,13 +1712,13 @@ impl RefundInterface for MockDb { refund_details .payment_id .clone() - .map_or(true, |id| id == refund.payment_id) + .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() - .map_or(true, |id| id == refund.refund_id) + .is_none_or(|id| id == refund.refund_id) }) .filter(|refund| { refund.profile_id.as_ref().is_some_and(|profile_id| { @@ -1747,15 +1739,11 @@ impl RefundInterface for MockDb { }) }) .filter(|refund| { - refund_details - .amount_filter - .as_ref() - .map_or(true, |amount| { - refund.refund_amount - >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) - && refund.refund_amount - <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) - }) + refund_details.amount_filter.as_ref().is_none_or(|amount| { + refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) + && refund.refund_amount + <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) + }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) @@ -1826,13 +1814,13 @@ impl RefundInterface for MockDb { refund_details .payment_id .clone() - .map_or(true, |id| id == refund.payment_id) + .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() - .map_or(true, |id| id == refund.id) + .is_none_or(|id| id == refund.id) }) .filter(|refund| { refund @@ -1854,15 +1842,11 @@ impl RefundInterface for MockDb { }) }) .filter(|refund| { - refund_details - .amount_filter - .as_ref() - .map_or(true, |amount| { - refund.refund_amount - >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) - && refund.refund_amount - <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) - }) + refund_details.amount_filter.as_ref().is_none_or(|amount| { + refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) + && refund.refund_amount + <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) + }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 67ed2127eab..7b5bd81678a 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -495,7 +495,7 @@ pub async fn fetch_user_roles_by_payload( .filter_map(|user_role| { let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?; request_entity_type - .map_or(true, |req_entity_type| entity_type == req_entity_type) + .is_none_or(|req_entity_type| entity_type == req_entity_type) .then_some(user_role) }) .collect::<HashSet<_>>()) diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rs index 9cfc683a3bf..fd611911d63 100644 --- a/crates/storage_impl/src/utils.rs +++ b/crates/storage_impl/src/utils.rs @@ -115,7 +115,7 @@ where let limit_satisfies = |len: usize, limit: i64| { TryInto::try_into(limit) .ok() - .map_or(true, |val: usize| len >= val) + .is_none_or(|val: usize| len >= val) }; let redis_output = redis_fut.await;
2025-09-15T15:02:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR bumps the Minimum Supported Rust Version (MSRV) from Rust 1.80 to 1.85. Clippy Warning Fixes: 1. Replace repeat().take() with repeat_n() - More concise iterator creation 2. Replace map_or(true, ...) with is_none_or(...) - Modern idiomatic Option handling ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Superposition has dependencies on the `askama` crate, which now requires a minimum Rust version of 1.81. Our current setup is still on 1.80. Bumping up the MSRV to 1.85 should solve this issue. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> N/A ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
ee12d44c5f13d0612dde3b6b24a412f6ddd870c8
juspay/hyperswitch
juspay__hyperswitch-9350
Bug: [FIX] : fix wasm Fix type account_id for ConfigMetadata
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 18da6b52498..cd4bdfcc239 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -149,7 +149,7 @@ pub struct ConfigMetadata { pub proxy_url: Option<InputData>, pub shop_name: Option<InputData>, pub merchant_funding_source: Option<InputData>, - pub account_id: Option<String>, + pub account_id: Option<InputData>, } #[serde_with::skip_serializing_none]
2025-09-10T10:39:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Fix type account_id for ConfigMetadata ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <img width="2254" height="416" alt="Screenshot 2025-09-10 at 4 55 21 PM" src="https://github.com/user-attachments/assets/d153477c-fd22-4f96-aff6-0340bbfc1c29" /> <img width="2384" height="992" alt="Screenshot 2025-09-10 at 4 55 57 PM" src="https://github.com/user-attachments/assets/4c07b386-cfb9-45df-b19c-0f9b1b56c395" /> <img width="2394" height="798" alt="Screenshot 2025-09-10 at 4 56 04 PM" src="https://github.com/user-attachments/assets/64005966-147d-461d-8d3f-289d961cf260" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
5ab8a27c10786885b91b79fbb9fb8b5e990029e1
juspay/hyperswitch
juspay__hyperswitch-9342
Bug: [REFACTOR] Update URL's in welcome email There is an issue with URL's in the welcome email. - Slack invite link - Expired - Quarterly roadmap link - pointing to old quarter.
diff --git a/crates/router/src/services/email/assets/welcome_to_community.html b/crates/router/src/services/email/assets/welcome_to_community.html index bb6c67a2624..f7e9b15b332 100644 --- a/crates/router/src/services/email/assets/welcome_to_community.html +++ b/crates/router/src/services/email/assets/welcome_to_community.html @@ -46,9 +46,9 @@ >. </p> <p> - We’ve got an exciting Q2 roadmap ahead — check it out here: - <a href="https://docs.hyperswitch.io/about-hyperswitch/roadmap-q2-2025" - >Roadmap Q2 2025</a + We’ve got an exciting roadmap ahead — check it out here: + <a href="https://docs.hyperswitch.io/about-hyperswitch/roadmap" + >Our quarterly roadmap</a >. </p> <p> @@ -58,7 +58,7 @@ > or our <a - href="https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw" + href="https://inviter.co/hyperswitch-slack" >Slack Community</a >. </p>
2025-09-10T09:37:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Updated quarterly roadmap and slack invite URL's in `welcome_to_community.html` file which is sent as the email body whenever a user signs up. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
7355a83ef9316a6cc7f9fa0c9c9aec7397e9fc4b
juspay/hyperswitch
juspay__hyperswitch-9338
Bug: handle force decline for no 3ds requests in adyen We need to start sending execute_three_d as false in adyen no3ds payments request to skip 3ds auth.
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 7494f452646..dee0efbf0b6 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -1887,29 +1887,19 @@ fn get_additional_data(item: &PaymentsAuthorizeRouterData) -> Option<AdditionalD let execute_three_d = if matches!(item.auth_type, storage_enums::AuthenticationType::ThreeDs) { Some("true".to_string()) } else { - None + Some("false".to_string()) }; - if authorisation_type.is_none() - && manual_capture.is_none() - && execute_three_d.is_none() - && riskdata.is_none() - { - //without this if-condition when the above 3 values are None, additionalData will be serialized to JSON like this -> additionalData: {} - //returning None, ensures that additionalData key will not be present in the serialized JSON - None - } else { - Some(AdditionalData { - authorisation_type, - manual_capture, - execute_three_d, - network_tx_reference: None, - recurring_detail_reference: None, - recurring_shopper_reference: None, - recurring_processing_model: None, - riskdata, - ..AdditionalData::default() - }) - } + Some(AdditionalData { + authorisation_type, + manual_capture, + execute_three_d, + network_tx_reference: None, + recurring_detail_reference: None, + recurring_shopper_reference: None, + recurring_processing_model: None, + riskdata, + ..AdditionalData::default() + }) } fn get_channel_type(pm_type: Option<storage_enums::PaymentMethodType>) -> Option<Channel> {
2025-09-10T08:33:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We need to start sending execute_three_d as false in adyen no3ds payments request to skip 3ds auth at adyen ends. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_**' \ --data-raw '{ "amount": 600, "currency": "USD", "connector": [ "adyen" ], "customer_id": "cus_CDei4NEhboFFubgAxsy8", "profile_id": "pro_kl4dSq0FXRc2PC6oZYic", "confirm": true, "payment_link": false, "capture_method": "automatic", "capture_on": "2029-09-10T10:11:12Z", "amount_to_capture": 600, "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method_data": { "card": { "card_number": "3714 4963 5398 431", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "7373" }, "billing": { "address": { "line1": "1467", "line2": "CA", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } } }, "payment_method": "card", "payment_method_type": "credit", "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-GB", "screen_height": 720, "screen_width": 1280, "time_zone": -330, "ip_address": "208.127.127.193", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "order_details": [ { "product_name": "Tea", "quantity": 1, "amount": 110, "product_img_link": "https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg" }, { "product_name": "Tea", "quantity": 1, "amount": 110, "product_img_link": "https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg" }, { "product_name": "Tea", "quantity": 1, "amount": 110, "product_img_link": "https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg" } ] }' ``` Response: ``` {"payment_id":"pay_i1WPa87SrXPwwNVQmvWi","merchant_id":"merchant_1757416130","status":"succeeded","amount":600,"net_amount":600,"shipping_cost":null,"amount_capturable":0,"amount_received":600,"connector":"adyen","client_secret":"pay_1","created":"2025-09-09T13:40:59.979Z","currency":"USD","customer_id":"cus_CDei4NEhboFFubgAxsy8","customer":{"id":"cus_CDei4NEhboFFubgAxsy8","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":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"8431","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"371449","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"CA","line3":null,"zip":"94122","state":"California","first_name":null,"last_name":null,"origin_zip":null},"phone":null,"email":null}},"payment_token":null,"shipping":null,"billing":null,"order_details":[{"sku":null,"upc":null,"brand":null,"amount":110,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Tea","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":"https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg","product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":null},{"sku":null,"upc":null,"brand":null,"amount":110,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Tea","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":"https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg","product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":null},{"sku":null,"upc":null,"brand":null,"amount":110,"category":null,"quantity":1,"tax_rate":null,"product_id":null,"description":null,"product_name":"Tea","product_type":null,"sub_category":null,"total_amount":null,"commodity_code":null,"unit_of_measure":null,"product_img_link":"https://thumbs.dreamstime.com/b/indian-tea-spices-masala-chai-33827904.jpg","product_tax_code":null,"total_tax_amount":null,"requires_shipping":null,"unit_discount_amount":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":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_CDei4NEhboFFubgAxsy8","created_at":1757425259,"expires":1757428859,"secret":"epk_c68ada5037fa41c2baf2979129cafaad"},"manual_retry_allowed":false,"connector_transaction_id":"GRVGDV9XKZZBDR75","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_i1WPa87SrXPwwNVQmvWi_1","payment_link":null,"profile_id":"pro_kl4dSq0FXRc2PC6oZYic","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_SWDhbvMuWt3v5vlL6MNT","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-09T13:55:59.979Z","fingerprint":null,"browser_info":{"language":"en-GB","time_zone":-330,"ip_address":"208.127.127.193","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0","color_depth":24,"java_enabled":true,"screen_width":1280,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":720,"java_script_enabled":true},"payment_channel":null,"payment_method_id":null,"network_transaction_id":"439956500571320","payment_method_status":null,"updated":"2025-09-09T13:41:03.043Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null} ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
juspay/hyperswitch
juspay__hyperswitch-9362
Bug: [FEATURE] Add Peachpayments Template Code ### Feature Description Add Peachpayments Template Code ### Possible Implementation Add Peachpayments Template Code ### 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 4ce52dfac4f..29649b13c03 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -280,6 +280,7 @@ paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +peachpayments.base_url = "https://apitest.bankint.ppay.io/v/1" phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index c756b0a9e9c..3d61dde7119 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -117,6 +117,7 @@ paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +peachpayments.base_url = "https://apitest.bankint.ppay.io/v/1" phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index f685bbe2787..fb135ef1214 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -121,6 +121,7 @@ paysafe.base_url = "https://api.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.payu.com/api/" +peachpayments.base_url = "https://api.bankint.peachpayments.com" phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://checkout.placetopay.com/rest/gateway" plaid.base_url = "https://production.plaid.com" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 9ed89a01c9b..fec6773d44c 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -121,6 +121,7 @@ paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +peachpayments.base_url = "https://apitest.bankint.ppay.io/v/1" phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/config/development.toml b/config/development.toml index 07cadbf3058..411263f9b17 100644 --- a/config/development.toml +++ b/config/development.toml @@ -318,6 +318,7 @@ paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +peachpayments.base_url = "https://apitest.bankint.ppay.io/v/1" phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index d299323f2c1..025fd916c99 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -206,6 +206,7 @@ paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +peachpayments.base_url = "https://apitest.bankint.ppay.io/v/1" phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 5004ef0624f..5051b035679 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -136,6 +136,7 @@ pub enum RoutableConnectors { Paystack, Paytm, Payu, + // Peachpayments, Phonepe, Placetopay, Powertranz, @@ -313,6 +314,7 @@ pub enum Connector { Paystack, Paytm, Payu, + // Peachpayments, Phonepe, Placetopay, Powertranz, @@ -501,6 +503,7 @@ impl Connector { | Self::Paysafe | Self::Paystack | Self::Payu + // | Self::Peachpayments | Self::Placetopay | Self::Powertranz | Self::Prophetpay @@ -680,6 +683,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Paysafe => Self::Paysafe, RoutableConnectors::Paystack => Self::Paystack, RoutableConnectors::Payu => Self::Payu, + // RoutableConnectors::Peachpayments => Self::Peachpayments, RoutableConnectors::Placetopay => Self::Placetopay, RoutableConnectors::Powertranz => Self::Powertranz, RoutableConnectors::Prophetpay => Self::Prophetpay, @@ -814,6 +818,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Paysafe => Ok(Self::Paysafe), Connector::Paystack => Ok(Self::Paystack), Connector::Payu => Ok(Self::Payu), + // Connector::Peachpayments => Ok(Self::Peachpayments), Connector::Placetopay => Ok(Self::Placetopay), Connector::Powertranz => Ok(Self::Powertranz), Connector::Prophetpay => Ok(Self::Prophetpay), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index cd4bdfcc239..060240873f5 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -281,6 +281,7 @@ pub struct ConnectorConfig { pub paystack: Option<ConnectorTomlConfig>, pub paytm: Option<ConnectorTomlConfig>, pub payu: Option<ConnectorTomlConfig>, + pub peachpayments: Option<ConnectorTomlConfig>, pub phonepe: Option<ConnectorTomlConfig>, pub placetopay: Option<ConnectorTomlConfig>, pub plaid: Option<ConnectorTomlConfig>, @@ -485,6 +486,7 @@ impl ConnectorConfig { Connector::Paysafe => Ok(connector_data.paysafe), Connector::Paystack => Ok(connector_data.paystack), Connector::Payu => Ok(connector_data.payu), + // Connector::Peachpayments => Ok(connector_data.peachpayments), Connector::Placetopay => Ok(connector_data.placetopay), Connector::Plaid => Ok(connector_data.plaid), Connector::Powertranz => Ok(connector_data.powertranz), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 248a1336051..8b6b0e875fb 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6839,3 +6839,7 @@ label="Payment Method Account ID" placeholder="Enter Account ID" required=true type="Text" + +[peachpayments] +[peachpayments.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 0bcd12a1133..7501bb4c33d 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5508,3 +5508,7 @@ label="Payment Method Account ID" placeholder="Enter Account ID" required=true type="Text" + +[peachpayments] +[peachpayments.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index a50f4b638e2..8220f4f2eae 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6822,3 +6822,7 @@ label="Payment Method Account ID" placeholder="Enter Account ID" required=true type="Text" + +[peachpayments] +[peachpayments.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 60d6866beea..bf3fab9335a 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -87,6 +87,7 @@ pub mod paysafe; pub mod paystack; pub mod paytm; pub mod payu; +pub mod peachpayments; pub mod phonepe; pub mod placetopay; pub mod plaid; @@ -150,12 +151,12 @@ pub use self::{ noon::Noon, nordea::Nordea, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payload::Payload, payme::Payme, payone::Payone, paypal::Paypal, paysafe::Paysafe, paystack::Paystack, paytm::Paytm, payu::Payu, - phonepe::Phonepe, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, - prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, - riskified::Riskified, santander::Santander, shift4::Shift4, sift::Sift, signifyd::Signifyd, - silverflow::Silverflow, square::Square, stax::Stax, stripe::Stripe, - stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, thunes::Thunes, - tokenio::Tokenio, trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, + peachpayments::Peachpayments, phonepe::Phonepe, placetopay::Placetopay, plaid::Plaid, + powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, + recurly::Recurly, redsys::Redsys, riskified::Riskified, santander::Santander, shift4::Shift4, + sift::Sift, signifyd::Signifyd, silverflow::Silverflow, square::Square, stax::Stax, + stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, + thunes::Thunes, tokenio::Tokenio, trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, worldpay::Worldpay, worldpayvantiv::Worldpayvantiv, worldpayxml::Worldpayxml, xendit::Xendit, diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments.rs new file mode 100644 index 00000000000..3c258893320 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/peachpayments.rs @@ -0,0 +1,630 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::enums; +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 peachpayments; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Peachpayments { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Peachpayments { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} + +impl api::Payment for Peachpayments {} +impl api::PaymentSession for Peachpayments {} +impl api::ConnectorAccessToken for Peachpayments {} +impl api::MandateSetup for Peachpayments {} +impl api::PaymentAuthorize for Peachpayments {} +impl api::PaymentSync for Peachpayments {} +impl api::PaymentCapture for Peachpayments {} +impl api::PaymentVoid for Peachpayments {} +impl api::Refund for Peachpayments {} +impl api::RefundExecute for Peachpayments {} +impl api::RefundSync for Peachpayments {} +impl api::PaymentToken for Peachpayments {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Peachpayments +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Peachpayments +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 Peachpayments { + fn id(&self) -> &'static str { + "peachpayments" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + // PeachPayments Card Gateway accepts amounts in cents (minor unit) + api::CurrencyUnit::Minor + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.peachpayments.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = peachpayments::PeachpaymentsAuthType::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: peachpayments::PeachpaymentsErrorResponse = res + .response + .parse_struct("PeachpaymentsErrorResponse") + .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, + connector_metadata: None, + }) + } +} + +impl ConnectorValidation for Peachpayments { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Peachpayments { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Peachpayments {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Peachpayments +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> + for Peachpayments +{ + 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 = peachpayments::PeachpaymentsRouterData::from((amount, req)); + let connector_req = + peachpayments::PeachpaymentsPaymentsRequest::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: peachpayments::PeachpaymentsPaymentsResponse = res + .response + .parse_struct("Peachpayments 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 Peachpayments { + 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: peachpayments::PeachpaymentsPaymentsResponse = res + .response + .parse_struct("peachpayments 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 Peachpayments { + 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: peachpayments::PeachpaymentsPaymentsResponse = res + .response + .parse_struct("Peachpayments 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 Peachpayments {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpayments { + 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 = + peachpayments::PeachpaymentsRouterData::from((refund_amount, req)); + let connector_req = + peachpayments::PeachpaymentsRefundRequest::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: peachpayments::RefundResponse = res + .response + .parse_struct("peachpayments 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 Peachpayments { + 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: peachpayments::RefundResponse = res + .response + .parse_struct("peachpayments 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 Peachpayments { + 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)) + } +} + +static PEACHPAYMENTS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static PEACHPAYMENTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Peachpayments", + description: "Peachpayments connector", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Beta, +}; + +static PEACHPAYMENTS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Peachpayments { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PEACHPAYMENTS_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PEACHPAYMENTS_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PEACHPAYMENTS_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs new file mode 100644 index 00000000000..1d403f26321 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs @@ -0,0 +1,223 @@ +use common_enums::enums; +use common_utils::types::MinorUnit; +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}; + +//TODO: Fill the struct with respective fields +pub struct PeachpaymentsRouterData<T> { + pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(MinorUnit, T)> for PeachpaymentsRouterData<T> { + fn from((amount, item): (MinorUnit, 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 PeachpaymentsPaymentsRequest { + amount: MinorUnit, + card: PeachpaymentsCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PeachpaymentsCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>> + for PeachpaymentsPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct PeachpaymentsAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for PeachpaymentsAuthType { + 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, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PeachpaymentsPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<PeachpaymentsPaymentStatus> for common_enums::AttemptStatus { + fn from(item: PeachpaymentsPaymentStatus) -> Self { + match item { + PeachpaymentsPaymentStatus::Succeeded => Self::Charged, + PeachpaymentsPaymentStatus::Failed => Self::Failure, + PeachpaymentsPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PeachpaymentsPaymentsResponse { + status: PeachpaymentsPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, PeachpaymentsPaymentsResponse, 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 PeachpaymentsRefundRequest { + pub amount: MinorUnit, +} + +impl<F> TryFrom<&PeachpaymentsRouterData<&RefundsRouterData<F>>> for PeachpaymentsRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PeachpaymentsRouterData<&RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 PeachpaymentsErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 2d366f3f99e..de8cc894367 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -232,6 +232,7 @@ default_imp_for_authorize_session_token!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -379,6 +380,7 @@ default_imp_for_calculate_tax!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -527,6 +529,7 @@ default_imp_for_session_update!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -669,6 +672,7 @@ default_imp_for_post_session_tokens!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -810,6 +814,7 @@ default_imp_for_create_order!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -950,6 +955,7 @@ default_imp_for_update_metadata!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1092,6 +1098,7 @@ default_imp_for_cancel_post_capture!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1214,6 +1221,7 @@ default_imp_for_complete_authorize!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1344,6 +1352,7 @@ default_imp_for_incremental_authorization!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1486,6 +1495,7 @@ default_imp_for_create_customer!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1613,6 +1623,7 @@ default_imp_for_connector_redirect_response!( connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1735,6 +1746,7 @@ default_imp_for_pre_processing_steps!( connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1873,6 +1885,7 @@ default_imp_for_post_processing_steps!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Powertranz, @@ -2016,6 +2029,7 @@ default_imp_for_approve!( connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2160,6 +2174,7 @@ default_imp_for_reject!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2303,6 +2318,7 @@ default_imp_for_webhook_source_verification!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2446,6 +2462,7 @@ default_imp_for_accept_dispute!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2587,6 +2604,7 @@ default_imp_for_submit_evidence!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2727,6 +2745,7 @@ default_imp_for_defend_dispute!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2870,6 +2889,7 @@ default_imp_for_fetch_disputes!( connectors::Paysafe, connectors::Paystack, connectors::Payu, + connectors::Peachpayments, connectors::Paytm, connectors::Phonepe, connectors::Placetopay, @@ -3013,6 +3033,7 @@ default_imp_for_dispute_sync!( connectors::Paysafe, connectors::Paystack, connectors::Payu, + connectors::Peachpayments, connectors::Paytm, connectors::Phonepe, connectors::Placetopay, @@ -3164,6 +3185,7 @@ default_imp_for_file_upload!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3297,6 +3319,7 @@ default_imp_for_payouts!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3431,6 +3454,7 @@ default_imp_for_payouts_create!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3572,6 +3596,7 @@ default_imp_for_payouts_retrieve!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Payone, connectors::Placetopay, @@ -3715,6 +3740,7 @@ default_imp_for_payouts_eligibility!( connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3853,6 +3879,7 @@ default_imp_for_payouts_fulfill!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3994,6 +4021,7 @@ default_imp_for_payouts_cancel!( connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4136,6 +4164,7 @@ default_imp_for_payouts_quote!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4279,6 +4308,7 @@ default_imp_for_payouts_recipient!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4422,6 +4452,7 @@ default_imp_for_payouts_recipient_account!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4567,6 +4598,7 @@ default_imp_for_frm_sale!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4711,6 +4743,7 @@ default_imp_for_frm_checkout!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4855,6 +4888,7 @@ default_imp_for_frm_transaction!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4999,6 +5033,7 @@ default_imp_for_frm_fulfillment!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -5143,6 +5178,7 @@ default_imp_for_frm_record_return!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -5281,6 +5317,7 @@ default_imp_for_revoking_mandates!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -5422,6 +5459,7 @@ default_imp_for_uas_pre_authentication!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, @@ -5563,6 +5601,7 @@ default_imp_for_uas_post_authentication!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, @@ -5703,6 +5742,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, @@ -5834,6 +5874,7 @@ default_imp_for_connector_request_id!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Payme, connectors::Payone, @@ -5973,6 +6014,7 @@ default_imp_for_fraud_check!( connectors::Paypal, connectors::Paysafe, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, @@ -6136,6 +6178,7 @@ default_imp_for_connector_authentication!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Payone, connectors::Powertranz, @@ -6275,6 +6318,7 @@ default_imp_for_uas_authentication!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, @@ -6411,6 +6455,7 @@ default_imp_for_revenue_recovery!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -6556,6 +6601,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -6699,6 +6745,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -6842,6 +6889,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -6979,6 +7027,7 @@ default_imp_for_external_vault!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -7122,6 +7171,7 @@ default_imp_for_external_vault_insert!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -7265,6 +7315,7 @@ default_imp_for_external_vault_retrieve!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -7408,6 +7459,7 @@ default_imp_for_external_vault_delete!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -7551,6 +7603,7 @@ default_imp_for_external_vault_create!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -7695,6 +7748,7 @@ default_imp_for_connector_authentication_token!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, @@ -7846,6 +7900,7 @@ default_imp_for_external_vault_proxy_payments_create!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index f175c52e93f..836ad796a05 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -342,6 +342,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -486,6 +487,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -621,6 +623,7 @@ default_imp_for_new_connector_integration_connector_authentication_token!( connectors::Paysafe, connectors::Paystack, connectors::Payu, + connectors::Peachpayments, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -757,6 +760,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -901,6 +905,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1050,6 +1055,7 @@ default_imp_for_new_connector_integration_fetch_disputes!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Plaid, connectors::Placetopay, @@ -1195,6 +1201,7 @@ default_imp_for_new_connector_integration_dispute_sync!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Plaid, connectors::Placetopay, @@ -1335,6 +1342,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1477,6 +1485,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Paysafe, connectors::Paystack, connectors::Payu, + connectors::Peachpayments, connectors::Paytm, connectors::Placetopay, connectors::Plaid, @@ -1632,6 +1641,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1778,6 +1788,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -1924,6 +1935,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2070,6 +2082,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2216,6 +2229,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2362,6 +2376,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2508,6 +2523,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2654,6 +2670,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2800,6 +2817,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -2944,6 +2962,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3090,6 +3109,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3236,6 +3256,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3382,6 +3403,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3528,6 +3550,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3674,6 +3697,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3816,6 +3840,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3934,6 +3959,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Payeezy, connectors::Payload, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4075,6 +4101,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Payeezy, connectors::Payload, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4209,6 +4236,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Payeezy, connectors::Payload, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -4371,6 +4399,7 @@ default_imp_for_new_connector_integration_external_vault!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Powertranz, @@ -4519,6 +4548,7 @@ default_imp_for_new_connector_integration_external_vault_proxy!( connectors::Paystack, connectors::Paytm, connectors::Payu, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rs index d6b62a5eb45..a9f5929c5fc 100644 --- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs +++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs @@ -102,6 +102,7 @@ pub struct Connectors { pub paystack: ConnectorParams, pub paytm: ConnectorParams, pub payu: ConnectorParams, + pub peachpayments: ConnectorParams, pub phonepe: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index a8e859cc5b3..45d7ad513d8 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -32,19 +32,20 @@ pub use hyperswitch_connectors::connectors::{ nordea, nordea::Nordea, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payload, payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paysafe, - paysafe::Paysafe, paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, phonepe, - phonepe::Phonepe, placetopay, placetopay::Placetopay, plaid, plaid::Plaid, powertranz, - powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, - razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, riskified, - riskified::Riskified, santander, santander::Santander, shift4, shift4::Shift4, sift, - sift::Sift, signifyd, signifyd::Signifyd, silverflow, silverflow::Silverflow, square, - square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, - stripebilling::Stripebilling, taxjar, taxjar::Taxjar, threedsecureio, - threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenio, tokenio::Tokenio, trustpay, - trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, tsys, tsys::Tsys, - unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, - vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, - wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, - worldpay, worldpay::Worldpay, worldpayvantiv, worldpayvantiv::Worldpayvantiv, worldpayxml, - worldpayxml::Worldpayxml, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, + paysafe::Paysafe, paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, + peachpayments, peachpayments::Peachpayments, phonepe, phonepe::Phonepe, placetopay, + placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, + prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, + recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, santander, + santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, + silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, + stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, + threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenio, + tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, + tsys, tsys::Tsys, unified_authentication_service, + unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, + wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, + wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, + worldpayvantiv::Worldpayvantiv, worldpayxml, worldpayxml::Worldpayxml, xendit, xendit::Xendit, + zen, zen::Zen, zsl, zsl::Zsl, }; diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index 77e51e63f38..c6271341d66 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -415,6 +415,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { payu::transformers::PayuAuthType::try_from(self.auth_type)?; Ok(()) } + // api_enums::Connector::Peachpayments => { + // peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?; + // Ok(()) + // } api_enums::Connector::Placetopay => { placetopay::transformers::PlacetopayAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index 0e809c628f1..28300ecbf21 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -352,6 +352,9 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Payone::new()))) } enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))), + // enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new( + // hyperswitch_connectors::connectors::Peachpayments::new(), + // ))), enums::Connector::Placetopay => { Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new()))) } diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index 98e00bc893d..d82c1968b02 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -274,6 +274,9 @@ impl FeatureMatrixConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Payone::new()))) } enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))), + // enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new( + // connector::Peachpayments::new(), + // ))), enums::Connector::Placetopay => { Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new()))) } diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index fb43e8b1360..683ba603733 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -113,6 +113,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Paysafe => Self::Paysafe, api_enums::Connector::Paystack => Self::Paystack, api_enums::Connector::Payu => Self::Payu, + // api_enums::Connector::Peachpayments => Self::Peachpayments, api_models::enums::Connector::Placetopay => Self::Placetopay, api_enums::Connector::Plaid => Self::Plaid, api_enums::Connector::Powertranz => Self::Powertranz, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 87434a0e6dd..d03e5e18afb 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -91,6 +91,7 @@ mod paysafe; mod paystack; mod paytm; mod payu; +mod peachpayments; mod phonepe; mod placetopay; mod plaid; diff --git a/crates/router/tests/connectors/peachpayments.rs b/crates/router/tests/connectors/peachpayments.rs new file mode 100644 index 00000000000..f7da85872af --- /dev/null +++ b/crates/router/tests/connectors/peachpayments.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 PeachpaymentsTest; +impl ConnectorActions for PeachpaymentsTest {} +impl utils::Connector for PeachpaymentsTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Peachpayments; + utils::construct_connector_data_old( + Box::new(Peachpayments::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .peachpayments + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "peachpayments".to_string() + } +} + +static CONNECTOR: PeachpaymentsTest = PeachpaymentsTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 5faf7bbafb5..5b79c5ef2e7 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -366,3 +366,7 @@ api_key="API Key" [bluecode] api_key="EOrder Token" + +[peachpayments] +api_key="API Key" +key1="Tenant ID" \ No newline at end of file diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index f6deae24e20..6793f54a8de 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -98,6 +98,7 @@ pub struct ConnectorAuthentication { pub paystack: Option<HeaderKey>, pub paytm: Option<HeaderKey>, pub payu: Option<BodyKey>, + pub peachpayments: Option<HeaderKey>, pub phonepe: Option<HeaderKey>, pub placetopay: Option<BodyKey>, pub plaid: Option<BodyKey>, diff --git a/crates/test_utils/tests/sample_auth.toml b/crates/test_utils/tests/sample_auth.toml index c7ec4f12c54..c11c637ece3 100644 --- a/crates/test_utils/tests/sample_auth.toml +++ b/crates/test_utils/tests/sample_auth.toml @@ -168,4 +168,8 @@ api_key="API Key" [boku] api_key="API Key" -key1 = "transaction key" \ No newline at end of file +key1 = "transaction key" + +[peachpayments] +api_key="API Key" +key1="Tenant ID" \ No newline at end of file diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 7508208069d..9075da96e6e 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -173,6 +173,7 @@ paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +peachpayments.base_url = "https://apitest.bankint.ppay.io/v/1" phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 6f041b8fa01..b42835e091c 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 affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu peachpayments phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
2025-09-11T13:26:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9362) ## Description <!-- Describe your changes in detail --> Added Peachpayments Template Code ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
cadfcf7c22bfd1124f19e2f1cc1c98c3d152be99
juspay/hyperswitch
juspay__hyperswitch-9359
Bug: [FEATURE] Introduce ApplePay to Paysafe Both Encrypt and Decrypt flows
diff --git a/config/config.example.toml b/config/config.example.toml index bae0da78fbb..61a53ee0fd4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -946,6 +946,9 @@ credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +[pm_filters.paysafe] +apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } + [connector_customer] connector_list = "authorizedotnet,dwolla,facilitapay,gocardless,hyperswitch_vault,stax,stripe" payout_connector_list = "nomupay,stripe,wise" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index f1addc2b581..1a1f9682074 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -818,6 +818,9 @@ giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN, ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +[pm_filters.paysafe] +apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } + [pm_filters.datatrans] credit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } debit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 3fd609dd9b7..35b3052d5bc 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -828,6 +828,9 @@ credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +[pm_filters.paysafe] +apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } + [payout_method_filters.adyenplatform] sepa = { country = "AT,BE,CH,CZ,DE,EE,ES,FI,FR,GB,HU,IE,IT,LT,LV,NL,NO,PL,PT,SE,SK", currency = "EUR,CZK,DKK,HUF,NOK,PLN,SEK,GBP,CHF" } credit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT,LU,LV,MT,NL,NO,PL,PT,RO,SE,SI,SK,US", currency = "EUR,USD,GBP" } @@ -870,7 +873,7 @@ dwolla = { long_lived_token = true, payment_method = "bank_debit" } outgoing_enabled = true redis_lock_expiry_seconds = 180 -[l2_l3_data_config] +[l2_l3_data_config] enabled = "false" [webhook_source_verification_call] @@ -907,4 +910,3 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call - diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 44238899b50..50c49a05cac 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -840,6 +840,9 @@ credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +[pm_filters.paysafe] +apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } + [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } diff --git a/config/development.toml b/config/development.toml index e145d1eb087..f570a4046fc 100644 --- a/config/development.toml +++ b/config/development.toml @@ -988,6 +988,9 @@ credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +[pm_filters.paysafe] +apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } + [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c36904d5fe8..55e6d194aed 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -971,6 +971,9 @@ credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +[pm_filters.paysafe] +apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } + [bank_config.online_banking_fpx] adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" fiuu.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_of_china,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -1257,7 +1260,7 @@ max_retry_count_for_thirty_day = 20 [revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery initial_timestamp_in_seconds = 3600 # number of seconds added to start time for Decider service of Revenue Recovery -job_schedule_buffer_time_in_seconds = 3600 # time in seconds to be added in schedule time as a buffer +job_schedule_buffer_time_in_seconds = 3600 # time in seconds to be added in schedule time as a buffer reopen_workflow_buffer_time_in_seconds = 60 # time in seconds to be added in scheduling for calculate workflow [clone_connector_allowlist] diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rs index e57c4370e48..57f239f6135 100644 --- a/crates/common_types/src/payments.rs +++ b/crates/common_types/src/payments.rs @@ -669,6 +669,13 @@ impl ApplePayPredecryptData { let month = self.get_expiry_month()?.expose(); Ok(Secret::new(format!("{month}{year}"))) } + + /// Get the expiry date in YYMM format from the Apple Pay pre-decrypt data + pub fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ValidationError> { + let year = self.get_two_digit_expiry_year()?.expose(); + let month = self.get_expiry_month()?.expose(); + Ok(Secret::new(format!("{year}{month}"))) + } } /// type of action that needs to taken after consuming recovery payload diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 186e08989ec..bf593ac2c7f 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -121,13 +121,22 @@ pub struct AccountIdConfigForRedirect { pub three_ds: Option<Vec<InputData>>, } +#[serde_with::skip_serializing_none] +#[derive(Debug, Deserialize, Serialize, Clone)] + +pub struct AccountIdConfigForApplePay { + pub encrypt: Option<Vec<InputData>>, + pub decrypt: Option<Vec<InputData>>, +} + #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct AccountIDSupportedMethods { + apple_pay: HashMap<String, AccountIdConfigForApplePay>, card: HashMap<String, AccountIdConfigForCard>, - skrill: HashMap<String, AccountIdConfigForRedirect>, interac: HashMap<String, AccountIdConfigForRedirect>, pay_safe_card: HashMap<String, AccountIdConfigForRedirect>, + skrill: HashMap<String, AccountIdConfigForRedirect>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 7d68c4de4fb..3c743540347 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -2158,7 +2158,7 @@ merchant_secret="Source verification key" api_key="Client ID" key1="Client Secret" [dwolla.connector_webhook_details] -merchant_secret="Source verification key" +merchant_secret = "Source verification key" [dwolla.metadata.merchant_funding_source] name = "merchant_funding_source" label = "Funding Source ID" @@ -6643,7 +6643,7 @@ options=[] [[santander.voucher]] payment_method_type = "boleto" [[santander.bank_transfer]] - payment_method_type = "pix" + payment_method_type = "pix" [santander.connector_auth.BodyKey] api_key="Client ID" @@ -6878,11 +6878,16 @@ payment_method_type = "interac" payment_method_type = "skrill" [[paysafe.gift_card]] payment_method_type = "pay_safe_card" +[[paysafe.wallet]] +payment_method_type = "apple_pay" + [paysafe.connector_auth.BodyKey] api_key = "Username" key1 = "Password" + [paysafe.connector_webhook_details] merchant_secret = "Source verification key" + [[paysafe.metadata.account_id.card.USD.three_ds]] name="three_ds" label="ThreeDS account id" @@ -6950,6 +6955,71 @@ placeholder="Enter eur Account ID" required=true type="Text" +[[paysafe.metadata.account_id.apple_pay.USD.encrypt]] +name="encrypt" +label="Encrypt" +placeholder="Enter encrypt value" +required=true +type="Text" +[[paysafe.metadata.account_id.apple_pay.USD.decrypt]] +name="decrypt" +label="Decrypt" +placeholder="Enter decrypt value" +required=true +type="Text" + +[[paysafe.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[paysafe.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[paysafe.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + [peachpayments] [[peachpayments.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index eff63730974..e606a71f33f 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -1322,7 +1322,7 @@ api_key="Celero API Key" api_key = "Checkbook API Secret key" [checkbook.connector_webhook_details] merchant_secret="Source verification key" - + [checkout] [[checkout.credit]] payment_method_type = "Mastercard" @@ -5346,7 +5346,7 @@ type = "Text" [[santander.voucher]] payment_method_type = "boleto" [[santander.bank_transfer]] - payment_method_type = "pix" + payment_method_type = "pix" [santander.connector_auth.BodyKey] api_key = "Client ID" key1 = "Client Secret" @@ -5596,11 +5596,16 @@ payment_method_type = "interac" payment_method_type = "skrill" [[paysafe.gift_card]] payment_method_type = "pay_safe_card" +[[paysafe.wallet]] +payment_method_type = "apple_pay" + [paysafe.connector_auth.BodyKey] api_key = "Username" key1 = "Password" + [paysafe.connector_webhook_details] merchant_secret = "Source verification key" + [[paysafe.metadata.account_id.card.USD.three_ds]] name="three_ds" label="ThreeDS account id" @@ -5668,6 +5673,71 @@ placeholder="Enter eur Account ID" required=true type="Text" +[[paysafe.metadata.account_id.apple_pay.USD.encrypt]] +name="encrypt" +label="Encrypt" +placeholder="Enter encrypt value" +required=true +type="Text" +[[paysafe.metadata.account_id.apple_pay.USD.decrypt]] +name="decrypt" +label="Decrypt" +placeholder="Enter decrypt value" +required=true +type="Text" + +[[paysafe.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[paysafe.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[paysafe.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + [peachpayments] [[peachpayments.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 379ea955c9a..cd03cb4b8f8 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6624,7 +6624,7 @@ options = [] [[santander.voucher]] payment_method_type = "boleto" [[santander.bank_transfer]] - payment_method_type = "pix" + payment_method_type = "pix" [santander.connector_auth.BodyKey] api_key = "Client ID" @@ -6857,11 +6857,16 @@ payment_method_type = "interac" payment_method_type = "skrill" [[paysafe.gift_card]] payment_method_type = "pay_safe_card" +[[paysafe.wallet]] +payment_method_type = "apple_pay" + [paysafe.connector_auth.BodyKey] api_key = "Username" key1 = "Password" + [paysafe.connector_webhook_details] merchant_secret = "Source verification key" + [[paysafe.metadata.account_id.card.USD.three_ds]] name="three_ds" label="ThreeDS account id" @@ -6929,7 +6934,70 @@ placeholder="Enter eur Account ID" required=true type="Text" +[[paysafe.metadata.account_id.apple_pay.USD.encrypt]] +name="encrypt" +label="Encrypt" +placeholder="Enter encrypt value" +required=true +type="Text" +[[paysafe.metadata.account_id.apple_pay.USD.decrypt]] +name="decrypt" +label="Decrypt" +placeholder="Enter decrypt value" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[paysafe.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[paysafe.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[paysafe.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] [peachpayments] [[peachpayments.credit]] diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe.rs b/crates/hyperswitch_connectors/src/connectors/paysafe.rs index df996434c78..c59149f37ff 100644 --- a/crates/hyperswitch_connectors/src/connectors/paysafe.rs +++ b/crates/hyperswitch_connectors/src/connectors/paysafe.rs @@ -342,6 +342,11 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData enums::PaymentMethod::Card if !req.is_three_ds() => { Ok(format!("{}v1/payments", self.base_url(connectors))) } + enums::PaymentMethod::Wallet + if req.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) => + { + Ok(format!("{}v1/payments", self.base_url(connectors))) + } _ => Ok(format!("{}v1/paymenthandles", self.base_url(connectors),)), } } @@ -365,6 +370,13 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } + enums::PaymentMethod::Wallet + if req.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) => + { + let connector_req = + paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } _ => { let connector_req = paysafe::PaysafePaymentHandleRequest::try_from(&connector_router_data)?; @@ -415,6 +427,21 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData http_code: res.status_code, }) } + enums::PaymentMethod::Wallet + if data.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) => + { + let response: paysafe::PaysafePaymentsResponse = res + .response + .parse_struct("Paysafe 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, + }) + } _ => { let response: paysafe::PaysafePaymentHandleResponse = res .response @@ -1029,6 +1056,17 @@ static PAYSAFE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = La }, ); + paysafe_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + paysafe_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::Skrill, diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs index 8a091a7aec2..5077aae085c 100644 --- a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs @@ -1,7 +1,9 @@ use std::collections::HashMap; +use base64::Engine; use cards::CardNumber; use common_enums::{enums, Currency}; +use common_types::payments::{ApplePayPaymentData, ApplePayPredecryptData}; use common_utils::{ id_type, pii::{Email, IpAddress, SecretSerdeValue}, @@ -10,8 +12,10 @@ use common_utils::{ }; use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::{BankRedirectData, GiftCardData, PaymentMethodData, WalletData}, - router_data::{ConnectorAuthType, RouterData}, + payment_method_data::{ + ApplePayWalletData, BankRedirectData, GiftCardData, PaymentMethodData, WalletData, + }, + router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreProcessingData, PaymentsSyncData, @@ -30,8 +34,9 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ - self, to_connector_meta, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, - PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _, + self, missing_field_err, to_connector_meta, BrowserInformationData, CardData, + PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + PaymentsPreProcessingRequestData, RouterData as _, }, }; @@ -56,10 +61,11 @@ pub struct PaysafeConnectorMetadataObject { #[derive(Debug, Default, Serialize, Deserialize)] pub struct PaysafePaymentMethodDetails { + pub apple_pay: Option<HashMap<Currency, ApplePayAccountDetails>>, pub card: Option<HashMap<Currency, CardAccountId>>, - pub skrill: Option<HashMap<Currency, RedirectAccountId>>, pub interac: Option<HashMap<Currency, RedirectAccountId>>, pub pay_safe_card: Option<HashMap<Currency, RedirectAccountId>>, + pub skrill: Option<HashMap<Currency, RedirectAccountId>>, } #[derive(Debug, Default, Serialize, Deserialize)] @@ -68,6 +74,12 @@ pub struct CardAccountId { three_ds: Option<Secret<String>>, } +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct ApplePayAccountDetails { + encrypt: Option<Secret<String>>, + decrypt: Option<Secret<String>>, +} + #[derive(Debug, Default, Serialize, Deserialize)] pub struct RedirectAccountId { three_ds: Option<Secret<String>>, @@ -151,12 +163,13 @@ pub struct PaysafeProfile { #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum PaysafePaymentMethod { + ApplePay { + #[serde(rename = "applePay")] + apple_pay: Box<PaysafeApplepayPayment>, + }, Card { card: PaysafeCard, }, - Skrill { - skrill: SkrillWallet, - }, Interac { #[serde(rename = "interacEtransfer")] interac_etransfer: InteracBankRedirect, @@ -165,6 +178,119 @@ pub enum PaysafePaymentMethod { #[serde(rename = "paysafecard")] pay_safe_card: PaysafeGiftCard, }, + Skrill { + skrill: SkrillWallet, + }, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplepayPayment { + pub label: Option<String>, + pub request_billing_address: Option<bool>, + #[serde(rename = "applePayPaymentToken")] + pub apple_pay_payment_token: PaysafeApplePayPaymentToken, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayPaymentToken { + pub token: PaysafeApplePayToken, + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_contact: Option<PaysafeApplePayBillingContact>, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayToken { + pub payment_data: PaysafeApplePayPaymentData, + pub payment_method: PaysafeApplePayPaymentMethod, + pub transaction_identifier: String, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(untagged)] +pub enum PaysafeApplePayPaymentData { + Encrypted(PaysafeApplePayEncryptedData), + Decrypted(PaysafeApplePayDecryptedDataWrapper), +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayEncryptedData { + pub data: Secret<String>, + pub signature: Secret<String>, + pub header: PaysafeApplePayHeader, + pub version: Secret<String>, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayDecryptedDataWrapper { + pub decrypted_data: PaysafeApplePayDecryptedData, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayDecryptedData { + pub application_primary_account_number: CardNumber, + pub application_expiration_date: Secret<String>, + pub currency_code: String, + pub transaction_amount: Option<MinorUnit>, + pub cardholder_name: Option<Secret<String>>, + pub device_manufacturer_identifier: Option<String>, + pub payment_data_type: Option<String>, + pub payment_data: PaysafeApplePayDecryptedPaymentData, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayDecryptedPaymentData { + pub online_payment_cryptogram: Secret<String>, + pub eci_indicator: String, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayHeader { + pub public_key_hash: String, + pub ephemeral_public_key: String, + pub transaction_id: String, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayPaymentMethod { + pub display_name: Secret<String>, + pub network: Secret<String>, + #[serde(rename = "type")] + pub method_type: Secret<String>, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeApplePayBillingContact { + pub address_lines: Vec<Option<Secret<String>>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub administrative_area: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option<String>, + pub country_code: api_models::enums::CountryAlpha2, + #[serde(skip_serializing_if = "Option::is_none")] + pub family_name: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub given_name: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub locality: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub phonetic_family_name: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub phonetic_given_name: Option<Secret<String>>, + pub postal_code: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub sub_administrative_area: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub sub_locality: Option<Secret<String>>, } #[derive(Debug, Serialize, Clone, PartialEq)] @@ -205,6 +331,7 @@ pub enum LinkType { #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaysafePaymentType { + // For Apple Pay and Google Pay, paymentType is 'CARD' as per Paysafe docs and is not reserved for card payments only Card, Skrill, InteracEtransfer, @@ -218,6 +345,32 @@ pub enum TransactionType { } impl PaysafePaymentMethodDetails { + pub fn get_applepay_encrypt_account_id( + &self, + currency: Currency, + ) -> Result<Secret<String>, errors::ConnectorError> { + self.apple_pay + .as_ref() + .and_then(|apple_pay| apple_pay.get(&currency)) + .and_then(|flow| flow.encrypt.clone()) + .ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig { + config: "Missing ApplePay encrypt account_id", + }) + } + + pub fn get_applepay_decrypt_account_id( + &self, + currency: Currency, + ) -> Result<Secret<String>, errors::ConnectorError> { + self.apple_pay + .as_ref() + .and_then(|apple_pay| apple_pay.get(&currency)) + .and_then(|flow| flow.decrypt.clone()) + .ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig { + config: "Missing ApplePay decrypt account_id", + }) + } + pub fn get_no_three_ds_account_id( &self, currency: Currency, @@ -289,84 +442,149 @@ impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePa fn try_from( item: &PaysafeRouterData<&PaymentsPreProcessingRouterData>, ) -> Result<Self, Self::Error> { - if item.router_data.is_three_ds() { - Err(errors::ConnectorError::NotSupported { - message: "Card 3DS".to_string(), - connector: "Paysafe", - })? - }; let metadata: PaysafeConnectorMetadataObject = utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "merchant_connector_account.metadata", })?; - let currency = item.router_data.request.get_currency()?; - match item.router_data.request.get_payment_method_data()?.clone() { - PaymentMethodData::Card(req_card) => { - let card = PaysafeCard { - card_num: req_card.card_number.clone(), - card_expiry: PaysafeCardExpiry { - month: req_card.card_exp_month.clone(), - year: req_card.get_expiry_year_4_digit(), - }, - cvv: if req_card.card_cvc.clone().expose().is_empty() { - None - } else { - Some(req_card.card_cvc.clone()) - }, - holder_name: item.router_data.get_optional_billing_full_name(), - }; - - let payment_method = PaysafePaymentMethod::Card { card: card.clone() }; - let account_id = metadata.account_id.get_no_three_ds_account_id(currency)?; - let amount = item.amount; - let payment_type = PaysafePaymentType::Card; - let transaction_type = TransactionType::Payment; - let redirect_url = item.router_data.request.get_router_return_url()?; - let return_links = vec![ - ReturnLink { - rel: LinkType::Default, - href: redirect_url.clone(), - method: Method::Get.to_string(), - }, - ReturnLink { - rel: LinkType::OnCompleted, - href: redirect_url.clone(), - method: Method::Get.to_string(), - }, - ReturnLink { - rel: LinkType::OnFailed, - href: redirect_url.clone(), - method: Method::Get.to_string(), - }, - ReturnLink { - rel: LinkType::OnCancelled, - href: redirect_url.clone(), - method: Method::Get.to_string(), - }, - ]; - - Ok(Self { - merchant_ref_num: item.router_data.connector_request_reference_id.clone(), - amount, - settle_with_auth: matches!( - item.router_data.request.capture_method, - Some(enums::CaptureMethod::Automatic) | None - ), - payment_method, - currency_code: currency, - payment_type, - transaction_type, - return_links, - account_id, - three_ds: None, - profile: None, - }) - } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - ))?, - } + + let amount = item.amount; + let currency_code = item.router_data.request.get_currency()?; + let redirect_url = item.router_data.request.get_router_return_url()?; + let return_links = vec![ + ReturnLink { + rel: LinkType::Default, + href: redirect_url.clone(), + method: Method::Get.to_string(), + }, + ReturnLink { + rel: LinkType::OnCompleted, + href: redirect_url.clone(), + method: Method::Get.to_string(), + }, + ReturnLink { + rel: LinkType::OnFailed, + href: redirect_url.clone(), + method: Method::Get.to_string(), + }, + ReturnLink { + rel: LinkType::OnCancelled, + href: redirect_url.clone(), + method: Method::Get.to_string(), + }, + ]; + let settle_with_auth = matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + ); + let transaction_type = TransactionType::Payment; + + let (payment_method, payment_type, account_id) = + match item.router_data.request.get_payment_method_data()?.clone() { + PaymentMethodData::Card(req_card) => { + let card = PaysafeCard { + card_num: req_card.card_number.clone(), + card_expiry: PaysafeCardExpiry { + month: req_card.card_exp_month.clone(), + year: req_card.get_expiry_year_4_digit(), + }, + cvv: if req_card.card_cvc.clone().expose().is_empty() { + None + } else { + Some(req_card.card_cvc.clone()) + }, + holder_name: item.router_data.get_optional_billing_full_name(), + }; + + let payment_method = PaysafePaymentMethod::Card { card: card.clone() }; + let payment_type = PaysafePaymentType::Card; + let account_id = metadata + .account_id + .get_no_three_ds_account_id(currency_code)?; + (payment_method, payment_type, account_id) + } + PaymentMethodData::Wallet(wallet_data) => match wallet_data { + WalletData::ApplePay(applepay_data) => { + let is_encrypted = matches!( + applepay_data.payment_data, + ApplePayPaymentData::Encrypted(_) + ); + + let account_id = if is_encrypted { + metadata + .account_id + .get_applepay_encrypt_account_id(currency_code)? + } else { + metadata + .account_id + .get_applepay_decrypt_account_id(currency_code)? + }; + + let applepay_payment = + PaysafeApplepayPayment::try_from((&applepay_data, item))?; + + let payment_method = PaysafePaymentMethod::ApplePay { + apple_pay: Box::new(applepay_payment), + }; + + let payment_type = PaysafePaymentType::Card; + + (payment_method, payment_type, account_id) + } + WalletData::AliPayQr(_) + | WalletData::AliPayRedirect(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::AmazonPay(_) + | WalletData::AmazonPayRedirect(_) + | WalletData::Paysera(_) + | WalletData::Skrill(_) + | WalletData::BluecodeRedirect {} + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePay(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::MobilePayRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::PaypalRedirect(_) + | WalletData::Paze(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::CashappQr(_) + | WalletData::SwishQr(_) + | WalletData::WeChatPayQr(_) + | WalletData::RevolutPay(_) + | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paysafe"), + ))?, + }, + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + ))?, + }; + + Ok(Self { + merchant_ref_num: item.router_data.connector_request_reference_id.clone(), + amount, + settle_with_auth, + payment_method, + currency_code, + payment_type, + transaction_type, + return_links, + account_id, + three_ds: None, + profile: None, + }) } } @@ -441,6 +659,7 @@ impl<F> >, ) -> Result<Self, Self::Error> { Ok(Self { + status: enums::AttemptStatus::try_from(item.response.status)?, preprocessing_id: Some( item.response .payment_handle_token @@ -516,15 +735,16 @@ impl<F> PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let url = match item.response.links.as_ref().and_then(|links| links.first()) { - Some(link) => link.href.clone(), - None => return Err(errors::ConnectorError::ResponseDeserializationFailed)?, - }; - let redirection_data = Some(RedirectForm::Form { - endpoint: url, - method: Method::Get, - form_fields: Default::default(), - }); + let redirection_data = item + .response + .links + .as_ref() + .and_then(|links| links.first()) + .map(|link| RedirectForm::Form { + endpoint: link.href.clone(), + method: Method::Get, + form_fields: Default::default(), + }); let connector_metadata = serde_json::json!(PaysafeMeta { payment_handle_token: item.response.payment_handle_token.clone(), }); @@ -572,6 +792,159 @@ pub struct PaysafeCardExpiry { pub year: Secret<String>, } +#[derive(Debug, Deserialize)] +struct DecryptedApplePayTokenData { + data: Secret<String>, + signature: Secret<String>, + header: DecryptedApplePayTokenHeader, + version: Secret<String>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct DecryptedApplePayTokenHeader { + public_key_hash: String, + ephemeral_public_key: String, + transaction_id: String, +} + +fn get_apple_pay_decrypt_data( + apple_pay_predecrypt_data: &ApplePayPredecryptData, + item: &PaysafeRouterData<&PaymentsPreProcessingRouterData>, +) -> Result<PaysafeApplePayDecryptedData, error_stack::Report<errors::ConnectorError>> { + Ok(PaysafeApplePayDecryptedData { + application_primary_account_number: apple_pay_predecrypt_data + .application_primary_account_number + .clone(), + application_expiration_date: apple_pay_predecrypt_data + .get_expiry_date_as_yymm() + .change_context(errors::ConnectorError::InvalidDataFormat { + field_name: "application_expiration_date", + })?, + currency_code: Currency::iso_4217( + item.router_data + .request + .currency + .ok_or_else(missing_field_err("currency"))?, + ) + .to_string(), + + transaction_amount: Some(item.amount), + cardholder_name: None, + device_manufacturer_identifier: Some("Apple".to_string()), + payment_data_type: Some("3DSecure".to_string()), + payment_data: PaysafeApplePayDecryptedPaymentData { + online_payment_cryptogram: apple_pay_predecrypt_data + .payment_data + .online_payment_cryptogram + .clone(), + eci_indicator: apple_pay_predecrypt_data + .payment_data + .eci_indicator + .clone() + .ok_or_else(missing_field_err( + "payment_method_data.wallet.apple_pay.payment_data.eci_indicator", + ))?, + }, + }) +} + +impl + TryFrom<( + &ApplePayWalletData, + &PaysafeRouterData<&PaymentsPreProcessingRouterData>, + )> for PaysafeApplepayPayment +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (wallet_data, item): ( + &ApplePayWalletData, + &PaysafeRouterData<&PaymentsPreProcessingRouterData>, + ), + ) -> Result<Self, Self::Error> { + let apple_pay_payment_token = PaysafeApplePayPaymentToken { + token: PaysafeApplePayToken { + payment_data: if let Ok(PaymentMethodToken::ApplePayDecrypt(ref token)) = + item.router_data.get_payment_method_token() + { + PaysafeApplePayPaymentData::Decrypted(PaysafeApplePayDecryptedDataWrapper { + decrypted_data: get_apple_pay_decrypt_data(token, item)?, + }) + } else { + match &wallet_data.payment_data { + ApplePayPaymentData::Decrypted(applepay_predecrypt_data) => { + PaysafeApplePayPaymentData::Decrypted( + PaysafeApplePayDecryptedDataWrapper { + decrypted_data: get_apple_pay_decrypt_data( + applepay_predecrypt_data, + item, + )?, + }, + ) + } + ApplePayPaymentData::Encrypted(applepay_encrypt_data) => { + let decoded_data = base64::prelude::BASE64_STANDARD + .decode(applepay_encrypt_data) + .change_context(errors::ConnectorError::InvalidDataFormat { + field_name: "apple_pay_encrypted_data", + })?; + + let apple_pay_token: DecryptedApplePayTokenData = + serde_json::from_slice(&decoded_data).change_context( + errors::ConnectorError::InvalidDataFormat { + field_name: "apple_pay_token_json", + }, + )?; + + PaysafeApplePayPaymentData::Encrypted(PaysafeApplePayEncryptedData { + data: apple_pay_token.data, + signature: apple_pay_token.signature, + header: PaysafeApplePayHeader { + public_key_hash: apple_pay_token.header.public_key_hash, + ephemeral_public_key: apple_pay_token + .header + .ephemeral_public_key, + transaction_id: apple_pay_token.header.transaction_id, + }, + version: apple_pay_token.version, + }) + } + } + }, + payment_method: PaysafeApplePayPaymentMethod { + display_name: Secret::new(wallet_data.payment_method.display_name.clone()), + network: Secret::new(wallet_data.payment_method.network.clone()), + method_type: Secret::new(wallet_data.payment_method.pm_type.clone()), + }, + transaction_identifier: wallet_data.transaction_identifier.clone(), + }, + billing_contact: Some(PaysafeApplePayBillingContact { + address_lines: vec![ + item.router_data.get_optional_billing_line1(), + item.router_data.get_optional_billing_line2(), + ], + postal_code: item.router_data.get_billing_zip()?, + country_code: item.router_data.get_billing_country()?, + country: None, + family_name: None, + given_name: None, + locality: None, + phonetic_family_name: None, + phonetic_given_name: None, + sub_administrative_area: None, + administrative_area: None, + sub_locality: None, + }), + }; + + Ok(Self { + label: None, + request_billing_address: Some(false), + apple_pay_payment_token, + }) + } +} + impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn 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 bfb3e36b291..eccd9b02b37 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -2393,6 +2393,17 @@ fn get_wallet_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFi Connector::Novalnet, fields(vec![], vec![], vec![RequiredField::BillingEmail]), ), + ( + Connector::Paysafe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::from([ + RequiredField::BillingAddressZip.to_tuple(), + RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), + ]), + }, + ), ( Connector::Wellsfargo, RequiredFieldFinal { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 56db1b8d080..19faac6084c 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -6567,6 +6567,12 @@ where router_data.preprocessing_steps(state, connector).await?, false, ) + } else if connector.connector_name == router_types::Connector::Paysafe { + router_data = router_data.preprocessing_steps(state, connector).await?; + + let is_error_in_response = router_data.response.is_err(); + // If is_error_in_response is true, should_continue_payment should be false, we should throw the error + (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index cd4fe3fc8c0..cb25fa4c830 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -680,6 +680,9 @@ credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +[pm_filters.paysafe] +apple_pay = {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,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,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,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,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" } + #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" } }
2025-09-11T09:49:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> this pr adds comprehensive apple pay support to the paysafe connector, enabling merchants to process apple pay transactions through paysafe's payment gateway - dynamic account id detection for apple pay for both encrypt and decrypt flows - payment via apple pay in paysafe happens in 2 steps: - payment initiate: hits `/paymenthandles` endpoint (happens in preprocessing step) with all the necessary apple data - payment confirm: hits `/payments` endpoint with the payment handle token to complete the payment ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> the pr includes connector metadata enhancements and preprocessing flow modifications. ## 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). --> expanding payment method support to include apple pay for paysafe connector. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> >[!NOTE] > To test it locally, the base URL should be `https` and not `http`. <details> <summary>MCA</summary> ```bash curl --location 'https://base_url/account/postman_merchant_GHAction_1757583450/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Pvdq3IlcMf857bnbRpKevrNjeNEvoU7e66n5nwBHCCcsI9mSzrtyafBeQ7FuKArE' \ --data '{ "connector_type": "payment_processor", "connector_name": "paysafe", "business_country": "US", "business_label": "default", "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", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "card_networks": [ "AmericanExpress", "Discover", "Interac", "JCB", "Mastercard", "Visa", "DinersClub", "UnionPay", "RuPay" ] }, { "payment_method_type": "debit", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "card_networks": [ "AmericanExpress", "Discover", "Interac", "JCB", "Mastercard", "Visa", "DinersClub", "UnionPay", "RuPay" ] } ] }, { "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 } ] } ], "metadata": { "account_id": { "apple_pay": { "USD": { "encrypt": "1003013960", "decrypt": "1003013960" } } }, "apple_pay_combined": { "manual": { "payment_request_data": { "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ], "label": "apple" }, "session_token_data": { "certificate": "certificate", "certificate_keys": "certificate_keys", "merchant_identifier": "merchant.merchant.identifier", "display_name": "Apple Pay", "initiative": "web", "initiative_context": "example.com", "merchant_business_country": "US", "payment_processing_details_at": "Connector" } } } }, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": { "apple_pay_combined": { "manual": { "payment_request_data": { "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ], "label": "apple" }, "session_token_data": { "certificate": "certificate", "certificate_keys": "certificate_keys", "display_name": "Apple Pay", "initiative": "web", "initiative_context": "example.com", "merchant_business_country": "US", "payment_processing_details_at": "Connector" } } } } }' ``` ```json { "connector_type": "payment_processor", "connector_name": "paysafe", "connector_label": "paysafe_US_default", "merchant_connector_id": "mca_IpxHuANMVZ1qWbcGRcil", "profile_id": "pro_pdMcyhMaLhxejyxdm4Gh", "connector_account_details": { "auth_type": "BodyKey", "api_key": "ap**ey", "key1": "k**1" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "AmericanExpress", "Discover", "Interac", "JCB", "Mastercard", "Visa", "DinersClub", "UnionPay", "RuPay" ], "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": [ "AmericanExpress", "Discover", "Interac", "JCB", "Mastercard", "Visa", "DinersClub", "UnionPay", "RuPay" ], "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": "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 } ] } ], "connector_webhook_details": null, "metadata": { "account_id": { "card": { "USD": { "no_three_ds": "123456", "three_ds": "123456" }, "EUR": { "no_three_ds": "123456", "three_ds": "123456" } }, "wallet": { "apple_pay": { "USD": { "encrypt": "123456", "decrypt": "123456" } } } }, "apple_pay_combined": { "manual": { "payment_request_data": { "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ], "label": "apple" }, "session_token_data": { "certificate": "certificate", "certificate_keys": "certificate_keys", "merchant_identifier": "merchant.merchant.identifier", "display_name": "Apple Pay", "initiative": "web", "initiative_context": "example.com", "merchant_business_country": "US", "payment_processing_details_at": "Connector" } } } }, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": { "apple_pay_combined": { "manual": { "payment_request_data": { "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ], "label": "apple" }, "session_token_data": { "certificate": "certificate", "certificate_keys": "certificate_keys", "display_name": "Apple Pay", "initiative": "web", "initiative_context": "example.com", "merchant_business_country": "US", "payment_processing_details_at": "Connector" } } } } } ``` </details> <details> <summary>Payment Initiate</summary> ```bash curl --location 'https://base_url/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_easrii6Oqqq9fjnj4AQw7tkdKDf9bfo8cIEa9IfUj8nl7LbLjMQD1cM9UeK6jnLb' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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_AOWndR0v1zIfq8T8Ff7h", "merchant_id": "postman_merchant_GHAction_1758644632", "status": "requires_payment_method", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_AOWndR0v1zIfq8T8Ff7h_secret_Tjst2yhf6Z5Ju7C3fGnT", "created": "2025-09-23T17:06:52.717Z", "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": null, "billing": null, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1758647212, "expires": 1758650812, "secret": "epk_aee57839c2554a47bd89f221608987ef" }, "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_X9nYDTDvLffn5ZFzovVC", "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-09-23T17:21:52.717Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-23T17:06:52.746Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` </details> <details> <summary>Session call</summary> ```bash curl --location 'https://base_url/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_8bc73f9c3edb44f7b8a4c9f08fa49169' \ --data '{ "payment_id": "pay_AOWndR0v1zIfq8T8Ff7h", "wallets": [], "client_secret": "pay_AOWndR0v1zIfq8T8Ff7h_secret_Tjst2yhf6Z5Ju7C3fGnT" }' ``` ```json { "payment_id": "pay_AOWndR0v1zIfq8T8Ff7h", "client_secret": "pay_AOWndR0v1zIfq8T8Ff7h_secret_Tjst2yhf6Z5Ju7C3fGnT", "session_token": [ { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1758647230798, "expires_at": 1758650830798, "merchant_session_identifier": "SS..C3", "nonce": "3ed97144", "merchant_identifier": "8C..C4", "domain_name": "hyperswitch.app", "display_name": "apple pay", "signature": "30..00", "operational_analytics_identifier": "apple pay:8C..C4", "retries": 0, "psp_id": "8C..C4" }, "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "10.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant" }, "connector": "paysafe", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` </details> <details> <summary>Payment Confirm (Encrypt)</summary> ```bash curl --location 'https://base_url/payments/pay_AOWndR0v1zIfq8T8Ff7h/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_easrii6Oqqq9fjnj4AQw7tkdKDf9bfo8cIEa9IfUj8nl7LbLjMQD1cM9UeK6jnLb' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": { "application_primary_account_number": "48..60", "application_expiration_month": "01", "application_expiration_year": "31", "payment_data": { "online_payment_cryptogram": "A..=", "eci_indicator": "7" } }, "payment_method": { "display_name": "Visa 4228", "network": "Visa", "type": "debit" }, "transaction_identifier": "a0..4a" } }, "billing": null }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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" } } }' ``` ```json { "payment_id": "pay_AOWndR0v1zIfq8T8Ff7h", "merchant_id": "postman_merchant_GHAction_1758644632", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "paysafe", "client_secret": "pay_AOWndR0v1zIfq8T8Ff7h_secret_Tjst2yhf6Z5Ju7C3fGnT", "created": "2025-09-23T17:06:52.717Z", "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": { "apple_pay": { "last4": "4228", "card_network": "Visa", "type": "debit" } }, "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", "origin_zip": 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": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "connector_label": "paysafe_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "c847c066-1d83-4b8c-9b2e-1a72559849c1", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_X9nYDTDvLffn5ZFzovVC", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_i61PcZcv8kyTX059WELX", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-23T17:21:52.717Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "os_version": null, "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, "device_model": null, "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, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-23T17:07:45.459Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` </details> <details> <summary>Payment Initiate</summary> ```bash curl --location 'https://base_url/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_easrii6Oqqq9fjnj4AQw7tkdKDf9bfo8cIEa9IfUj8nl7LbLjMQD1cM9UeK6jnLb' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "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_mBfTZrLSPhmdcPGo6cwg", "merchant_id": "postman_merchant_GHAction_1758644632", "status": "requires_payment_method", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_mBfTZrLSPhmdcPGo6cwg_secret_rnqK1jqamjwpYrBxNqRx", "created": "2025-09-23T17:10:35.122Z", "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": null, "billing": null, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1758647435, "expires": 1758651035, "secret": "epk_7c990250150a4b80bab9366a184d17ae" }, "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_X9nYDTDvLffn5ZFzovVC", "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-09-23T17:25:35.122Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-23T17:10:35.142Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` </details> <details> <summary>Session call</summary> ```bash curl --location 'https://base_url/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_8bc73f9c3edb44f7b8a4c9f08fa49169' \ --data '{ "payment_id": "pay_mBfTZrLSPhmdcPGo6cwg", "wallets": [], "client_secret": "pay_mBfTZrLSPhmdcPGo6cwg_secret_rnqK1jqamjwpYrBxNqRx" }' ``` ```json { "payment_id": "pay_mBfTZrLSPhmdcPGo6cwg", "client_secret": "pay_mBfTZrLSPhmdcPGo6cwg_secret_rnqK1jqamjwpYrBxNqRx", "session_token": [ { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1758647447788, "expires_at": 1758651047788, "merchant_session_identifier": "SS..C3", "nonce": "8de2c3ef", "merchant_identifier": "8C..C4", "domain_name": "hyperswitch.app", "display_name": "apple pay", "signature": "30..00", "operational_analytics_identifier": "apple pay:8C..C4", "retries": 0, "psp_id": "8C..C4" }, "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "10.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant" }, "connector": "paysafe", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` </details> <details> <summary>Payment Confirm (Decrypt)</summary> ```bash curl --location 'https://base_url/payments/pay_mBfTZrLSPhmdcPGo6cwg/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_easrii6Oqqq9fjnj4AQw7tkdKDf9bfo8cIEa9IfUj8nl7LbLjMQD1cM9UeK6jnLb' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "ey...n0=", "payment_method": { "display_name": "Visa 4228", "network": "Visa", "type": "debit" }, "transaction_identifier": "a0...4a" } }, "billing": null }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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" } } }' ``` ```json { "payment_id": "pay_mBfTZrLSPhmdcPGo6cwg", "merchant_id": "postman_merchant_GHAction_1758644632", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "paysafe", "client_secret": "pay_mBfTZrLSPhmdcPGo6cwg_secret_rnqK1jqamjwpYrBxNqRx", "created": "2025-09-23T17:10:35.122Z", "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": { "apple_pay": { "last4": "4228", "card_network": "Visa", "type": "debit" } }, "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", "origin_zip": 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": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "connector_label": "paysafe_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "3becc659-ad98-4e6a-9e72-5290eb80e214", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": null, "payment_link": null, "profile_id": "pro_X9nYDTDvLffn5ZFzovVC", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_i61PcZcv8kyTX059WELX", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-23T17:25:35.122Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "os_version": null, "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, "device_model": null, "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, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-23T17:11:20.313Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` </details> <details> <summary>WASM changes</summary> <img width="618" height="858" alt="image" src="https://github.com/user-attachments/assets/7d0439bb-dd00-4bdc-95da-1334ef4c9fa0" /> </details> <details> <summary>Dashboard changes</summary> <img width="1001" height="204" alt="image" src="https://github.com/user-attachments/assets/e3ee4b50-b27f-4c20-be92-24e23415d85a" /> <img width="569" height="464" alt="image" src="https://github.com/user-attachments/assets/d71fe988-85b5-4f2d-8d94-8131b86a61b7" /> <img width="570" height="994" alt="image" src="https://github.com/user-attachments/assets/718b5878-e609-4c68-b56b-e0a7596eaa54" /> <img width="656" height="162" alt="image" src="https://github.com/user-attachments/assets/9631030a-b128-4480-baaa-00225d4c0033" /> <img width="567" height="154" alt="image" src="https://github.com/user-attachments/assets/9e680eac-c108-493e-82e3-701191f34c44" /> <img width="830" height="224" alt="image" src="https://github.com/user-attachments/assets/97446ac7-d03c-4e1e-80a2-44786b082e12" /> </details> > [!IMPORTANT] > Connector decryption flow is not fully implemented yet. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
juspay/hyperswitch
juspay__hyperswitch-9335
Bug: [FEATURE] Novalnet - integrate NTI fields ### Feature Description Novalnet sends back and allows processing payments using network's transaction IDs. These are needed to be captured from payments API response and also send it when processing payments using NTI flow. ### Possible Implementation Connector integration updates. ### 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/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index c3fa01c74ca..b0405855e61 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -111,6 +111,7 @@ pub struct NovalnetRawCardDetails { card_number: CardNumber, card_expiry_month: Secret<String>, card_expiry_year: Secret<String>, + scheme_tid: Secret<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -163,7 +164,6 @@ pub struct NovalnetPaymentsRequestTransaction { error_return_url: Option<String>, enforce_3d: Option<i8>, //NOTE: Needed for CREDITCARD, GOOGLEPAY create_token: Option<i8>, - scheme_tid: Option<Secret<String>>, // Card network's transaction ID } #[derive(Debug, Serialize, Clone)] @@ -276,7 +276,6 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: Some(novalnet_card), enforce_3d, create_token, - scheme_tid: None, }; Ok(Self { @@ -316,7 +315,6 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: Some(novalnet_google_pay), enforce_3d, create_token, - scheme_tid: None, }; Ok(Self { @@ -342,7 +340,6 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym })), enforce_3d: None, create_token, - scheme_tid: None, }; Ok(Self { @@ -390,7 +387,6 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: None, enforce_3d: None, create_token, - scheme_tid: None, }; Ok(Self { merchant, @@ -449,7 +445,6 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: Some(novalnet_mandate_data), enforce_3d, create_token: None, - scheme_tid: None, }; Ok(Self { @@ -468,6 +463,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym card_number: raw_card_details.card_number.clone(), card_expiry_month: raw_card_details.card_exp_month.clone(), card_expiry_year: raw_card_details.card_exp_year.clone(), + scheme_tid: network_transaction_id.into(), }); let transaction = NovalnetPaymentsRequestTransaction { @@ -482,7 +478,6 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: Some(novalnet_card), enforce_3d, create_token, - scheme_tid: Some(network_transaction_id.into()), }; Ok(Self { @@ -692,7 +687,15 @@ impl<F, T> TryFrom<ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsRe } })), connector_metadata: None, - network_txn_id: None, + network_txn_id: item.response.transaction.and_then(|data| { + data.payment_data + .and_then(|payment_data| match payment_data { + NovalnetResponsePaymentData::Card(card) => { + card.scheme_tid.map(|tid| tid.expose()) + } + NovalnetResponsePaymentData::Paypal(_) => None, + }) + }), connector_response_reference_id: transaction_id.clone(), incremental_authorization_allowed: None, charges: None, @@ -783,6 +786,7 @@ pub struct NovalnetResponseCard { pub cc_3d: Option<Secret<u8>>, pub last_four: Option<Secret<String>>, pub token: Option<Secret<String>>, + pub scheme_tid: Option<Secret<String>>, } #[derive(Serialize, Deserialize, Clone, Debug)] @@ -1094,7 +1098,15 @@ impl<F> } })), connector_metadata: None, - network_txn_id: None, + network_txn_id: item.response.transaction.and_then(|data| { + data.payment_data + .and_then(|payment_data| match payment_data { + NovalnetResponsePaymentData::Card(card) => { + card.scheme_tid.map(|tid| tid.expose()) + } + NovalnetResponsePaymentData::Paypal(_) => None, + }) + }), connector_response_reference_id: transaction_id.clone(), incremental_authorization_allowed: None, charges: None, @@ -1544,7 +1556,6 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { payment_data: Some(novalnet_card), enforce_3d, create_token, - scheme_tid: None, }; Ok(Self { @@ -1582,7 +1593,6 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { payment_data: Some(novalnet_google_pay), enforce_3d, create_token, - scheme_tid: None, }; Ok(Self { @@ -1607,7 +1617,6 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { })), enforce_3d: None, create_token, - scheme_tid: None, }; Ok(Self { @@ -1654,7 +1663,6 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { payment_data: None, enforce_3d: None, create_token, - scheme_tid: None, }; Ok(Self {
2025-09-10T08:18:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR enables reading NTI from Novalnet's payments response. And also updates the integration for raw card + NTI flow. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Allows HS consumers using Novalnet to persist `network_transaction_id` and also to process payments using raw card + NTI flow. ## How did you test it? <details> <summary>1. Process card CIT</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_1hbJaLcnNC7iqUQD89rKd2Wg8dNRSi5Zq0lJboT8jIKY3YsopGxJQIjrHfT18oYp' \ --data-raw '{"amount":4500,"currency":"EUR","confirm":true,"profile_id":"pro_VWVhP8nTOe47wWOSGJGw","capture_method":"automatic","authentication_type":"three_ds","setup_future_usage":"off_session","connector":["novalnet"],"customer_id":"agnostic_test_customer","return_url":"https://google.com","payment_method":"card","payment_method_data":{"card":{"card_number":"4111111111111111","card_exp_month":"03","card_exp_year":"2030","card_cvc":"737"},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","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"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"metadata":{"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"}},"session_expiry":2890}' Response {"payment_id":"pay_KwXxBKx1TiKHH6ZwmraE","merchant_id":"merchant_1757581123","status":"requires_customer_action","amount":4500,"net_amount":4500,"shipping_cost":null,"amount_capturable":4500,"amount_received":null,"connector":"novalnet","client_secret":"pay_KwXxBKx1TiKHH6ZwmraE_secret_aD0Pn7be1ZSGjqcdLetk","created":"2025-09-11T10:33:16.809Z","currency":"EUR","customer_id":"agnostic_test_customer","customer":{"id":"agnostic_test_customer","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":"card","payment_method_data":{"card":{"last4":"1111","card_type":"CREDIT","card_network":"Visa","card_issuer":"JP Morgan","card_issuing_country":"INDIA","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":null,"first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"}},"payment_token":null,"shipping":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":null,"last_name":null,"origin_zip":null},"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":null,"first_name":"joseph","last_name":"Doe","origin_zip":null},"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":"http://localhost:8080/payments/redirect/pay_KwXxBKx1TiKHH6ZwmraE/merchant_1757581123/pay_KwXxBKx1TiKHH6ZwmraE_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":"agnostic_test_customer","created_at":1757586796,"expires":1757590396,"secret":"epk_54deae69cfe8474597ee97bcf2a20f68"},"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":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":null,"payment_link":null,"profile_id":"pro_VWVhP8nTOe47wWOSGJGw","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_DsZfA2bQdRFuYYticYjC","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-11T11:21:26.809Z","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_channel":null,"payment_method_id":"pm_Ehu3SdGRlE6KNvErguGv","network_transaction_id":null,"payment_method_status":"inactive","updated":"2025-09-11T10:33:17.987Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} Open and complete 3DS payment cURL (payments retrieve) curl --location --request GET 'http://localhost:8080/payments/pay_KwXxBKx1TiKHH6ZwmraE?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_1hbJaLcnNC7iqUQD89rKd2Wg8dNRSi5Zq0lJboT8jIKY3YsopGxJQIjrHfT18oYp' Response (must contain `network_transaction_id`) {"payment_id":"pay_KwXxBKx1TiKHH6ZwmraE","merchant_id":"merchant_1757581123","status":"succeeded","amount":4500,"net_amount":4500,"shipping_cost":null,"amount_capturable":0,"amount_received":4500,"connector":"novalnet","client_secret":"pay_KwXxBKx1TiKHH6ZwmraE_secret_aD0Pn7be1ZSGjqcdLetk","created":"2025-09-11T10:33:16.809Z","currency":"EUR","customer_id":"agnostic_test_customer","customer":{"id":"agnostic_test_customer","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":"card","payment_method_data":{"card":{"last4":"1111","card_type":"CREDIT","card_network":"Visa","card_issuer":"JP Morgan","card_issuing_country":"INDIA","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":null,"first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"}},"payment_token":null,"shipping":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":null,"last_name":null,"origin_zip":null},"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":null,"first_name":"joseph","last_name":"Doe","origin_zip":null},"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":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":"15236300041213946","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"15236300041213946","payment_link":null,"profile_id":"pro_VWVhP8nTOe47wWOSGJGw","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_DsZfA2bQdRFuYYticYjC","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-11T11:21:26.809Z","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_channel":null,"payment_method_id":"pm_Ehu3SdGRlE6KNvErguGv","network_transaction_id":"3623011723898289702365","payment_method_status":"active","updated":"2025-09-11T10:33:35.522Z","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} </details> <details> <summary>2. Process txn using NTI flow</summary> Pre-requisites 1. `is_connector_agnostic_mit_enabled` is enabled in profile 2. Stored payment method entry only has raw card details + NTI (no PSP token) <img width="1684" height="204" alt="Screenshot 2025-09-11 at 4 25 31 PM" src="https://github.com/user-attachments/assets/6296cc9e-1765-471c-9c08-a644f56afce7" /> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_1hbJaLcnNC7iqUQD89rKd2Wg8dNRSi5Zq0lJboT8jIKY3YsopGxJQIjrHfT18oYp' \ --data '{"amount":1000,"currency":"EUR","confirm":true,"capture_on":"2022-09-10T10:11:12Z","customer_id":"agnostic_test_customer","description":"Its my first payment request","return_url":"https://hyperswitch.io","off_session":true,"recurring_details":{"type":"payment_method_id","data":"pm_Ehu3SdGRlE6KNvErguGv"}}' Response {"payment_id":"pay_zkCwmnk8BmiLH0LeUqOb","merchant_id":"merchant_1757581123","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":1000,"connector":"novalnet","client_secret":"pay_zkCwmnk8BmiLH0LeUqOb_secret_XNve5qlQwoHPZuKjWo6K","created":"2025-09-11T10:57:18.973Z","currency":"EUR","customer_id":"agnostic_test_customer","customer":{"id":"agnostic_test_customer","name":null,"email":null,"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":null,"off_session":true,"capture_on":null,"capture_method":null,"payment_method":"card","payment_method_data":{"card":{"last4":"1111","card_type":"CREDIT","card_network":"Visa","card_issuer":"JP Morgan","card_issuing_country":"INDIA","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://hyperswitch.io/","authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"agnostic_test_customer","created_at":1757588238,"expires":1757591838,"secret":"epk_2df49937a64b445a93b27ed3e8cc323c"},"manual_retry_allowed":false,"connector_transaction_id":"15236300042606240","frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"15236300042606240","payment_link":null,"profile_id":"pro_VWVhP8nTOe47wWOSGJGw","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_DsZfA2bQdRFuYYticYjC","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-11T11:12:18.972Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_Ehu3SdGRlE6KNvErguGv","network_transaction_id":"1595759806994174449514","payment_method_status":"active","updated":"2025-09-11T10:57:22.956Z","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":"saved_card","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,"enable_partial_authorization":null,"enable_overcapture":null,"is_overcapture_enabled":null,"network_details":null} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
juspay/hyperswitch
juspay__hyperswitch-9345
Bug: Handle incoming webhooks for invoice_created event
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index 5885f7fb98c..23212cb69f1 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -67,6 +67,7 @@ pub enum IncomingWebhookEvent { #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryInvoiceCancel, SetupWebhook, + InvoiceGenerated, } impl IncomingWebhookEvent { @@ -300,6 +301,7 @@ impl From<IncomingWebhookEvent> for WebhookFlow { | IncomingWebhookEvent::RecoveryPaymentPending | IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery, IncomingWebhookEvent::SetupWebhook => Self::Setup, + IncomingWebhookEvent::InvoiceGenerated => Self::Subscription, } } } @@ -341,6 +343,7 @@ pub enum ObjectReferenceId { PayoutId(PayoutIdType), #[cfg(all(feature = "revenue_recovery", feature = "v2"))] InvoiceId(InvoiceIdType), + SubscriptionId(common_utils::id_type::SubscriptionId), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] @@ -388,7 +391,12 @@ impl ObjectReferenceId { common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received InvoiceId", }, - ) + ), + Self::SubscriptionId(_) => Err( + common_utils::errors::ValidationError::IncorrectValueProvided { + field_name: "PaymentId is required but received SubscriptionId", + }, + ), } } } diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index 167c2a337ba..43773022596 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -9,8 +9,6 @@ use common_utils::{ request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; -#[cfg(feature = "v1")] -use error_stack::report; use error_stack::ResultExt; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::{revenue_recovery, router_data_v2::RouterDataV2}; @@ -1319,17 +1317,25 @@ impl webhooks::IncomingWebhook for Chargebee { chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api_models::webhooks::ObjectReferenceId::InvoiceId( - api_models::webhooks::InvoiceIdType::ConnectorInvoiceId(webhook.content.invoice.id), + api_models::webhooks::InvoiceIdType::ConnectorInvoiceId( + webhook.content.invoice.id.get_string_repr().to_string(), + ), )) } #[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))] fn get_webhook_object_reference_id( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let webhook = + chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body) + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + + let subscription_id = webhook.content.invoice.subscription_id; + Ok(api_models::webhooks::ObjectReferenceId::SubscriptionId( + subscription_id, + )) } - #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, @@ -1340,13 +1346,6 @@ impl webhooks::IncomingWebhook for Chargebee { let event = api_models::webhooks::IncomingWebhookEvent::from(webhook.event_type); Ok(event) } - #[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))] - 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, @@ -1375,6 +1374,36 @@ impl webhooks::IncomingWebhook for Chargebee { transformers::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)?; revenue_recovery::RevenueRecoveryInvoiceData::try_from(webhook) } + + fn get_subscription_mit_payment_data( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData, + errors::ConnectorError, + > { + let webhook_body = + transformers::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) + .attach_printable("Failed to parse Chargebee invoice webhook body")?; + + let chargebee_mit_data = transformers::ChargebeeMitPaymentData::try_from(webhook_body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) + .attach_printable("Failed to extract MIT payment data from Chargebee webhook")?; + + // Convert Chargebee-specific data to generic domain model + Ok( + hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData { + invoice_id: chargebee_mit_data.invoice_id, + amount_due: chargebee_mit_data.amount_due, + currency_code: chargebee_mit_data.currency_code, + status: chargebee_mit_data.status.map(|s| s.into()), + customer_id: chargebee_mit_data.customer_id, + subscription_id: chargebee_mit_data.subscription_id, + first_invoice: chargebee_mit_data.first_invoice, + }, + ) + } } static CHARGEBEE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 64d9431c195..4c7b135f1a2 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -5,7 +5,7 @@ use common_enums::{connector_enums, enums}; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, - id_type::{CustomerId, SubscriptionId}, + id_type::{CustomerId, InvoiceId, SubscriptionId}, pii::{self, Email}, types::MinorUnit, }; @@ -461,17 +461,21 @@ pub enum ChargebeeEventType { PaymentSucceeded, PaymentFailed, InvoiceDeleted, + InvoiceGenerated, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ChargebeeInvoiceData { // invoice id - pub id: String, + pub id: InvoiceId, pub total: MinorUnit, pub currency_code: enums::Currency, pub status: Option<ChargebeeInvoiceStatus>, pub billing_address: Option<ChargebeeInvoiceBillingAddress>, pub linked_payments: Option<Vec<ChargebeeInvoicePayments>>, + pub customer_id: CustomerId, + pub subscription_id: SubscriptionId, + pub first_invoice: Option<bool>, } #[derive(Serialize, Deserialize, Clone, Debug)] @@ -585,7 +589,35 @@ impl ChargebeeInvoiceBody { Ok(webhook_body) } } +// Structure to extract MIT payment data from invoice_generated webhook +#[derive(Debug, Clone)] +pub struct ChargebeeMitPaymentData { + pub invoice_id: InvoiceId, + pub amount_due: MinorUnit, + pub currency_code: enums::Currency, + pub status: Option<ChargebeeInvoiceStatus>, + pub customer_id: CustomerId, + pub subscription_id: SubscriptionId, + pub first_invoice: bool, +} + +impl TryFrom<ChargebeeInvoiceBody> for ChargebeeMitPaymentData { + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from(webhook_body: ChargebeeInvoiceBody) -> Result<Self, Self::Error> { + let invoice = webhook_body.content.invoice; + Ok(Self { + invoice_id: invoice.id, + amount_due: invoice.total, + currency_code: invoice.currency_code, + status: invoice.status, + customer_id: invoice.customer_id, + subscription_id: invoice.subscription_id, + first_invoice: invoice.first_invoice.unwrap_or(false), + }) + } +} pub struct ChargebeeMandateDetails { pub customer_id: String, pub mandate_id: String, @@ -620,9 +652,10 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD fn try_from(item: ChargebeeWebhookBody) -> Result<Self, Self::Error> { let amount = item.content.transaction.amount; let currency = item.content.transaction.currency_code.to_owned(); - let merchant_reference_id = - common_utils::id_type::PaymentReferenceId::from_str(&item.content.invoice.id) - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let merchant_reference_id = common_utils::id_type::PaymentReferenceId::from_str( + item.content.invoice.id.get_string_repr(), + ) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let connector_transaction_id = item .content .transaction @@ -746,6 +779,19 @@ impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent { ChargebeeEventType::PaymentSucceeded => Self::RecoveryPaymentSuccess, ChargebeeEventType::PaymentFailed => Self::RecoveryPaymentFailure, ChargebeeEventType::InvoiceDeleted => Self::RecoveryInvoiceCancel, + ChargebeeEventType::InvoiceGenerated => Self::InvoiceGenerated, + } + } +} + +#[cfg(feature = "v1")] +impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent { + fn from(event: ChargebeeEventType) -> Self { + match event { + ChargebeeEventType::PaymentSucceeded => Self::PaymentIntentSuccess, + ChargebeeEventType::PaymentFailed => Self::PaymentIntentFailure, + ChargebeeEventType::InvoiceDeleted => Self::EventNotSupported, + ChargebeeEventType::InvoiceGenerated => Self::InvoiceGenerated, } } } @@ -754,9 +800,10 @@ impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent { impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: ChargebeeInvoiceBody) -> Result<Self, Self::Error> { - let merchant_reference_id = - common_utils::id_type::PaymentReferenceId::from_str(&item.content.invoice.id) - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let merchant_reference_id = common_utils::id_type::PaymentReferenceId::from_str( + item.content.invoice.id.get_string_repr(), + ) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; // The retry count will never exceed u16 limit in a billing connector. It can have maximum of 12 in case of charge bee so its ok to suppress this #[allow(clippy::as_conversions)] diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs index ac4e8388956..fcb94c9c5ab 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs @@ -1,3 +1,4 @@ +use common_enums::connector_enums::InvoiceStatus; #[derive(Debug, Clone)] pub struct SubscriptionCreate; #[derive(Debug, Clone)] @@ -8,3 +9,15 @@ pub struct GetSubscriptionPlanPrices; #[derive(Debug, Clone)] pub struct GetSubscriptionEstimate; + +/// Generic structure for subscription MIT (Merchant Initiated Transaction) payment data +#[derive(Debug, Clone)] +pub struct SubscriptionMitPaymentData { + pub invoice_id: common_utils::id_type::InvoiceId, + pub amount_due: common_utils::types::MinorUnit, + pub currency_code: common_enums::enums::Currency, + pub status: Option<InvoiceStatus>, + pub customer_id: common_utils::id_type::CustomerId, + pub subscription_id: common_utils::id_type::SubscriptionId, + pub first_invoice: bool, +} diff --git a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs index e60b7783cb5..3da78e63beb 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs @@ -16,7 +16,7 @@ pub struct SubscriptionCreateResponse { #[derive(Debug, Clone, serde::Serialize)] pub struct SubscriptionInvoiceData { - pub id: String, + pub id: id_type::InvoiceId, pub total: MinorUnit, pub currency_code: Currency, pub status: Option<common_enums::connector_enums::InvoiceStatus>, diff --git a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs index 47ead156e2d..a876258f39f 100644 --- a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs +++ b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs @@ -416,6 +416,18 @@ impl IncomingWebhook for ConnectorEnum { Self::New(connector) => connector.get_revenue_recovery_attempt_details(request), } } + fn get_subscription_mit_payment_data( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData, + errors::ConnectorError, + > { + match self { + Self::Old(connector) => connector.get_subscription_mit_payment_data(request), + Self::New(connector) => connector.get_subscription_mit_payment_data(request), + } + } } impl ConnectorRedirectResponse for ConnectorEnum { diff --git a/crates/hyperswitch_interfaces/src/webhooks.rs b/crates/hyperswitch_interfaces/src/webhooks.rs index 3c7e3c04c30..7204330d6d5 100644 --- a/crates/hyperswitch_interfaces/src/webhooks.rs +++ b/crates/hyperswitch_interfaces/src/webhooks.rs @@ -301,4 +301,18 @@ pub trait IncomingWebhook: ConnectorCommon + Sync { ) .into()) } + + /// get subscription MIT payment data from webhook + fn get_subscription_mit_payment_data( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData, + errors::ConnectorError, + > { + Err(errors::ConnectorError::NotImplemented( + "get_subscription_mit_payment_data method".to_string(), + ) + .into()) + } } diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 71e32c43bf6..5c53a60c5d7 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -42,7 +42,7 @@ pub async fn create_subscription( let billing_handler = BillingHandler::create(&state, &merchant_context, customer, profile.clone()).await?; - let subscription_handler = SubscriptionHandler::new(&state, &merchant_context, profile); + let subscription_handler = SubscriptionHandler::new(&state, &merchant_context); let mut subscription = subscription_handler .create_subscription_entry( subscription_id, @@ -50,10 +50,11 @@ pub async fn create_subscription( billing_handler.connector_data.connector_name, billing_handler.merchant_connector_id.clone(), request.merchant_reference_id.clone(), + &profile.clone(), ) .await .attach_printable("subscriptions: failed to create subscription entry")?; - let invoice_handler = subscription.get_invoice_handler(); + let invoice_handler = subscription.get_invoice_handler(profile.clone()); let payment = invoice_handler .create_payment_with_confirm_false(subscription.handler.state, &request) .await @@ -107,7 +108,7 @@ pub async fn create_and_confirm_subscription( let billing_handler = BillingHandler::create(&state, &merchant_context, customer, profile.clone()).await?; - let subscription_handler = SubscriptionHandler::new(&state, &merchant_context, profile.clone()); + let subscription_handler = SubscriptionHandler::new(&state, &merchant_context); let mut subs_handler = subscription_handler .create_subscription_entry( subscription_id.clone(), @@ -115,10 +116,11 @@ pub async fn create_and_confirm_subscription( billing_handler.connector_data.connector_name, billing_handler.merchant_connector_id.clone(), request.merchant_reference_id.clone(), + &profile.clone(), ) .await .attach_printable("subscriptions: failed to create subscription entry")?; - let invoice_handler = subs_handler.get_invoice_handler(); + let invoice_handler = subs_handler.get_invoice_handler(profile.clone()); let _customer_create_response = billing_handler .create_customer_on_connector( @@ -210,9 +212,9 @@ pub async fn confirm_subscription( .await .attach_printable("subscriptions: failed to find customer")?; - let handler = SubscriptionHandler::new(&state, &merchant_context, profile.clone()); + let handler = SubscriptionHandler::new(&state, &merchant_context); let mut subscription_entry = handler.find_subscription(subscription_id).await?; - let invoice_handler = subscription_entry.get_invoice_handler(); + let invoice_handler = subscription_entry.get_invoice_handler(profile.clone()); let invoice = invoice_handler .get_latest_invoice(&state) .await @@ -230,8 +232,8 @@ pub async fn confirm_subscription( .await?; let billing_handler = - BillingHandler::create(&state, &merchant_context, customer, profile).await?; - let invoice_handler = subscription_entry.get_invoice_handler(); + BillingHandler::create(&state, &merchant_context, customer, profile.clone()).await?; + let invoice_handler = subscription_entry.get_invoice_handler(profile); let subscription = subscription_entry.subscription.clone(); let _customer_create_response = billing_handler @@ -296,13 +298,13 @@ pub async fn get_subscription( profile_id: common_utils::id_type::ProfileId, subscription_id: common_utils::id_type::SubscriptionId, ) -> RouterResponse<SubscriptionResponse> { - let profile = + let _profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable( "subscriptions: failed to find business profile in get_subscription", )?; - let handler = SubscriptionHandler::new(&state, &merchant_context, profile); + let handler = SubscriptionHandler::new(&state, &merchant_context); let subscription = handler .find_subscription(subscription_id) .await diff --git a/crates/router/src/core/subscription/subscription_handler.rs b/crates/router/src/core/subscription/subscription_handler.rs index 25259a47696..24c08313b82 100644 --- a/crates/router/src/core/subscription/subscription_handler.rs +++ b/crates/router/src/core/subscription/subscription_handler.rs @@ -14,24 +14,23 @@ use hyperswitch_domain_models::{ use masking::Secret; use super::errors; -use crate::{core::subscription::invoice_handler::InvoiceHandler, routes::SessionState}; +use crate::{ + core::{errors::StorageErrorExt, subscription::invoice_handler::InvoiceHandler}, + db::CustomResult, + routes::SessionState, + types::domain, +}; pub struct SubscriptionHandler<'a> { pub state: &'a SessionState, pub merchant_context: &'a MerchantContext, - pub profile: hyperswitch_domain_models::business_profile::Profile, } impl<'a> SubscriptionHandler<'a> { - pub fn new( - state: &'a SessionState, - merchant_context: &'a MerchantContext, - profile: hyperswitch_domain_models::business_profile::Profile, - ) -> Self { + pub fn new(state: &'a SessionState, merchant_context: &'a MerchantContext) -> Self { Self { state, merchant_context, - profile, } } @@ -43,6 +42,7 @@ impl<'a> SubscriptionHandler<'a> { billing_processor: connector_enums::Connector, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, merchant_reference_id: Option<String>, + profile: &hyperswitch_domain_models::business_profile::Profile, ) -> errors::RouterResult<SubscriptionWithHandler<'_>> { let store = self.state.store.clone(); let db = store.as_ref(); @@ -61,7 +61,7 @@ impl<'a> SubscriptionHandler<'a> { .clone(), customer_id.clone(), None, - self.profile.get_id().clone(), + profile.get_id().clone(), merchant_reference_id, ); @@ -76,7 +76,6 @@ impl<'a> SubscriptionHandler<'a> { Ok(SubscriptionWithHandler { handler: self, subscription: new_subscription, - profile: self.profile.clone(), merchant_account: self.merchant_context.get_merchant_account().clone(), }) } @@ -145,7 +144,6 @@ impl<'a> SubscriptionHandler<'a> { Ok(SubscriptionWithHandler { handler: self, subscription, - profile: self.profile.clone(), merchant_account: self.merchant_context.get_merchant_account().clone(), }) } @@ -153,7 +151,6 @@ impl<'a> SubscriptionHandler<'a> { pub struct SubscriptionWithHandler<'a> { pub handler: &'a SubscriptionHandler<'a>, pub subscription: diesel_models::subscription::Subscription, - pub profile: hyperswitch_domain_models::business_profile::Profile, pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, } @@ -237,11 +234,83 @@ impl SubscriptionWithHandler<'_> { Ok(()) } - pub fn get_invoice_handler(&self) -> InvoiceHandler { + pub fn get_invoice_handler( + &self, + profile: hyperswitch_domain_models::business_profile::Profile, + ) -> InvoiceHandler { InvoiceHandler { subscription: self.subscription.clone(), merchant_account: self.merchant_account.clone(), - profile: self.profile.clone(), + profile, + } + } + pub async fn get_mca( + &mut self, + connector_name: &str, + ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = self.handler.state.store.as_ref(); + let key_manager_state = &(self.handler.state).into(); + + match &self.subscription.merchant_connector_id { + Some(merchant_connector_id) => { + #[cfg(feature = "v1")] + { + db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, + self.handler + .merchant_context + .get_merchant_account() + .get_id(), + merchant_connector_id, + self.handler.merchant_context.get_merchant_key_store(), + ) + .await + .to_not_found_response( + errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_connector_id.get_string_repr().to_string(), + }, + ) + } + #[cfg(feature = "v2")] + { + //get mca using id + let _ = key_manager_state; + let _ = connector_name; + let _ = merchant_context.get_merchant_key_store(); + let _ = subscription.profile_id; + todo!() + } + } + None => { + // Fallback to profile-based lookup when merchant_connector_id is not set + #[cfg(feature = "v1")] + { + db.find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, + &self.subscription.profile_id, + connector_name, + self.handler.merchant_context.get_merchant_key_store(), + ) + .await + .to_not_found_response( + errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: format!( + "profile_id {} and connector_name {connector_name}", + self.subscription.profile_id.get_string_repr() + ), + }, + ) + } + #[cfg(feature = "v2")] + { + //get mca using id + let _ = key_manager_state; + let _ = connector_name; + let _ = self.handler.merchant_context.get_merchant_key_store(); + let _ = self.subscription.profile_id; + todo!() + } + } } } } diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index d1203cd1a34..f207c243d26 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -3,7 +3,11 @@ use std::{str::FromStr, time::Instant}; use actix_web::FromRequest; #[cfg(feature = "payouts")] use api_models::payouts as payout_models; -use api_models::webhooks::{self, WebhookResponseTracker}; +use api_models::{ + enums::Connector, + webhooks::{self, WebhookResponseTracker}, +}; +pub use common_enums::{connector_enums::InvoiceStatus, enums::ProcessTrackerRunner}; use common_utils::{ errors::ReportSwitchExt, events::ApiEventsType, @@ -30,7 +34,9 @@ use crate::{ errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payment_methods, payments::{self, tokenization}, - refunds, relay, unified_connector_service, utils as core_utils, + refunds, relay, + subscription::subscription_handler::SubscriptionHandler, + unified_connector_service, utils as core_utils, webhooks::{network_tokenization_incoming, utils::construct_webhook_router_data}, }, db::StorageInterface, @@ -253,6 +259,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( &request_details, merchant_context.get_merchant_account().get_id(), merchant_connector_account + .clone() .and_then(|mca| mca.connector_webhook_details.clone()), &connector_name, ) @@ -342,6 +349,11 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( &webhook_processing_result.transform_data, &final_request_details, is_relay_webhook, + merchant_connector_account + .ok_or(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: connector_name_or_mca_id.to_string(), + })? + .merchant_connector_id, ) .await; @@ -524,12 +536,13 @@ async fn process_webhook_business_logic( webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>, request_details: &IncomingWebhookRequestDetails<'_>, is_relay_webhook: bool, + billing_connector_mca_id: common_utils::id_type::MerchantConnectorAccountId, ) -> errors::RouterResult<WebhookResponseTracker> { let object_ref_id = connector .get_webhook_object_reference_id(request_details) .switch() .attach_printable("Could not find object reference id in incoming webhook body")?; - let connector_enum = api_models::enums::Connector::from_str(connector_name) + let connector_enum = Connector::from_str(connector_name) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) @@ -814,6 +827,21 @@ async fn process_webhook_business_logic( .await .attach_printable("Incoming webhook flow for payouts failed"), + api::WebhookFlow::Subscription => Box::pin(subscription_incoming_webhook_flow( + state.clone(), + req_state, + merchant_context.clone(), + business_profile, + webhook_details, + source_verified, + connector, + request_details, + event_type, + billing_connector_mca_id, + )) + .await + .attach_printable("Incoming webhook flow for subscription failed"), + _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unsupported Flow Type received in incoming webhooks"), } @@ -845,7 +873,7 @@ fn handle_incoming_webhook_error( logger::error!(?error, "Incoming webhook flow failed"); // fetch the connector enum from the connector name - let connector_enum = api_models::connector_enums::Connector::from_str(connector_name) + let connector_enum = Connector::from_str(connector_name) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) @@ -2533,3 +2561,92 @@ fn insert_mandate_details( )?; Ok(connector_mandate_details) } + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +async fn subscription_incoming_webhook_flow( + state: SessionState, + _req_state: ReqState, + merchant_context: domain::MerchantContext, + business_profile: domain::Profile, + _webhook_details: api::IncomingWebhookDetails, + source_verified: bool, + connector_enum: &ConnectorEnum, + request_details: &IncomingWebhookRequestDetails<'_>, + event_type: webhooks::IncomingWebhookEvent, + billing_connector_mca_id: common_utils::id_type::MerchantConnectorAccountId, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + // Only process invoice_generated events for MIT payments + if event_type != webhooks::IncomingWebhookEvent::InvoiceGenerated { + return Ok(WebhookResponseTracker::NoEffect); + } + + if !source_verified { + logger::error!("Webhook source verification failed for subscription webhook flow"); + return Err(report!( + errors::ApiErrorResponse::WebhookAuthenticationFailed + )); + } + + let connector_name = connector_enum.id().to_string(); + + let connector = Connector::from_str(&connector_name) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) + .attach_printable_lazy(|| format!("unable to parse connector name {connector_name}"))?; + + let mit_payment_data = connector_enum + .get_subscription_mit_payment_data(request_details) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("Failed to extract MIT payment data from subscription webhook")?; + + if mit_payment_data.first_invoice { + return Ok(WebhookResponseTracker::NoEffect); + } + + let profile_id = business_profile.get_id().clone(); + + let profile = + SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) + .await + .attach_printable( + "subscriptions: failed to find business profile in get_subscription", + )?; + + let handler = SubscriptionHandler::new(&state, &merchant_context); + + let subscription_id = mit_payment_data.subscription_id.clone(); + + let subscription_with_handler = handler + .find_subscription(subscription_id) + .await + .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?; + + let invoice_handler = subscription_with_handler.get_invoice_handler(profile); + + let payment_method_id = subscription_with_handler + .subscription + .payment_method_id + .clone() + .ok_or(errors::ApiErrorResponse::GenericNotFoundError { + message: "No payment method found for subscription".to_string(), + }) + .attach_printable("No payment method found for subscription")?; + + logger::info!("Payment method ID found: {}", payment_method_id); + + let _invoice_new = invoice_handler + .create_invoice_entry( + &state, + billing_connector_mca_id.clone(), + None, + mit_payment_data.amount_due, + mit_payment_data.currency_code, + InvoiceStatus::PaymentPending, + connector, + None, + ) + .await?; + + Ok(WebhookResponseTracker::NoEffect) +} diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index fab407e4161..4a8ce622255 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -1456,6 +1456,7 @@ impl RecoveryAction { | webhooks::IncomingWebhookEvent::PayoutCreated | webhooks::IncomingWebhookEvent::PayoutExpired | webhooks::IncomingWebhookEvent::PayoutReversed + | webhooks::IncomingWebhookEvent::InvoiceGenerated | webhooks::IncomingWebhookEvent::SetupWebhook => { common_types::payments::RecoveryAction::InvalidAction } diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 71f1ed404b2..123d723e566 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -44,6 +44,8 @@ use serde_json::Value; use tracing_futures::Instrument; pub use self::ext_traits::{OptionExt, ValidateCall}; +#[cfg(feature = "v1")] +use crate::core::subscription::subscription_handler::SubscriptionHandler; use crate::{ consts, core::{ @@ -459,7 +461,6 @@ pub async fn get_mca_from_payment_intent( } } } - #[cfg(feature = "payouts")] pub async fn get_mca_from_payout_attempt( state: &SessionState, @@ -639,6 +640,22 @@ pub async fn get_mca_from_object_reference_id( ) .await } + webhooks::ObjectReferenceId::SubscriptionId(subscription_id_type) => { + #[cfg(feature = "v1")] + { + let subscription_handler = SubscriptionHandler::new(state, merchant_context); + let mut subscription_with_handler = subscription_handler + .find_subscription(subscription_id_type) + .await?; + + subscription_with_handler.get_mca(connector_name).await + } + #[cfg(feature = "v2")] + { + let _db = db; + todo!() + } + } #[cfg(feature = "payouts")] webhooks::ObjectReferenceId::PayoutId(payout_id_type) => { get_mca_from_payout_attempt(state, merchant_context, payout_id_type, connector_name)
2025-09-16T09:35:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pr adds support for the invoice-generated event type for the incoming webhook for Chargebee and creates a process tracker entry that will trigger a S2S call and invoice sync. ### 1. __Invoice Generated Webhook Support__ - Implements handling for Chargebee's `invoice_generated` webhook event - Creates process tracker entries for subscription workflow management - Added SubscriptionId to ObjectReferenceId for subscription webhook - Created a get_mca_from_subscription_id function to fetch the MerchantConnectorAccount from the SubscriptionId ### 2. __Subscription Workflow Integration__ - Adds subscription workflow tracking data - Implements process tracker integration for subscription events ### 3. __Database Changes__ - Insert details into the invoice table ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Insert into subscription table ``` INSERT INTO public.subscription ( id, status, billing_processor, payment_method_id, merchant_connector_id, client_secret, connector_subscription_id, merchant_id, customer_id, metadata, created_at, modified_at, profile_id, merchant_reference_id ) VALUES ( '169vD0Uxi8JB746e', 'active', 'chargebee', 'pm_98765', 'mca_YH3XxYGMv6IbKD0icBie', 'secret_subs_1231abcd', '169vD0Uxi8JB746e', 'merchant_1758710612', 'gaurav_test', '{"plan":"basic","trial":true}', NOW(), NOW(), 'pro_RkLiGcSuaRjmxA5suSfV', 'ref_subs_1231abcd' ); ``` incoming webhook for chargebee ``` curl --location 'http://localhost:8080/webhooks/merchant_1758710612/mca_YH3XxYGMv6IbKD0icBie' \ --header 'api-key: dev_5LNrrMNqyyFle8hvMssLob9pFq6OIEh0Vl3DqZttFXiDe7wrrScUePEYrIiYfSKT' \ --header 'Content-Type: application/json' \ --header 'authorization: Basic aHlwZXJzd2l0Y2g6aHlwZXJzd2l0Y2g=' \ --data-raw '{ "api_version": "v2", "content": { "invoice": { "adjustment_credit_notes": [], "amount_adjusted": 0, "amount_due": 14100, "amount_paid": 0, "amount_to_collect": 14100, "applied_credits": [], "base_currency_code": "INR", "channel": "web", "credits_applied": 0, "currency_code": "INR", "customer_id": "gaurav_test", "date": 1758711043, "deleted": false, "due_date": 1758711043, "dunning_attempts": [], "exchange_rate": 1.0, "first_invoice": false, "generated_at": 1758711043, "has_advance_charges": false, "id": "3", "is_gifted": false, "issued_credit_notes": [], "line_items": [ { "amount": 14100, "customer_id": "gaurav_test", "date_from": 1758711043, "date_to": 1761303043, "description": "Enterprise Suite Monthly", "discount_amount": 0, "entity_id": "cbdemo_enterprise-suite-monthly", "entity_type": "plan_item_price", "id": "li_169vD0Uxi8JBp46g", "is_taxed": false, "item_level_discount_amount": 0, "object": "line_item", "pricing_model": "flat_fee", "quantity": 1, "subscription_id": "169vD0Uxi8JB746e", "tax_amount": 0, "tax_exempt_reason": "tax_not_configured", "unit_amount": 14100 } ], "linked_orders": [], "linked_payments": [], "net_term_days": 0, "new_sales_amount": 14100, "object": "invoice", "price_type": "tax_exclusive", "recurring": true, "reference_transactions": [], "resource_version": 1758711043846, "round_off_amount": 0, "site_details_at_creation": { "timezone": "Asia/Calcutta" }, "status": "payment_due", "sub_total": 14100, "subscription_id": "169vD0Uxi8JB746e", "tax": 0, "term_finalized": true, "total": 14100, "updated_at": 1758711043, "write_off_amount": 0 } }, "event_type": "invoice_generated", "id": "ev_169vD0Uxi8JDf46i", "object": "event", "occurred_at": 1758711043, "source": "admin_console", "user": "[email protected]", "webhook_status": "scheduled", "webhooks": [ { "id": "whv2_169mYOUxi3nvkZ8v", "object": "webhook", "webhook_status": "scheduled" } ] }' ``` response 200 ok <img width="2551" height="555" alt="image" src="https://github.com/user-attachments/assets/29c9f075-cbb6-4a3d-ace0-cee8a884644a" /> db entry into invoice table <img width="578" height="449" alt="image" src="https://github.com/user-attachments/assets/23614dcf-70fc-480b-9922-0d5645e1d333" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c611b8145596e61d0f1aad8ec9a0f7f2f83b4ae6
juspay/hyperswitch
juspay__hyperswitch-9343
Bug: Add invoice table in hyperswitch
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 9991ba8a27e..89d2ed7d89c 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -875,3 +875,16 @@ impl TryFrom<Connector> for RoutableConnectors { } } } + +// Enum representing different status an invoice can have. +#[derive(Debug, Clone, PartialEq, Eq, strum::Display, strum::EnumString)] +pub enum InvoiceStatus { + InvoiceCreated, + PaymentPending, + PaymentPendingTimeout, + PaymentSucceeded, + PaymentFailed, + PaymentCanceled, + InvoicePaid, + ManualReview, +} diff --git a/crates/diesel_models/src/invoice.rs b/crates/diesel_models/src/invoice.rs new file mode 100644 index 00000000000..24534629307 --- /dev/null +++ b/crates/diesel_models/src/invoice.rs @@ -0,0 +1,108 @@ +use common_enums::connector_enums::{Connector, InvoiceStatus}; +use common_utils::{pii::SecretSerdeValue, types::MinorUnit}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; +use serde::{Deserialize, Serialize}; + +use crate::schema::invoice; + +#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] +#[diesel(table_name = invoice, check_for_backend(diesel::pg::Pg))] +pub struct InvoiceNew { + pub id: String, + pub subscription_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_id: common_utils::id_type::ProfileId, + pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + pub payment_intent_id: Option<common_utils::id_type::PaymentId>, + pub payment_method_id: Option<String>, + pub customer_id: common_utils::id_type::CustomerId, + pub amount: MinorUnit, + pub currency: String, + pub status: String, + pub provider_name: Connector, + pub metadata: Option<SecretSerdeValue>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, +} + +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, +)] +#[diesel( + table_name = invoice, + primary_key(id), + check_for_backend(diesel::pg::Pg) +)] +pub struct Invoice { + id: String, + subscription_id: String, + merchant_id: common_utils::id_type::MerchantId, + profile_id: common_utils::id_type::ProfileId, + merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + payment_intent_id: Option<common_utils::id_type::PaymentId>, + payment_method_id: Option<String>, + customer_id: common_utils::id_type::CustomerId, + amount: MinorUnit, + currency: String, + status: String, + provider_name: Connector, + metadata: Option<SecretSerdeValue>, + created_at: time::PrimitiveDateTime, + modified_at: time::PrimitiveDateTime, +} + +#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Deserialize)] +#[diesel(table_name = invoice)] +pub struct InvoiceUpdate { + pub status: Option<String>, + pub payment_method_id: Option<String>, + pub modified_at: time::PrimitiveDateTime, +} + +impl InvoiceNew { + #[allow(clippy::too_many_arguments)] + pub fn new( + id: String, + subscription_id: String, + merchant_id: common_utils::id_type::MerchantId, + profile_id: common_utils::id_type::ProfileId, + merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + payment_intent_id: Option<common_utils::id_type::PaymentId>, + payment_method_id: Option<String>, + customer_id: common_utils::id_type::CustomerId, + amount: MinorUnit, + currency: String, + status: InvoiceStatus, + provider_name: Connector, + metadata: Option<SecretSerdeValue>, + ) -> Self { + let now = common_utils::date_time::now(); + Self { + id, + subscription_id, + merchant_id, + profile_id, + merchant_connector_id, + payment_intent_id, + payment_method_id, + customer_id, + amount, + currency, + status: status.to_string(), + provider_name, + metadata, + created_at: now, + modified_at: now, + } + } +} + +impl InvoiceUpdate { + pub fn new(payment_method_id: Option<String>, status: Option<InvoiceStatus>) -> Self { + Self { + payment_method_id, + status: status.map(|status| status.to_string()), + modified_at: common_utils::date_time::now(), + } + } +} diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index b715134f926..d29eeac41cb 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -24,6 +24,7 @@ pub mod fraud_check; pub mod generic_link; pub mod gsm; pub mod hyperswitch_ai_interaction; +pub mod invoice; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 2dc6c18a1a1..9bf6adc40b2 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -22,6 +22,7 @@ pub mod generic_link; pub mod generics; pub mod gsm; pub mod hyperswitch_ai_interaction; +pub mod invoice; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; diff --git a/crates/diesel_models/src/query/invoice.rs b/crates/diesel_models/src/query/invoice.rs new file mode 100644 index 00000000000..10df8620461 --- /dev/null +++ b/crates/diesel_models/src/query/invoice.rs @@ -0,0 +1,41 @@ +use diesel::{associations::HasTable, ExpressionMethods}; + +use super::generics; +use crate::{ + invoice::{Invoice, InvoiceNew, InvoiceUpdate}, + schema::invoice::dsl, + PgPooledConn, StorageResult, +}; + +impl InvoiceNew { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Invoice> { + generics::generic_insert(conn, self).await + } +} + +impl Invoice { + pub async fn find_invoice_by_id_invoice_id( + conn: &PgPooledConn, + id: String, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::id.eq(id.to_owned()), + ) + .await + } + + pub async fn update_invoice_entry( + conn: &PgPooledConn, + id: String, + invoice_update: InvoiceUpdate, + ) -> StorageResult<Self> { + generics::generic_update_with_unique_predicate_get_result::< + <Self as HasTable>::Table, + _, + _, + _, + >(conn, dsl::id.eq(id.to_owned()), invoice_update) + .await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 36345ef7570..5581856b56d 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -715,6 +715,40 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + invoice (id) { + #[max_length = 64] + id -> Varchar, + #[max_length = 128] + subscription_id -> Varchar, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + profile_id -> Varchar, + #[max_length = 128] + merchant_connector_id -> Varchar, + #[max_length = 64] + payment_intent_id -> Nullable<Varchar>, + #[max_length = 64] + payment_method_id -> Nullable<Varchar>, + #[max_length = 64] + customer_id -> Varchar, + amount -> Int8, + #[max_length = 3] + currency -> Varchar, + #[max_length = 64] + status -> Varchar, + #[max_length = 128] + provider_name -> Varchar, + metadata -> Nullable<Jsonb>, + created_at -> Timestamp, + modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1730,6 +1764,7 @@ diesel::allow_tables_to_appear_in_same_query!( hyperswitch_ai_interaction, hyperswitch_ai_interaction_default, incremental_authorization, + invoice, locker_mock_up, mandate, merchant_account, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index f05b4e460c3..11c23b0169a 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -729,6 +729,40 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + invoice (id) { + #[max_length = 64] + id -> Varchar, + #[max_length = 128] + subscription_id -> Varchar, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + profile_id -> Varchar, + #[max_length = 128] + merchant_connector_id -> Varchar, + #[max_length = 64] + payment_intent_id -> Nullable<Varchar>, + #[max_length = 64] + payment_method_id -> Nullable<Varchar>, + #[max_length = 64] + customer_id -> Varchar, + amount -> Int8, + #[max_length = 3] + currency -> Varchar, + #[max_length = 64] + status -> Varchar, + #[max_length = 128] + provider_name -> Varchar, + metadata -> Nullable<Jsonb>, + created_at -> Timestamp, + modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1685,6 +1719,7 @@ diesel::allow_tables_to_appear_in_same_query!( hyperswitch_ai_interaction, hyperswitch_ai_interaction_default, incremental_authorization, + invoice, locker_mock_up, mandate, merchant_account, diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index ab3b7cba577..e43c12da150 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -21,6 +21,7 @@ pub mod generic_link; pub mod gsm; pub mod health_check; pub mod hyperswitch_ai_interaction; +pub mod invoice; pub mod kafka_store; pub mod locker_mock_up; pub mod mandate; @@ -147,6 +148,7 @@ pub trait StorageInterface: + tokenization::TokenizationInterface + callback_mapper::CallbackMapperInterface + subscription::SubscriptionInterface + + invoice::InvoiceInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/invoice.rs b/crates/router/src/db/invoice.rs new file mode 100644 index 00000000000..850f1c52730 --- /dev/null +++ b/crates/router/src/db/invoice.rs @@ -0,0 +1,126 @@ +use error_stack::report; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait InvoiceInterface { + async fn insert_invoice_entry( + &self, + invoice_new: storage::invoice::InvoiceNew, + ) -> CustomResult<storage::Invoice, errors::StorageError>; + + async fn find_invoice_by_invoice_id( + &self, + invoice_id: String, + ) -> CustomResult<storage::Invoice, errors::StorageError>; + + async fn update_invoice_entry( + &self, + invoice_id: String, + data: storage::invoice::InvoiceUpdate, + ) -> CustomResult<storage::Invoice, errors::StorageError>; +} + +#[async_trait::async_trait] +impl InvoiceInterface for Store { + #[instrument(skip_all)] + async fn insert_invoice_entry( + &self, + invoice_new: storage::invoice::InvoiceNew, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + invoice_new + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn find_invoice_by_invoice_id( + &self, + invoice_id: String, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Invoice::find_invoice_by_id_invoice_id(&conn, invoice_id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn update_invoice_entry( + &self, + invoice_id: String, + data: storage::invoice::InvoiceUpdate, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Invoice::update_invoice_entry(&conn, invoice_id, data) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } +} + +#[async_trait::async_trait] +impl InvoiceInterface for MockDb { + #[instrument(skip_all)] + async fn insert_invoice_entry( + &self, + _invoice_new: storage::invoice::InvoiceNew, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn find_invoice_by_invoice_id( + &self, + _invoice_id: String, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn update_invoice_entry( + &self, + _invoice_id: String, + _data: storage::invoice::InvoiceUpdate, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl InvoiceInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_invoice_entry( + &self, + invoice_new: storage::invoice::InvoiceNew, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + self.diesel_store.insert_invoice_entry(invoice_new).await + } + + #[instrument(skip_all)] + async fn find_invoice_by_invoice_id( + &self, + invoice_id: String, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + self.diesel_store + .find_invoice_by_invoice_id(invoice_id) + .await + } + + #[instrument(skip_all)] + async fn update_invoice_entry( + &self, + invoice_id: String, + data: storage::invoice::InvoiceUpdate, + ) -> CustomResult<storage::Invoice, errors::StorageError> { + self.diesel_store + .update_invoice_entry(invoice_id, data) + .await + } +} diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index e9c26dd30c2..bc5fa611d3e 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -22,6 +22,7 @@ pub mod fraud_check; pub mod generic_link; pub mod gsm; pub mod hyperswitch_ai_interaction; +pub mod invoice; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; @@ -76,9 +77,9 @@ pub use self::{ blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*, capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*, - generic_link::*, gsm::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, - merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, - payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, + generic_link::*, gsm::*, hyperswitch_ai_interaction::*, invoice::*, locker_mock_up::*, + mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*, + payment_link::*, payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, subscription::*, unified_translations::*, user::*, user_authentication_method::*, user_role::*, }; diff --git a/crates/router/src/types/storage/invoice.rs b/crates/router/src/types/storage/invoice.rs new file mode 100644 index 00000000000..ac16c517efd --- /dev/null +++ b/crates/router/src/types/storage/invoice.rs @@ -0,0 +1 @@ +pub use diesel_models::invoice::{Invoice, InvoiceNew, InvoiceUpdate}; diff --git a/migrations/2025-09-10-101514_add_invoice_table/down.sql b/migrations/2025-09-10-101514_add_invoice_table/down.sql new file mode 100644 index 00000000000..fa537f820cc --- /dev/null +++ b/migrations/2025-09-10-101514_add_invoice_table/down.sql @@ -0,0 +1,3 @@ +DROP INDEX IF EXISTS idx_subscription_id; + +DROP TABLE IF EXISTS invoice; diff --git a/migrations/2025-09-10-101514_add_invoice_table/up.sql b/migrations/2025-09-10-101514_add_invoice_table/up.sql new file mode 100644 index 00000000000..4dd8bb3bbf8 --- /dev/null +++ b/migrations/2025-09-10-101514_add_invoice_table/up.sql @@ -0,0 +1,19 @@ +CREATE TABLE invoice ( + id VARCHAR(64) PRIMARY KEY, + subscription_id VARCHAR(128) NOT NULL, + merchant_id VARCHAR(64) NOT NULL, + profile_id VARCHAR(64) NOT NULL, + merchant_connector_id VARCHAR(128) NOT NULL, + payment_intent_id VARCHAR(64) UNIQUE, + payment_method_id VARCHAR(64), + customer_id VARCHAR(64) NOT NULL, + amount BIGINT NOT NULL, + currency VARCHAR(3) NOT NULL, + status VARCHAR(64) NOT NULL, + provider_name VARCHAR(128) NOT NULL, + metadata JSONB, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + modified_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_subscription_id ON invoice (subscription_id);
2025-09-10T10:35:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> <img width="539" height="305" alt="Screenshot 2025-09-18 at 22 35 30" src="https://github.com/user-attachments/assets/6ef6a861-7bb8-459e-9ac2-99791ec94c21" /> ## Description This PR introduces the **`invoice` table** along with supporting models, queries, schema definitions, and storage interfaces. The goal is to enable **subscription billing and payment tracking** by storing invoices linked to merchants, customers, subscriptions, and connectors. ### Key Features - **New `Invoice` table** with fields for subscription, connector, merchant, customer, amount, currency, status, and metadata. - Added **`InvoiceStatus` enum** to represent invoice lifecycle stages (e.g., `PendingPayment`, `PaymentSucceeded`, `InvoicePaid`, etc.). - Implemented **Diesel models**: `InvoiceNew`, `Invoice`, `InvoiceUpdate`. - Added **storage query methods**: - Insert new invoice - Find invoice by ID - Find invoice by merchant + invoice ID - Update invoice entry - Integrated with **router storage interface** (`InvoiceInterface`). - Added **migrations**: - `up.sql`: creates `invoice` table and indexes (`payment_intent_id`, `subscription_id`, `merchant_id + customer_id`). - `down.sql`: drops indexes and table. --- ## Motivation and Context - Provides a foundation for **subscription billing system** in Hyperswitch. - Supports **payment reconciliation and invoice lifecycle tracking**. - Enables robust query and update flows for invoices tied to subscriptions. --- ## Schema Details **Table: `invoice`** - `id` (PK) - `subscription_id` - `connector_subscription_id` - `merchant_id` - `profile_id` - `merchant_connector_id` - `payment_intent_id` (unique) - `payment_method_id` - `customer_id` - `amount` - `currency` - `status` - `provider_name` - `metadata` - `created_at` - `modified_at` **Indexes** - `idx_payment_intent_id` - `idx_subscription_id` - `idx_merchant_customer` --- ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This can't be tested as this is only creation of tables and their respective storage models. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
juspay/hyperswitch
juspay__hyperswitch-9346
Bug: Invoice sync workflow to check psync status and call record back on successful payment
diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs index c0403848b9d..c9cc3acd2ce 100644 --- a/crates/api_models/src/subscription.rs +++ b/crates/api_models/src/subscription.rs @@ -226,6 +226,7 @@ pub struct PaymentResponseData { pub payment_experience: Option<api_enums::PaymentExperience>, pub error_code: Option<String>, pub error_message: Option<String>, + pub payment_method_type: Option<api_enums::PaymentMethodType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionRequest { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 83aeda0dfb0..b1859cc6c28 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -9434,6 +9434,7 @@ pub enum ProcessTrackerRunner { PassiveRecoveryWorkflow, ProcessDisputeWorkflow, DisputeListWorkflow, + InvoiceSyncflow, } #[derive(Debug)] diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index 43773022596..b2d66db1f4b 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -737,16 +737,31 @@ impl ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRe ) -> CustomResult<String, errors::ConnectorError> { let metadata: chargebee::ChargebeeMetadata = utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?; - let url = self - .base_url(connectors) - .to_string() - .replace("{{merchant_endpoint_prefix}}", metadata.site.peek()); + + let site = metadata.site.peek(); + + let mut base = self.base_url(connectors).to_string(); + + base = base.replace("{{merchant_endpoint_prefix}}", site); + base = base.replace("$", site); + + if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') { + return Err(errors::ConnectorError::InvalidConnectorConfig { + config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).", + } + .into()); + } + + if !base.ends_with('/') { + base.push('/'); + } + let invoice_id = req .request .merchant_reference_id .get_string_repr() .to_string(); - Ok(format!("{url}v2/invoices/{invoice_id}/record_payment")) + Ok(format!("{base}v2/invoices/{invoice_id}/record_payment")) } fn get_content_type(&self) -> &'static str { @@ -833,6 +848,7 @@ fn get_chargebee_plans_query_params( } impl api::subscriptions::GetSubscriptionPlansFlow for Chargebee {} +impl api::subscriptions::SubscriptionRecordBackFlow for Chargebee {} impl ConnectorIntegration< diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index bfa9a50a99a..1abc5550311 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -12,7 +12,7 @@ use hyperswitch_domain_models::{ router_data_v2::{ flow_common_types::{ GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, - SubscriptionCreateData, SubscriptionCustomerData, + InvoiceRecordBackData, SubscriptionCreateData, SubscriptionCustomerData, }, UasFlowData, }, @@ -24,9 +24,10 @@ use hyperswitch_domain_models::{ unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, - CreateConnectorCustomer, + CreateConnectorCustomer, InvoiceRecordBack, }, router_request_types::{ + revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, @@ -39,6 +40,7 @@ use hyperswitch_domain_models::{ ConnectorCustomerData, }, router_response_types::{ + revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, @@ -161,6 +163,7 @@ impl impl api::revenue_recovery_v2::RevenueRecoveryV2 for Recurly {} impl api::subscriptions_v2::SubscriptionsV2 for Recurly {} impl api::subscriptions_v2::GetSubscriptionPlansV2 for Recurly {} +impl api::subscriptions_v2::SubscriptionRecordBackV2 for Recurly {} impl api::subscriptions_v2::SubscriptionConnectorCustomerV2 for Recurly {} impl @@ -173,6 +176,16 @@ impl { } +#[cfg(feature = "v1")] +impl + ConnectorIntegrationV2< + InvoiceRecordBack, + InvoiceRecordBackData, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, + > for Recurly +{ +} impl ConnectorIntegrationV2< CreateConnectorCustomer, @@ -385,10 +398,10 @@ impl #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl ConnectorIntegrationV2< - recovery_router_flows::InvoiceRecordBack, - recovery_flow_common_types::InvoiceRecordBackData, - recovery_request_types::InvoiceRecordBackRequest, - recovery_response_types::InvoiceRecordBackResponse, + InvoiceRecordBack, + InvoiceRecordBackData, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, > for Recurly { fn get_headers( diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs index 99d83e4ef82..3bbeabd42d8 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -12,35 +12,35 @@ use common_utils::{ use error_stack::{report, ResultExt}; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::revenue_recovery; +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +use hyperswitch_domain_models::types as recovery_router_data_types; 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}, + revenue_recovery as recovery_router_flows, subscriptions as subscription_flow_types, }, router_request_types::{ + revenue_recovery as recovery_request_types, subscriptions as subscription_request_types, AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{ConnectorInfo, PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + revenue_recovery as recovery_response_types, subscriptions as subscription_response_types, + ConnectorInfo, PaymentsResponseData, RefundsResponseData, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use hyperswitch_domain_models::{ - router_flow_types::revenue_recovery as recovery_router_flows, - router_request_types::revenue_recovery as recovery_request_types, - router_response_types::revenue_recovery as recovery_response_types, - types as recovery_router_data_types, -}; use hyperswitch_interfaces::{ api::{ - self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, - ConnectorValidation, + self, subscriptions as subscriptions_api, ConnectorCommon, ConnectorCommonExt, + ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, @@ -90,6 +90,45 @@ impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, Pay // Not Implemented (R) } +impl subscriptions_api::Subscriptions for Stripebilling {} +impl subscriptions_api::GetSubscriptionPlansFlow for Stripebilling {} +impl subscriptions_api::SubscriptionRecordBackFlow for Stripebilling {} +impl subscriptions_api::SubscriptionCreate for Stripebilling {} +impl + ConnectorIntegration< + subscription_flow_types::GetSubscriptionPlans, + subscription_request_types::GetSubscriptionPlansRequest, + subscription_response_types::GetSubscriptionPlansResponse, + > for Stripebilling +{ +} +impl subscriptions_api::GetSubscriptionPlanPricesFlow for Stripebilling {} +impl + ConnectorIntegration< + subscription_flow_types::GetSubscriptionPlanPrices, + subscription_request_types::GetSubscriptionPlanPricesRequest, + subscription_response_types::GetSubscriptionPlanPricesResponse, + > for Stripebilling +{ +} +impl + ConnectorIntegration< + subscription_flow_types::SubscriptionCreate, + subscription_request_types::SubscriptionCreateRequest, + subscription_response_types::SubscriptionCreateResponse, + > for Stripebilling +{ +} +impl subscriptions_api::GetSubscriptionEstimateFlow for Stripebilling {} +impl + ConnectorIntegration< + subscription_flow_types::GetSubscriptionEstimate, + subscription_request_types::GetSubscriptionEstimateRequest, + subscription_response_types::GetSubscriptionEstimateResponse, + > for Stripebilling +{ +} + impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Stripebilling where Self: ConnectorIntegration<Flow, Request, Response>, @@ -660,6 +699,16 @@ impl } } +#[cfg(feature = "v1")] +impl + ConnectorIntegration< + recovery_router_flows::InvoiceRecordBack, + recovery_request_types::InvoiceRecordBackRequest, + recovery_response_types::InvoiceRecordBackResponse, + > for Stripebilling +{ +} + #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl ConnectorIntegration< diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index b3eb01ba92a..e7e39adaf81 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -8,7 +8,7 @@ use common_enums::{CallConnectorAction, PaymentAction}; use common_utils::errors::CustomResult; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_flow_types::{ - BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, + BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, }; #[cfg(feature = "dummy_connector")] use hyperswitch_domain_models::router_request_types::authentication::{ @@ -17,12 +17,10 @@ use hyperswitch_domain_models::router_request_types::authentication::{ #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_request_types::revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, - InvoiceRecordBackRequest, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, - InvoiceRecordBackResponse, }; use hyperswitch_domain_models::{ router_data::AccessTokenAuthenticationResponse, @@ -43,11 +41,12 @@ use hyperswitch_domain_models::{ webhooks::VerifyWebhookSource, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, - ExternalVaultProxy, ExternalVaultRetrieveFlow, PostAuthenticate, PreAuthenticate, - SubscriptionCreate as SubscriptionCreateFlow, + ExternalVaultProxy, ExternalVaultRetrieveFlow, InvoiceRecordBack, PostAuthenticate, + PreAuthenticate, SubscriptionCreate as SubscriptionCreateFlow, }, router_request_types::{ authentication, + revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, @@ -70,6 +69,7 @@ use hyperswitch_domain_models::{ VerifyWebhookSourceRequestData, }, router_response_types::{ + revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, @@ -139,7 +139,7 @@ use hyperswitch_interfaces::{ revenue_recovery::RevenueRecovery, subscriptions::{ GetSubscriptionEstimateFlow, GetSubscriptionPlanPricesFlow, GetSubscriptionPlansFlow, - SubscriptionCreate, Subscriptions, + SubscriptionCreate, SubscriptionRecordBackFlow, Subscriptions, }, vault::{ ExternalVault, ExternalVaultCreate, ExternalVaultDelete, ExternalVaultInsert, @@ -7186,6 +7186,7 @@ macro_rules! default_imp_for_subscriptions { ($($path:ident::$connector:ident),*) => { $( impl Subscriptions for $path::$connector {} impl GetSubscriptionPlansFlow for $path::$connector {} + impl SubscriptionRecordBackFlow for $path::$connector {} impl SubscriptionCreate for $path::$connector {} impl ConnectorIntegration< @@ -7193,6 +7194,9 @@ macro_rules! default_imp_for_subscriptions { GetSubscriptionPlansRequest, GetSubscriptionPlansResponse > for $path::$connector + {} + impl + ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> for $path::$connector {} impl GetSubscriptionPlanPricesFlow for $path::$connector {} impl @@ -7330,7 +7334,6 @@ default_imp_for_subscriptions!( connectors::Stax, connectors::Stripe, connectors::Square, - connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, @@ -7508,13 +7511,6 @@ default_imp_for_billing_connector_payment_sync!( macro_rules! default_imp_for_revenue_recovery_record_back { ($($path:ident::$connector:ident),*) => { $( impl recovery_traits::RevenueRecoveryRecordBack for $path::$connector {} - impl - ConnectorIntegration< - InvoiceRecordBack, - InvoiceRecordBackRequest, - InvoiceRecordBackResponse - > for $path::$connector - {} )* }; } @@ -9561,6 +9557,9 @@ impl<const T: u8> #[cfg(feature = "dummy_connector")] impl<const T: u8> GetSubscriptionPlansFlow for connectors::DummyConnector<T> {} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> SubscriptionRecordBackFlow for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< @@ -9571,6 +9570,13 @@ impl<const T: u8> { } +#[cfg(all(feature = "dummy_connector", feature = "v1"))] +impl<const T: u8> + ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> + for connectors::DummyConnector<T> +{ +} + #[cfg(feature = "dummy_connector")] impl<const T: u8> SubscriptionCreate for connectors::DummyConnector<T> {} diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs index 245d57064b9..f012c62b8b5 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs @@ -148,7 +148,9 @@ pub struct FilesFlowData { } #[derive(Debug, Clone)] -pub struct InvoiceRecordBackData; +pub struct InvoiceRecordBackData { + pub connector_meta_data: Option<pii::SecretSerdeValue>, +} #[derive(Debug, Clone)] pub struct SubscriptionCustomerData { diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions.rs b/crates/hyperswitch_interfaces/src/api/subscriptions.rs index bea4c4773ea..7f9f4ea827f 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions.rs @@ -1,26 +1,33 @@ //! Subscriptions Interface for V1 -#[cfg(feature = "v1")] + use hyperswitch_domain_models::{ - router_flow_types::subscriptions::SubscriptionCreate as SubscriptionCreateFlow, - router_flow_types::subscriptions::{ - GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + router_flow_types::{ + subscriptions::{ + GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + SubscriptionCreate as SubscriptionCreateFlow, + }, + InvoiceRecordBack, }, - router_request_types::subscriptions::{ - GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, - GetSubscriptionPlansRequest, SubscriptionCreateRequest, + router_request_types::{ + revenue_recovery::InvoiceRecordBackRequest, + subscriptions::{ + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, + }, }, - router_response_types::subscriptions::{ - GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, - GetSubscriptionPlansResponse, SubscriptionCreateResponse, + router_response_types::{ + revenue_recovery::InvoiceRecordBackResponse, + subscriptions::{ + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, + }, }, }; -#[cfg(feature = "v1")] use super::{ payments::ConnectorCustomer as PaymentsConnectorCustomer, ConnectorCommon, ConnectorIntegration, }; -#[cfg(feature = "v1")] /// trait GetSubscriptionPlans for V1 pub trait GetSubscriptionPlansFlow: ConnectorIntegration< @@ -31,7 +38,12 @@ pub trait GetSubscriptionPlansFlow: { } -#[cfg(feature = "v1")] +/// trait SubscriptionRecordBack for V1 +pub trait SubscriptionRecordBackFlow: + ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> +{ +} + /// trait GetSubscriptionPlanPrices for V1 pub trait GetSubscriptionPlanPricesFlow: ConnectorIntegration< @@ -42,14 +54,12 @@ pub trait GetSubscriptionPlanPricesFlow: { } -#[cfg(feature = "v1")] /// trait SubscriptionCreate pub trait SubscriptionCreate: ConnectorIntegration<SubscriptionCreateFlow, SubscriptionCreateRequest, SubscriptionCreateResponse> { } -#[cfg(feature = "v1")] /// trait GetSubscriptionEstimate for V1 pub trait GetSubscriptionEstimateFlow: ConnectorIntegration< @@ -60,37 +70,13 @@ pub trait GetSubscriptionEstimateFlow: { } /// trait Subscriptions -#[cfg(feature = "v1")] pub trait Subscriptions: ConnectorCommon + GetSubscriptionPlansFlow + GetSubscriptionPlanPricesFlow + SubscriptionCreate + PaymentsConnectorCustomer + + SubscriptionRecordBackFlow + GetSubscriptionEstimateFlow { } - -/// trait Subscriptions (disabled when not V1) -#[cfg(not(feature = "v1"))] -pub trait Subscriptions {} - -/// trait GetSubscriptionPlansFlow (disabled when not V1) -#[cfg(not(feature = "v1"))] -pub trait GetSubscriptionPlansFlow {} - -/// trait GetSubscriptionPlanPricesFlow (disabled when not V1) -#[cfg(not(feature = "v1"))] -pub trait GetSubscriptionPlanPricesFlow {} - -#[cfg(not(feature = "v1"))] -/// trait CreateCustomer (disabled when not V1) -pub trait ConnectorCustomer {} - -/// trait SubscriptionCreate -#[cfg(not(feature = "v1"))] -pub trait SubscriptionCreate {} - -/// trait GetSubscriptionEstimateFlow (disabled when not V1) -#[cfg(not(feature = "v1"))] -pub trait GetSubscriptionEstimateFlow {} diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs index 47a8b4484a1..9dd9fa6e064 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs @@ -2,13 +2,18 @@ use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, - SubscriptionCreateData, SubscriptionCustomerData, + InvoiceRecordBackData, SubscriptionCreateData, SubscriptionCustomerData, }, router_flow_types::{ - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, - CreateConnectorCustomer, GetSubscriptionEstimate, + revenue_recovery::InvoiceRecordBack, + subscriptions::{ + GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + SubscriptionCreate, + }, + CreateConnectorCustomer, }, router_request_types::{ + revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, @@ -16,6 +21,7 @@ use hyperswitch_domain_models::{ ConnectorCustomerData, }, router_response_types::{ + revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, @@ -32,6 +38,7 @@ pub trait SubscriptionsV2: + SubscriptionsCreateV2 + SubscriptionConnectorCustomerV2 + GetSubscriptionPlanPricesV2 + + SubscriptionRecordBackV2 + GetSubscriptionEstimateV2 { } @@ -47,7 +54,17 @@ pub trait GetSubscriptionPlansV2: { } -/// trait GetSubscriptionPlans for V2 +/// trait SubscriptionRecordBack for V2 +pub trait SubscriptionRecordBackV2: + ConnectorIntegrationV2< + InvoiceRecordBack, + InvoiceRecordBackData, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, +> +{ +} +/// trait GetSubscriptionPlanPricesV2 for V2 pub trait GetSubscriptionPlanPricesV2: ConnectorIntegrationV2< GetSubscriptionPlanPrices, diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index a1172f160c6..9c5e420e86c 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -808,7 +808,9 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for InvoiceR where Self: Sized, { - let resource_common_data = Self {}; + let resource_common_data = Self { + connector_meta_data: old_router_data.connector_meta_data.clone(), + }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), @@ -825,16 +827,18 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for InvoiceR where Self: Sized, { - let router_data = get_default_router_data( + let Self { + connector_meta_data, + } = new_router_data.resource_common_data; + let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "recovery_record_back", new_router_data.request, new_router_data.response, ); - Ok(RouterData { - connector_auth_type: new_router_data.connector_auth_type.clone(), - ..router_data - }) + router_data.connector_meta_data = connector_meta_data; + router_data.connector_auth_type = new_router_data.connector_auth_type.clone(); + Ok(router_data) } } diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 492c07e5ab9..a442a338c67 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -287,6 +287,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner { storage::ProcessTrackerRunner::DisputeListWorkflow => { Ok(Box::new(workflows::dispute_list::DisputeListWorkflow)) } + storage::ProcessTrackerRunner::InvoiceSyncflow => { + Ok(Box::new(workflows::invoice_sync::InvoiceSyncWorkflow)) + } storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new( workflows::tokenized_data::DeleteTokenizeDataWorkflow, )), diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 3bdc822859f..bf90eb0d8c1 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -1394,7 +1394,9 @@ pub fn construct_invoice_record_back_router_data( let router_data = router_data_v2::RouterDataV2 { flow: PhantomData::<router_flow_types::InvoiceRecordBack>, tenant_id: state.tenant.tenant_id.clone(), - resource_common_data: flow_common_types::InvoiceRecordBackData, + resource_common_data: flow_common_types::InvoiceRecordBackData { + connector_meta_data: None, + }, connector_auth_type: auth_type, request: revenue_recovery_request::InvoiceRecordBackRequest { merchant_reference_id, diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 5c53a60c5d7..7ef35b8c0d1 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -39,8 +39,14 @@ pub async fn create_subscription( SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id) .await .attach_printable("subscriptions: failed to find customer")?; - let billing_handler = - BillingHandler::create(&state, &merchant_context, customer, profile.clone()).await?; + let billing_handler = BillingHandler::create( + &state, + merchant_context.get_merchant_account(), + merchant_context.get_merchant_key_store(), + customer, + profile.clone(), + ) + .await?; let subscription_handler = SubscriptionHandler::new(&state, &merchant_context); let mut subscription = subscription_handler @@ -106,8 +112,14 @@ pub async fn create_and_confirm_subscription( .await .attach_printable("subscriptions: failed to find customer")?; - let billing_handler = - BillingHandler::create(&state, &merchant_context, customer, profile.clone()).await?; + let billing_handler = BillingHandler::create( + &state, + merchant_context.get_merchant_account(), + merchant_context.get_merchant_key_store(), + customer, + profile.clone(), + ) + .await?; let subscription_handler = SubscriptionHandler::new(&state, &merchant_context); let mut subs_handler = subscription_handler .create_subscription_entry( @@ -162,6 +174,7 @@ pub async fn create_and_confirm_subscription( amount, currency, invoice_details + .clone() .and_then(|invoice| invoice.status) .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), billing_handler.connector_data.connector_name, @@ -169,9 +182,20 @@ pub async fn create_and_confirm_subscription( ) .await?; - // invoice_entry - // .create_invoice_record_back_job(&payment_response) - // .await?; + invoice_handler + .create_invoice_sync_job( + &state, + &invoice_entry, + invoice_details + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "invoice_details", + })? + .id + .get_string_repr() + .to_string(), + billing_handler.connector_data.connector_name, + ) + .await?; subs_handler .update_subscription(diesel_models::subscription::SubscriptionUpdate::new( @@ -231,8 +255,14 @@ pub async fn confirm_subscription( ) .await?; - let billing_handler = - BillingHandler::create(&state, &merchant_context, customer, profile.clone()).await?; + let billing_handler = BillingHandler::create( + &state, + merchant_context.get_merchant_account(), + merchant_context.get_merchant_key_store(), + customer, + profile.clone(), + ) + .await?; let invoice_handler = subscription_entry.get_invoice_handler(profile); let subscription = subscription_entry.subscription.clone(); @@ -270,6 +300,22 @@ pub async fn confirm_subscription( ) .await?; + invoice_handler + .create_invoice_sync_job( + &state, + &invoice_entry, + invoice_details + .clone() + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "invoice_details", + })? + .id + .get_string_repr() + .to_string(), + billing_handler.connector_data.connector_name, + ) + .await?; + subscription_entry .update_subscription(diesel_models::subscription::SubscriptionUpdate::new( payment_response.payment_method_id.clone(), diff --git a/crates/router/src/core/subscription/billing_processor_handler.rs b/crates/router/src/core/subscription/billing_processor_handler.rs index 7e0e303f042..4cc8ad31073 100644 --- a/crates/router/src/core/subscription/billing_processor_handler.rs +++ b/crates/router/src/core/subscription/billing_processor_handler.rs @@ -4,12 +4,16 @@ use common_enums::connector_enums; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::ResultExt; use hyperswitch_domain_models::{ - merchant_context::MerchantContext, - router_data_v2::flow_common_types::{SubscriptionCreateData, SubscriptionCustomerData}, - router_request_types::{subscriptions as subscription_request_types, ConnectorCustomerData}, + router_data_v2::flow_common_types::{ + InvoiceRecordBackData, SubscriptionCreateData, SubscriptionCustomerData, + }, + router_request_types::{ + revenue_recovery::InvoiceRecordBackRequest, subscriptions as subscription_request_types, + ConnectorCustomerData, + }, router_response_types::{ - subscriptions as subscription_response_types, ConnectorCustomerResponseData, - PaymentsResponseData, + revenue_recovery::InvoiceRecordBackResponse, subscriptions as subscription_response_types, + ConnectorCustomerResponseData, PaymentsResponseData, }, }; @@ -31,7 +35,8 @@ pub struct BillingHandler { impl BillingHandler { pub async fn create( state: &SessionState, - merchant_context: &MerchantContext, + merchant_account: &hyperswitch_domain_models::merchant_account::MerchantAccount, + key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, customer: hyperswitch_domain_models::customer::Customer, profile: hyperswitch_domain_models::business_profile::Profile, ) -> errors::RouterResult<Self> { @@ -41,9 +46,9 @@ impl BillingHandler { .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &(state).into(), - merchant_context.get_merchant_account().get_id(), + merchant_account.get_id(), &merchant_connector_id, - merchant_context.get_merchant_key_store(), + key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { @@ -213,6 +218,62 @@ impl BillingHandler { .into()), } } + #[allow(clippy::too_many_arguments)] + pub async fn record_back_to_billing_processor( + &self, + state: &SessionState, + invoice_id: String, + payment_id: common_utils::id_type::PaymentId, + payment_status: common_enums::AttemptStatus, + amount: common_utils::types::MinorUnit, + currency: common_enums::Currency, + payment_method_type: Option<common_enums::PaymentMethodType>, + ) -> errors::RouterResult<InvoiceRecordBackResponse> { + let invoice_record_back_req = InvoiceRecordBackRequest { + amount, + currency, + payment_method_type, + attempt_status: payment_status, + merchant_reference_id: common_utils::id_type::PaymentReferenceId::from_str(&invoice_id) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "invoice_id", + })?, + connector_params: self.connector_params.clone(), + connector_transaction_id: Some(common_utils::types::ConnectorTransactionId::TxnId( + payment_id.get_string_repr().to_string(), + )), + }; + + let router_data = self.build_router_data( + state, + invoice_record_back_req, + InvoiceRecordBackData { + connector_meta_data: self.connector_metadata.clone(), + }, + )?; + let connector_integration = self.connector_data.connector.get_connector_integration(); + + let response = self + .call_connector( + state, + router_data, + "invoice record back", + connector_integration, + ) + .await?; + + match response { + Ok(response_data) => Ok(response_data), + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: self.connector_data.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + } + .into()), + } + } async fn call_connector<F, ResourceCommonData, Req, Resp>( &self, diff --git a/crates/router/src/core/subscription/invoice_handler.rs b/crates/router/src/core/subscription/invoice_handler.rs index eae1b9d05c7..3809474acff 100644 --- a/crates/router/src/core/subscription/invoice_handler.rs +++ b/crates/router/src/core/subscription/invoice_handler.rs @@ -9,7 +9,10 @@ use hyperswitch_domain_models::router_response_types::subscriptions as subscript use masking::{PeekInterface, Secret}; use super::errors; -use crate::{core::subscription::payments_api_client, routes::SessionState}; +use crate::{ + core::subscription::payments_api_client, routes::SessionState, types::storage as storage_types, + workflows::invoice_sync as invoice_sync_workflow, +}; pub struct InvoiceHandler { pub subscription: diesel_models::subscription::Subscription, @@ -19,9 +22,20 @@ pub struct InvoiceHandler { #[allow(clippy::todo)] impl InvoiceHandler { + pub fn new( + subscription: diesel_models::subscription::Subscription, + merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, + profile: hyperswitch_domain_models::business_profile::Profile, + ) -> Self { + Self { + subscription, + merchant_account, + profile, + } + } #[allow(clippy::too_many_arguments)] pub async fn create_invoice_entry( - self, + &self, state: &SessionState, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, payment_intent_id: Option<common_utils::id_type::PaymentId>, @@ -204,12 +218,41 @@ impl InvoiceHandler { .attach_printable("invoices: unable to get latest invoice from database") } - pub async fn create_invoice_record_back_job( + pub async fn get_invoice_by_id( + &self, + state: &SessionState, + invoice_id: common_utils::id_type::InvoiceId, + ) -> errors::RouterResult<diesel_models::invoice::Invoice> { + state + .store + .find_invoice_by_invoice_id(invoice_id.get_string_repr().to_string()) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: "Get Invoice by ID".to_string(), + }) + .attach_printable("invoices: unable to get invoice by id from database") + } + + pub async fn create_invoice_sync_job( &self, - // _invoice: &subscription_types::Invoice, - _payment_response: &subscription_types::PaymentResponseData, + state: &SessionState, + invoice: &diesel_models::invoice::Invoice, + connector_invoice_id: String, + connector_name: connector_enums::Connector, ) -> errors::RouterResult<()> { - // Create an invoice job entry based on payment status - todo!("Create an invoice job entry based on payment status") + let request = storage_types::invoice_sync::InvoiceSyncRequest::new( + self.subscription.id.to_owned(), + invoice.id.to_owned(), + self.subscription.merchant_id.to_owned(), + self.subscription.profile_id.to_owned(), + self.subscription.customer_id.to_owned(), + connector_invoice_id, + connector_name, + ); + + invoice_sync_workflow::create_invoice_sync_job(state, request) + .await + .attach_printable("invoices: unable to create invoice sync job in database")?; + Ok(()) } } diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index bc5fa611d3e..5f4c0cd8c6a 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -23,6 +23,7 @@ pub mod generic_link; pub mod gsm; pub mod hyperswitch_ai_interaction; pub mod invoice; +pub mod invoice_sync; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; diff --git a/crates/router/src/types/storage/invoice_sync.rs b/crates/router/src/types/storage/invoice_sync.rs new file mode 100644 index 00000000000..01bbcf17d92 --- /dev/null +++ b/crates/router/src/types/storage/invoice_sync.rs @@ -0,0 +1,113 @@ +use api_models::enums as api_enums; +use common_utils::id_type; +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct InvoiceSyncTrackingData { + pub subscription_id: id_type::SubscriptionId, + pub invoice_id: id_type::InvoiceId, + pub merchant_id: id_type::MerchantId, + pub profile_id: id_type::ProfileId, + pub customer_id: id_type::CustomerId, + pub connector_invoice_id: String, + pub connector_name: api_enums::Connector, // The connector to which the invoice belongs +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct InvoiceSyncRequest { + pub subscription_id: id_type::SubscriptionId, + pub invoice_id: id_type::InvoiceId, + pub merchant_id: id_type::MerchantId, + pub profile_id: id_type::ProfileId, + pub customer_id: id_type::CustomerId, + pub connector_invoice_id: String, + pub connector_name: api_enums::Connector, +} + +impl From<InvoiceSyncRequest> for InvoiceSyncTrackingData { + fn from(item: InvoiceSyncRequest) -> Self { + Self { + subscription_id: item.subscription_id, + invoice_id: item.invoice_id, + merchant_id: item.merchant_id, + profile_id: item.profile_id, + customer_id: item.customer_id, + connector_invoice_id: item.connector_invoice_id, + connector_name: item.connector_name, + } + } +} + +impl InvoiceSyncRequest { + #[allow(clippy::too_many_arguments)] + pub fn new( + subscription_id: id_type::SubscriptionId, + invoice_id: id_type::InvoiceId, + merchant_id: id_type::MerchantId, + profile_id: id_type::ProfileId, + customer_id: id_type::CustomerId, + connector_invoice_id: String, + connector_name: api_enums::Connector, + ) -> Self { + Self { + subscription_id, + invoice_id, + merchant_id, + profile_id, + customer_id, + connector_invoice_id, + connector_name, + } + } +} + +impl InvoiceSyncTrackingData { + #[allow(clippy::too_many_arguments)] + pub fn new( + subscription_id: id_type::SubscriptionId, + invoice_id: id_type::InvoiceId, + merchant_id: id_type::MerchantId, + profile_id: id_type::ProfileId, + customer_id: id_type::CustomerId, + connector_invoice_id: String, + connector_name: api_enums::Connector, + ) -> Self { + Self { + subscription_id, + invoice_id, + merchant_id, + profile_id, + customer_id, + connector_invoice_id, + connector_name, + } + } +} + +#[derive(Debug, Clone)] +pub enum InvoiceSyncPaymentStatus { + PaymentSucceeded, + PaymentProcessing, + PaymentFailed, +} + +impl From<common_enums::IntentStatus> for InvoiceSyncPaymentStatus { + fn from(value: common_enums::IntentStatus) -> Self { + match value { + common_enums::IntentStatus::Succeeded => Self::PaymentSucceeded, + common_enums::IntentStatus::Processing + | common_enums::IntentStatus::RequiresCustomerAction + | common_enums::IntentStatus::RequiresConfirmation + | common_enums::IntentStatus::RequiresPaymentMethod => Self::PaymentProcessing, + _ => Self::PaymentFailed, + } + } +} + +impl From<InvoiceSyncPaymentStatus> for common_enums::connector_enums::InvoiceStatus { + fn from(value: InvoiceSyncPaymentStatus) -> Self { + match value { + InvoiceSyncPaymentStatus::PaymentSucceeded => Self::InvoicePaid, + InvoiceSyncPaymentStatus::PaymentProcessing => Self::PaymentPending, + InvoiceSyncPaymentStatus::PaymentFailed => Self::PaymentFailed, + } + } +} diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs index 2c2410f7449..3c205377afa 100644 --- a/crates/router/src/workflows.rs +++ b/crates/router/src/workflows.rs @@ -15,3 +15,5 @@ pub mod revenue_recovery; pub mod process_dispute; pub mod dispute_list; + +pub mod invoice_sync; diff --git a/crates/router/src/workflows/invoice_sync.rs b/crates/router/src/workflows/invoice_sync.rs new file mode 100644 index 00000000000..83aa45dc840 --- /dev/null +++ b/crates/router/src/workflows/invoice_sync.rs @@ -0,0 +1,436 @@ +#[cfg(feature = "v1")] +use api_models::subscription as subscription_types; +use async_trait::async_trait; +use common_utils::{ + errors::CustomResult, + ext_traits::{StringExt, ValueExt}, +}; +use diesel_models::{ + invoice::Invoice, process_tracker::business_status, subscription::Subscription, +}; +use error_stack::ResultExt; +use router_env::logger; +use scheduler::{ + consumer::{self, workflows::ProcessTrackerWorkflow}, + errors, + types::process_data, + utils as scheduler_utils, +}; + +#[cfg(feature = "v1")] +use crate::core::subscription::{ + billing_processor_handler as billing, invoice_handler, payments_api_client, +}; +use crate::{ + db::StorageInterface, + errors as router_errors, + routes::SessionState, + types::{domain, storage}, +}; + +const INVOICE_SYNC_WORKFLOW: &str = "INVOICE_SYNC"; +const INVOICE_SYNC_WORKFLOW_TAG: &str = "INVOICE"; +pub struct InvoiceSyncWorkflow; + +pub struct InvoiceSyncHandler<'a> { + pub state: &'a SessionState, + pub tracking_data: storage::invoice_sync::InvoiceSyncTrackingData, + pub key_store: domain::MerchantKeyStore, + pub merchant_account: domain::MerchantAccount, + pub customer: domain::Customer, + pub profile: domain::Profile, + pub subscription: Subscription, + pub invoice: Invoice, +} + +#[cfg(feature = "v1")] +impl<'a> InvoiceSyncHandler<'a> { + pub async fn create( + state: &'a SessionState, + tracking_data: storage::invoice_sync::InvoiceSyncTrackingData, + ) -> Result<Self, errors::ProcessTrackerError> { + let key_manager_state = &state.into(); + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &tracking_data.merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .attach_printable("Failed to fetch Merchant key store from DB")?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id( + key_manager_state, + &tracking_data.merchant_id, + &key_store, + ) + .await + .attach_printable("Subscriptions: Failed to fetch Merchant Account from DB")?; + + let profile = state + .store + .find_business_profile_by_profile_id( + &(state).into(), + &key_store, + &tracking_data.profile_id, + ) + .await + .attach_printable("Subscriptions: Failed to fetch Business Profile from DB")?; + + let customer = state + .store + .find_customer_by_customer_id_merchant_id( + &(state).into(), + &tracking_data.customer_id, + merchant_account.get_id(), + &key_store, + merchant_account.storage_scheme, + ) + .await + .attach_printable("Subscriptions: Failed to fetch Customer from DB")?; + + let subscription = state + .store + .find_by_merchant_id_subscription_id( + merchant_account.get_id(), + tracking_data.subscription_id.get_string_repr().to_string(), + ) + .await + .attach_printable("Subscriptions: Failed to fetch subscription from DB")?; + + let invoice = state + .store + .find_invoice_by_invoice_id(tracking_data.invoice_id.get_string_repr().to_string()) + .await + .attach_printable("invoices: unable to get latest invoice from database")?; + + Ok(Self { + state, + tracking_data, + key_store, + merchant_account, + customer, + profile, + subscription, + invoice, + }) + } + + async fn finish_process_with_business_status( + &self, + process: &storage::ProcessTracker, + business_status: &'static str, + ) -> CustomResult<(), router_errors::ApiErrorResponse> { + self.state + .store + .as_scheduler() + .finish_process_with_business_status(process.clone(), business_status) + .await + .change_context(router_errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update process tracker status") + } + + pub async fn perform_payments_sync( + &self, + ) -> CustomResult<subscription_types::PaymentResponseData, router_errors::ApiErrorResponse> + { + let payment_id = self.invoice.payment_intent_id.clone().ok_or( + router_errors::ApiErrorResponse::SubscriptionError { + operation: "Invoice_sync: Missing Payment Intent ID in Invoice".to_string(), + }, + )?; + let payments_response = payments_api_client::PaymentsApiClient::sync_payment( + self.state, + payment_id.get_string_repr().to_string(), + self.merchant_account.get_id().get_string_repr(), + self.profile.get_id().get_string_repr(), + ) + .await + .change_context(router_errors::ApiErrorResponse::SubscriptionError { + operation: "Invoice_sync: Failed to sync payment status from payments microservice" + .to_string(), + }) + .attach_printable("Failed to sync payment status from payments microservice")?; + + Ok(payments_response) + } + + pub async fn perform_billing_processor_record_back( + &self, + payment_response: subscription_types::PaymentResponseData, + payment_status: common_enums::AttemptStatus, + connector_invoice_id: String, + invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus, + ) -> CustomResult<(), router_errors::ApiErrorResponse> { + logger::info!("perform_billing_processor_record_back"); + + let billing_handler = billing::BillingHandler::create( + self.state, + &self.merchant_account, + &self.key_store, + self.customer.clone(), + self.profile.clone(), + ) + .await + .attach_printable("Failed to create billing handler")?; + + let invoice_handler = invoice_handler::InvoiceHandler::new( + self.subscription.clone(), + self.merchant_account.clone(), + self.profile.clone(), + ); + + // TODO: Handle retries here on failure + billing_handler + .record_back_to_billing_processor( + self.state, + connector_invoice_id.clone(), + payment_response.payment_id.to_owned(), + payment_status, + payment_response.amount, + payment_response.currency, + payment_response.payment_method_type, + ) + .await + .attach_printable("Failed to record back to billing processor")?; + + invoice_handler + .update_invoice( + self.state, + self.invoice.id.to_owned(), + None, + common_enums::connector_enums::InvoiceStatus::from(invoice_sync_status), + ) + .await + .attach_printable("Failed to update invoice in DB")?; + + Ok(()) + } + + pub async fn transition_workflow_state( + &self, + process: storage::ProcessTracker, + payment_response: subscription_types::PaymentResponseData, + connector_invoice_id: String, + ) -> CustomResult<(), router_errors::ApiErrorResponse> { + let invoice_sync_status = + storage::invoice_sync::InvoiceSyncPaymentStatus::from(payment_response.status); + match invoice_sync_status { + storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentSucceeded => { + Box::pin(self.perform_billing_processor_record_back( + payment_response, + common_enums::AttemptStatus::Charged, + connector_invoice_id, + invoice_sync_status, + )) + .await + .attach_printable("Failed to record back to billing processor")?; + + self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT) + .await + .change_context(router_errors::ApiErrorResponse::SubscriptionError { + operation: "Invoice_sync process_tracker task completion".to_string(), + }) + .attach_printable("Failed to update process tracker status") + } + storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentProcessing => { + retry_subscription_invoice_sync_task( + &*self.state.store, + self.tracking_data.connector_name.to_string().clone(), + self.merchant_account.get_id().to_owned(), + process, + ) + .await + .change_context(router_errors::ApiErrorResponse::SubscriptionError { + operation: "Invoice_sync process_tracker task retry".to_string(), + }) + .attach_printable("Failed to update process tracker status") + } + storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentFailed => { + Box::pin(self.perform_billing_processor_record_back( + payment_response, + common_enums::AttemptStatus::Failure, + connector_invoice_id, + invoice_sync_status, + )) + .await + .attach_printable("Failed to record back to billing processor")?; + + self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT) + .await + .change_context(router_errors::ApiErrorResponse::SubscriptionError { + operation: "Invoice_sync process_tracker task completion".to_string(), + }) + .attach_printable("Failed to update process tracker status") + } + } + } +} + +#[async_trait] +impl ProcessTrackerWorkflow<SessionState> for InvoiceSyncWorkflow { + #[cfg(feature = "v1")] + async fn execute_workflow<'a>( + &'a self, + state: &'a SessionState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + let tracking_data = process + .tracking_data + .clone() + .parse_value::<storage::invoice_sync::InvoiceSyncTrackingData>( + "InvoiceSyncTrackingData", + )?; + + match process.name.as_deref() { + Some(INVOICE_SYNC_WORKFLOW) => { + Box::pin(perform_subscription_invoice_sync( + state, + process, + tracking_data, + )) + .await + } + _ => Err(errors::ProcessTrackerError::JobNotFound), + } + } + + async fn error_handler<'a>( + &'a self, + state: &'a SessionState, + process: storage::ProcessTracker, + error: errors::ProcessTrackerError, + ) -> CustomResult<(), errors::ProcessTrackerError> { + logger::error!("Encountered error"); + consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await + } + + #[cfg(feature = "v2")] + async fn execute_workflow<'a>( + &'a self, + state: &'a SessionState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + Ok(()) + } +} + +#[cfg(feature = "v1")] +async fn perform_subscription_invoice_sync( + state: &SessionState, + process: storage::ProcessTracker, + tracking_data: storage::invoice_sync::InvoiceSyncTrackingData, +) -> Result<(), errors::ProcessTrackerError> { + let handler = InvoiceSyncHandler::create(state, tracking_data).await?; + + let payment_status = handler.perform_payments_sync().await?; + + Box::pin(handler.transition_workflow_state( + process, + payment_status, + handler.tracking_data.connector_invoice_id.clone(), + )) + .await?; + + Ok(()) +} + +pub async fn create_invoice_sync_job( + state: &SessionState, + request: storage::invoice_sync::InvoiceSyncRequest, +) -> CustomResult<(), router_errors::ApiErrorResponse> { + let tracking_data = storage::invoice_sync::InvoiceSyncTrackingData::from(request); + + let process_tracker_entry = diesel_models::ProcessTrackerNew::new( + common_utils::generate_id(crate::consts::ID_LENGTH, "proc"), + INVOICE_SYNC_WORKFLOW.to_string(), + common_enums::ProcessTrackerRunner::InvoiceSyncflow, + vec![INVOICE_SYNC_WORKFLOW_TAG.to_string()], + tracking_data, + Some(0), + common_utils::date_time::now(), + common_types::consts::API_VERSION, + ) + .change_context(router_errors::ApiErrorResponse::InternalServerError) + .attach_printable("subscriptions: unable to form process_tracker type")?; + + state + .store + .insert_process(process_tracker_entry) + .await + .change_context(router_errors::ApiErrorResponse::InternalServerError) + .attach_printable("subscriptions: unable to insert process_tracker entry in DB")?; + + Ok(()) +} + +pub async fn get_subscription_invoice_sync_process_schedule_time( + db: &dyn StorageInterface, + connector: &str, + merchant_id: &common_utils::id_type::MerchantId, + retry_count: i32, +) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { + let mapping: CustomResult< + process_data::SubscriptionInvoiceSyncPTMapping, + router_errors::StorageError, + > = db + .find_config_by_key(&format!("invoice_sync_pt_mapping_{connector}")) + .await + .map(|value| value.config) + .and_then(|config| { + config + .parse_struct("SubscriptionInvoiceSyncPTMapping") + .change_context(router_errors::StorageError::DeserializationFailed) + .attach_printable("Failed to deserialize invoice_sync_pt_mapping config to struct") + }); + let mapping = match mapping { + Ok(x) => x, + Err(error) => { + logger::info!(?error, "Redis Mapping Error"); + process_data::SubscriptionInvoiceSyncPTMapping::default() + } + }; + + let time_delta = scheduler_utils::get_subscription_invoice_sync_retry_schedule_time( + mapping, + merchant_id, + retry_count, + ); + + Ok(scheduler_utils::get_time_from_delta(time_delta)) +} + +pub async fn retry_subscription_invoice_sync_task( + db: &dyn StorageInterface, + connector: String, + merchant_id: common_utils::id_type::MerchantId, + pt: storage::ProcessTracker, +) -> Result<(), errors::ProcessTrackerError> { + let schedule_time = get_subscription_invoice_sync_process_schedule_time( + db, + connector.as_str(), + &merchant_id, + pt.retry_count + 1, + ) + .await?; + + match schedule_time { + Some(s_time) => { + db.as_scheduler() + .retry_process(pt, s_time) + .await + .attach_printable("Failed to retry subscription invoice sync task")?; + } + None => { + db.as_scheduler() + .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) + .await + .attach_printable("Failed to finish subscription invoice sync task")?; + } + } + + Ok(()) +} diff --git a/crates/scheduler/src/consumer/types/process_data.rs b/crates/scheduler/src/consumer/types/process_data.rs index 26d0fdf7022..6e236e18272 100644 --- a/crates/scheduler/src/consumer/types/process_data.rs +++ b/crates/scheduler/src/consumer/types/process_data.rs @@ -29,6 +29,26 @@ impl Default for ConnectorPTMapping { } } +#[derive(Serialize, Deserialize)] +pub struct SubscriptionInvoiceSyncPTMapping { + pub default_mapping: RetryMapping, + pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, + pub max_retries_count: i32, +} + +impl Default for SubscriptionInvoiceSyncPTMapping { + fn default() -> Self { + Self { + custom_merchant_mapping: HashMap::new(), + default_mapping: RetryMapping { + start_after: 60, + frequencies: vec![(300, 5)], + }, + max_retries_count: 5, + } + } +} + #[derive(Serialize, Deserialize)] pub struct PaymentMethodsPTMapping { pub default_mapping: RetryMapping, diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 58dd0be4da1..0db72a24a1c 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -386,6 +386,23 @@ pub fn get_pcr_payments_retry_schedule_time( } } +pub fn get_subscription_invoice_sync_retry_schedule_time( + mapping: process_data::SubscriptionInvoiceSyncPTMapping, + merchant_id: &common_utils::id_type::MerchantId, + retry_count: i32, +) -> Option<i32> { + let mapping = match mapping.custom_merchant_mapping.get(merchant_id) { + Some(map) => map.clone(), + None => mapping.default_mapping, + }; + + if retry_count == 0 { + Some(mapping.start_after) + } else { + get_delay(retry_count, &mapping.frequencies) + } +} + /// Get the delay based on the retry count pub fn get_delay<'a>( retry_count: i32,
2025-09-23T17:13:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces a comprehensive set of changes to add invoice management capabilities to the codebase. The changes include new data models and enums for invoices, database schema and query support, and integration with connectors and APIs for invoice-related workflows. **Invoice Data Model and Enums** - Added the `InvoiceStatus` enum to represent the various states an invoice can be in, such as `InvoiceCreated`, `PaymentPending`, `PaymentSucceeded`, etc. (`crates/common_enums/src/connector_enums.rs`) - Introduced the `InvoiceRecordBackTrackingData` struct for tracking invoice-related process data, along with a constructor. (`crates/api_models/src/process_tracker/invoice_record_back.rs`) - Created a new `InvoiceId` type and implemented associated methods and traits, including event metric integration. (`crates/common_utils/src/id_type/invoice.rs`) - Registered the new `InvoiceId` in the global ID types and exposed it for use. (`crates/common_utils/src/id_type.rs`) [[1]](diffhunk://#diff-d949a6c528436f8ab1a851147e7467d525cba63b395b253d1dec17101a971fa1R10) [[2]](diffhunk://#diff-d949a6c528436f8ab1a851147e7467d525cba63b395b253d1dec17101a971fa1R51) - Added `Invoice` to the `ApiEventsType` enum for event categorization. (`crates/common_utils/src/events.rs`) - Extended the `ProcessTrackerRunner` enum to include `InvoiceRecordBackflow`. (`crates/common_enums/src/enums.rs`) **Database Schema and Models** - Added a new `invoice` table to the Diesel ORM schema (both v1 and v2), including all necessary fields and indices. (`crates/diesel_models/src/schema.rs`, `crates/diesel_models/src/schema_v2.rs`) [[1]](diffhunk://#diff-b3de56db64ac930fe24b6b0acb45282191598a506d20732f70ef00192b4b18d5R718-R751) [[2]](diffhunk://#diff-b3de56db64ac930fe24b6b0acb45282191598a506d20732f70ef00192b4b18d5R1767) [[3]](diffhunk://#diff-22fdeee3005db31c44a9d40cd43c5a244e77a74e17d2e227d4c0b376f133f37eR732-R765) [[4]](diffhunk://#diff-22fdeee3005db31c44a9d40cd43c5a244e77a74e17d2e227d4c0b376f133f37eR1722) - Implemented the `Invoice`, `InvoiceNew`, and `InvoiceUpdate` structs for ORM mapping, along with constructors and update methods. (`crates/diesel_models/src/invoice.rs`) - Added query support for inserting, finding, and updating invoices in the database. (`crates/diesel_models/src/query/invoice.rs`) - Registered the new `invoice` module in the Diesel models and query modules. (`crates/diesel_models/src/lib.rs`, `crates/diesel_models/src/query.rs`) [[1]](diffhunk://#diff-7eb95277f166342b9ffb08398f8165f1498aa8ecb4ac3b967133e4d682c382a3R27) [[2]](diffhunk://#diff-a8ff468e437001f77b303a9f63b47a6204ffc99b25dd4e9d9a122d5093b69f1cR25) **Connector and API Integration** - Added support for the invoice record backflow in the Chargebee and Recurly connectors, including trait implementations and integration with request/response types. (`crates/hyperswitch_connectors/src/connectors/chargebee.rs`, `crates/hyperswitch_connectors/src/connectors/recurly.rs`) [[1]](diffhunk://#diff-805dd853d554bb072ad3427d6b5ed7dc7b9ed62ee278f5adbf389a08266996b0R688) [[2]](diffhunk://#diff-987be7b07b93a35ac0316f1eb8ad93ece84e5280d37e5566964238d1c969a3fdL12-R34) [[3]](diffhunk://#diff-987be7b07b93a35ac0316f1eb8ad93ece84e5280d37e5566964238d1c969a3fdR151) [[4]](diffhunk://#diff-987be7b07b93a35ac0316f1eb8ad93ece84e5280d37e5566964238d1c969a3fdR162-R171) - Updated the default connector implementations to support the new invoice record backflow and related API flows. (`crates/hyperswitch_connectors/src/default_implementations.rs`) [[1]](diffhunk://#diff-ee28a7003b898fbf15bb25eb102e2310a4c52ba46d3961e3f929f4cf6bd1f6beL46-R51) [[2]](diffhunk://#diff-ee28a7003b898fbf15bb25eb102e2310a4c52ba46d3961e3f929f4cf6bd1f6beL69-R75) [[3]](diffhunk://#diff-ee28a7003b898fbf15bb25eb102e2310a4c52ba46d3961e3f929f4cf6bd1f6beL133-R135) [[4]](diffhunk://#diff-ee28a7003b898fbf15bb25eb102e2310a4c52ba46d3961e3f929f4cf6bd1f6beR6946-R6956) **API Models** - Added a new module for `invoice_record_back` in the process tracker API models. (`crates/api_models/src/process_tracker.rs`) --- **Summary of Most Important Changes:** **Invoice Data Model and Enums** - Introduced the `InvoiceStatus` enum and the `InvoiceRecordBackTrackingData` struct for invoice state tracking and process workflows. [[1]](diffhunk://#diff-6b571cd80816c7f8efa676e546481b145ab156fe1f76b59a69796f218749aeb1R877-R889) [[2]](diffhunk://#diff-0358abeaeb311c146f922f8915a84016820331754f1e8cb6632dd6b48e3e2fceR1-R44) - Added a new `InvoiceId` type with associated methods and event metric integration. [[1]](diffhunk://#diff-dbf2199d67bff928fb938c82846a4e4c84e7fa9e077905ca3273556757f2675bR1-R21) [[2]](diffhunk://#diff-d949a6c528436f8ab1a851147e7467d525cba63b395b253d1dec17101a971fa1R10) [[3]](diffhunk://#diff-d949a6c528436f8ab1a851147e7467d525cba63b395b253d1dec17101a971fa1R51) [[4]](diffhunk://#diff-77f0e8abb88015b6a88d517bd4b0eb801b98ed2ac5a4a0fac5be92d4927ee780R89) - Extended process tracker and event enums for invoice support. [[1]](diffhunk://#diff-955707712c9bdbbd986dc29a9dd001579001580cf0a65e286ac8a2a25a2a49f2R9374) [[2]](diffhunk://#diff-77f0e8abb88015b6a88d517bd4b0eb801b98ed2ac5a4a0fac5be92d4927ee780R89) **Database Schema and Models** - Created a new `invoice` table in the Diesel schema, and implemented corresponding ORM structs and query methods for invoice creation, lookup, and updates. [[1]](diffhunk://#diff-b3de56db64ac930fe24b6b0acb45282191598a506d20732f70ef00192b4b18d5R718-R751) [[2]](diffhunk://#diff-b3de56db64ac930fe24b6b0acb45282191598a506d20732f70ef00192b4b18d5R1767) [[3]](diffhunk://#diff-22fdeee3005db31c44a9d40cd43c5a244e77a74e17d2e227d4c0b376f133f37eR732-R765) [[4]](diffhunk://#diff-22fdeee3005db31c44a9d40cd43c5a244e77a74e17d2e227d4c0b376f133f37eR1722) [[5]](diffhunk://#diff-cc8ce5ad039d65f1b8644286fe6abb6e8fae401fdb8e5f43f3984efdf2803696R1-R108) [[6]](diffhunk://#diff-d2c14bc247ee6cee7d5e45e9e967ff7d1cc3e98b98af02f7e5a4a8c6796f40fbR1-R41) [[7]](diffhunk://#diff-7eb95277f166342b9ffb08398f8165f1498aa8ecb4ac3b967133e4d682c382a3R27) [[8]](diffhunk://#diff-a8ff468e437001f77b303a9f63b47a6204ffc99b25dd4e9d9a122d5093b69f1cR25) **Connector and API Integration** - Added invoice record backflow support to Chargebee and Recurly connectors, and updated default connector implementations for new invoice-related flows. [[1]](diffhunk://#diff-805dd853d554bb072ad3427d6b5ed7dc7b9ed62ee278f5adbf389a08266996b0R688) [[2]](diffhunk://#diff-987be7b07b93a35ac0316f1eb8ad93ece84e5280d37e5566964238d1c969a3fdL12-R34) [[3]](diffhunk://#diff-987be7b07b93a35ac0316f1eb8ad93ece84e5280d37e5566964238d1c969a3fdR151) [[4]](diffhunk://#diff-987be7b07b93a35ac0316f1eb8ad93ece84e5280d37e5566964238d1c969a3fdR162-R171) [[5]](diffhunk://#diff-ee28a7003b898fbf15bb25eb102e2310a4c52ba46d3961e3f929f4cf6bd1f6beL46-R51) [[6]](diffhunk://#diff-ee28a7003b898fbf15bb25eb102e2310a4c52ba46d3961e3f929f4cf6bd1f6beL69-R75) [[7]](diffhunk://#diff-ee28a7003b898fbf15bb25eb102e2310a4c52ba46d3961e3f929f4cf6bd1f6beL133-R135) [[8]](diffhunk://#diff-ee28a7003b898fbf15bb25eb102e2310a4c52ba46d3961e3f929f4cf6bd1f6beR6946-R6956) **API Models** - Registered a new `invoice_record_back` module in the process tracker API models. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create+Confirm subscription ``` curl --location 'http://localhost:8080/subscriptions' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_2WzEeiNyj8fSCObXqo36' \ --header 'api-key: dev_Ske75Nx2J7qtHsP8cc7pFx5k4dccYBedM6UAExaLOdHCkji3uVWSqfmZ0Qz0Tnyj' \ --data '{ "item_price_id": "cbdemo_enterprise-suite-monthly", "customer_id": "cus_27J5gnsyKB4XrzyIxeoS", "description": "Hello this is description", "merchant_reference_id": "mer_ref_1759334677", "shipping": { "address": { "state": "zsaasdas", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "payment_details": { "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "CLBRW dffdg", "card_cvc": "737" } }, "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "capture_method": "automatic", "return_url": "https://google.com", "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" } } } }' ``` Response - ``` {"id":"sub_qHATQ50oyNXU88ATREqE","merchant_reference_id":"mer_ref_1759334677","status":"active","plan_id":null,"price_id":null,"coupon":null,"profile_id":"pro_2WzEeiNyj8fSCObXqo36","payment":{"payment_id":"pay_i25XfiRs8BZhuVuKIMeZ","status":"succeeded","amount":14100,"currency":"INR","connector":"stripe","payment_method_id":"pm_MjezVPJ1fyh70zER6aNW","payment_experience":null,"error_code":null,"error_message":null,"payment_method_type":"credit"},"customer_id":"cus_27J5gnsyKB4XrzyIxeoS","invoice":{"id":"invoice_2xFn2gjrxUshLw0A3FwG","subscription_id":"sub_qHATQ50oyNXU88ATREqE","merchant_id":"merchant_1758626894","profile_id":"pro_2WzEeiNyj8fSCObXqo36","merchant_connector_id":"mca_eN6JxSK2NkuT0wSYAH5s","payment_intent_id":"pay_i25XfiRs8BZhuVuKIMeZ","payment_method_id":null,"customer_id":"cus_27J5gnsyKB4XrzyIxeoS","amount":14100,"currency":"INR","status":"payment_pending"},"billing_processor_subscription_id":"sub_qHATQ50oyNXU88ATREqE"} ``` <img width="927" height="394" alt="image" src="https://github.com/user-attachments/assets/8d7a713a-338c-434e-83e2-d34b83b51b4d" /> <img width="941" height="471" alt="image" src="https://github.com/user-attachments/assets/6caecd07-58ea-4348-b994-a8d4d32385a4" /> <img width="1369" height="939" alt="image" src="https://github.com/user-attachments/assets/0b3981cc-8a9b-44db-b3ed-1843df54a963" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
32dd9e10e3103a906cfef49c7baa117778ea02f3
juspay/hyperswitch
juspay__hyperswitch-9364
Bug: [FEATURE] Add Peachpayments Connector - Cards Flow ### Feature Description Add Peachpayments Connector - Cards Flow ### Possible Implementation Add Peachpayments Connector - Cards Flow ### 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/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 5051b035679..3a7d2f535cc 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -136,7 +136,7 @@ pub enum RoutableConnectors { Paystack, Paytm, Payu, - // Peachpayments, + Peachpayments, Phonepe, Placetopay, Powertranz, @@ -314,7 +314,7 @@ pub enum Connector { Paystack, Paytm, Payu, - // Peachpayments, + Peachpayments, Phonepe, Placetopay, Powertranz, @@ -503,7 +503,7 @@ impl Connector { | Self::Paysafe | Self::Paystack | Self::Payu - // | Self::Peachpayments + | Self::Peachpayments | Self::Placetopay | Self::Powertranz | Self::Prophetpay @@ -683,7 +683,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Paysafe => Self::Paysafe, RoutableConnectors::Paystack => Self::Paystack, RoutableConnectors::Payu => Self::Payu, - // RoutableConnectors::Peachpayments => Self::Peachpayments, + RoutableConnectors::Peachpayments => Self::Peachpayments, RoutableConnectors::Placetopay => Self::Placetopay, RoutableConnectors::Powertranz => Self::Powertranz, RoutableConnectors::Prophetpay => Self::Prophetpay, @@ -818,7 +818,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Paysafe => Ok(Self::Paysafe), Connector::Paystack => Ok(Self::Paystack), Connector::Payu => Ok(Self::Payu), - // Connector::Peachpayments => Ok(Self::Peachpayments), + Connector::Peachpayments => Ok(Self::Peachpayments), Connector::Placetopay => Ok(Self::Placetopay), Connector::Powertranz => Ok(Self::Powertranz), Connector::Prophetpay => Ok(Self::Prophetpay), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 060240873f5..dfede98f1e4 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -486,7 +486,7 @@ impl ConnectorConfig { Connector::Paysafe => Ok(connector_data.paysafe), Connector::Paystack => Ok(connector_data.paystack), Connector::Payu => Ok(connector_data.payu), - // Connector::Peachpayments => Ok(connector_data.peachpayments), + Connector::Peachpayments => Ok(connector_data.peachpayments), Connector::Placetopay => Ok(connector_data.placetopay), Connector::Plaid => Ok(connector_data.plaid), Connector::Powertranz => Ok(connector_data.powertranz), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 8b6b0e875fb..a5de72b6e24 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6841,5 +6841,113 @@ required=true type="Text" [peachpayments] -[peachpayments.connector_auth.HeaderKey] -api_key = "API Key" +[[peachpayments.credit]] + payment_method_type = "Mastercard" +[[peachpayments.credit]] + payment_method_type = "Visa" +[[peachpayments.credit]] + payment_method_type = "AmericanExpress" +[[peachpayments.debit]] + payment_method_type = "Mastercard" +[[peachpayments.debit]] + payment_method_type = "Visa" +[[peachpayments.debit]] + payment_method_type = "AmericanExpress" +[peachpayments.connector_auth.BodyKey] +api_key="API Key" +key1="Tenant ID" +[peachpayments.connector_webhook_details] +merchant_secret="Webhook Secret" + +[peachpayments.metadata.merchant_name] +name="merchant_name" +label="Merchant Name" +placeholder="Enter Merchant Name" +required=true +type="Text" +[peachpayments.metadata.mcc] +name="mcc" +label="Merchant Category Code" +placeholder="Enter MCC (e.g., 5411)" +required=true +type="Text" +[peachpayments.metadata.merchant_phone] +name="merchant_phone" +label="Merchant Phone" +placeholder="Enter merchant phone (e.g., +27123456789)" +required=true +type="Text" +[peachpayments.metadata.merchant_email] +name="merchant_email" +label="Merchant Email" +placeholder="Enter merchant email" +required=true +type="Text" +[peachpayments.metadata.merchant_mobile] +name="merchant_mobile" +label="Merchant Mobile" +placeholder="Enter merchant mobile (e.g., +27123456789)" +required=true +type="Text" +[peachpayments.metadata.merchant_address] +name="merchant_address" +label="Merchant Address" +placeholder="Enter merchant address" +required=true +type="Text" +[peachpayments.metadata.merchant_city] +name="merchant_city" +label="Merchant City" +placeholder="Enter merchant city" +required=true +type="Text" +[peachpayments.metadata.merchant_postal_code] +name="merchant_postal_code" +label="Merchant Postal Code" +placeholder="Enter postal code" +required=true +type="Text" +[peachpayments.metadata.merchant_region_code] +name="merchant_region_code" +label="Merchant Region Code" +placeholder="Enter region code (e.g., WC)" +required=true +type="Text" +[peachpayments.metadata.merchant_type] +name="merchant_type" +label="Merchant Type" +placeholder="Select merchant type" +required=true +type="Select" +options=["direct", "sub"] +[peachpayments.metadata.merchant_website] +name="merchant_website" +label="Merchant Website" +placeholder="Enter merchant website URL" +required=true +type="Text" +[peachpayments.metadata.routing_mid] +name="routing_mid" +label="Routing MID" +placeholder="Enter routing MID" +required=true +type="Text" +[peachpayments.metadata.routing_tid] +name="routing_tid" +label="Routing TID" +placeholder="Enter routing TID" +required=true +type="Text" +[peachpayments.metadata.routing_route] +name="routing_route" +label="Routing Route" +placeholder="Select routing route" +required=true +type="Select" +options=["cardgateway_emulator", "exipay_emulator", "absa_base24", "nedbank_postbridge"] +[peachpayments.metadata.amex_id] +name="amex_id" +label="AmEx ID" +placeholder="Enter AmEx ID for routing" +required=false +type="Text" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 7501bb4c33d..3515ff2c58b 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5510,5 +5510,113 @@ required=true type="Text" [peachpayments] -[peachpayments.connector_auth.HeaderKey] -api_key = "API Key" +[[peachpayments.credit]] + payment_method_type = "Mastercard" +[[peachpayments.credit]] + payment_method_type = "Visa" +[[peachpayments.credit]] + payment_method_type = "AmericanExpress" +[[peachpayments.debit]] + payment_method_type = "Mastercard" +[[peachpayments.debit]] + payment_method_type = "Visa" +[[peachpayments.debit]] + payment_method_type = "AmericanExpress" +[peachpayments.connector_auth.BodyKey] +api_key="API Key" +key1="Tenant ID" +[peachpayments.connector_webhook_details] +merchant_secret="Webhook Secret" + +[peachpayments.metadata.merchant_name] +name="merchant_name" +label="Merchant Name" +placeholder="Enter Merchant Name" +required=true +type="Text" +[peachpayments.metadata.mcc] +name="mcc" +label="Merchant Category Code" +placeholder="Enter MCC (e.g., 5411)" +required=true +type="Text" +[peachpayments.metadata.merchant_phone] +name="merchant_phone" +label="Merchant Phone" +placeholder="Enter merchant phone (e.g., +27123456789)" +required=true +type="Text" +[peachpayments.metadata.merchant_email] +name="merchant_email" +label="Merchant Email" +placeholder="Enter merchant email" +required=true +type="Text" +[peachpayments.metadata.merchant_mobile] +name="merchant_mobile" +label="Merchant Mobile" +placeholder="Enter merchant mobile (e.g., +27123456789)" +required=true +type="Text" +[peachpayments.metadata.merchant_address] +name="merchant_address" +label="Merchant Address" +placeholder="Enter merchant address" +required=true +type="Text" +[peachpayments.metadata.merchant_city] +name="merchant_city" +label="Merchant City" +placeholder="Enter merchant city" +required=true +type="Text" +[peachpayments.metadata.merchant_postal_code] +name="merchant_postal_code" +label="Merchant Postal Code" +placeholder="Enter postal code" +required=true +type="Text" +[peachpayments.metadata.merchant_region_code] +name="merchant_region_code" +label="Merchant Region Code" +placeholder="Enter region code (e.g., WC)" +required=true +type="Text" +[peachpayments.metadata.merchant_type] +name="merchant_type" +label="Merchant Type" +placeholder="Select merchant type" +required=true +type="Select" +options=["direct", "sub"] +[peachpayments.metadata.merchant_website] +name="merchant_website" +label="Merchant Website" +placeholder="Enter merchant website URL" +required=true +type="Text" +[peachpayments.metadata.routing_mid] +name="routing_mid" +label="Routing MID" +placeholder="Enter routing MID" +required=true +type="Text" +[peachpayments.metadata.routing_tid] +name="routing_tid" +label="Routing TID" +placeholder="Enter routing TID" +required=true +type="Text" +[peachpayments.metadata.routing_route] +name="routing_route" +label="Routing Route" +placeholder="Select routing route" +required=true +type="Select" +options=["cardgateway_emulator", "exipay_emulator", "absa_base24", "nedbank_postbridge"] +[peachpayments.metadata.amex_id] +name="amex_id" +label="AmEx ID" +placeholder="Enter AmEx ID for routing" +required=false +type="Text" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 8220f4f2eae..9cfb45cf6db 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6823,6 +6823,116 @@ placeholder="Enter Account ID" required=true type="Text" + + [peachpayments] -[peachpayments.connector_auth.HeaderKey] -api_key = "API Key" +[[peachpayments.credit]] + payment_method_type = "Mastercard" +[[peachpayments.credit]] + payment_method_type = "Visa" +[[peachpayments.credit]] + payment_method_type = "AmericanExpress" +[[peachpayments.debit]] + payment_method_type = "Mastercard" +[[peachpayments.debit]] + payment_method_type = "Visa" +[[peachpayments.debit]] + payment_method_type = "AmericanExpress" +[peachpayments.connector_auth.BodyKey] +api_key="API Key" +key1="Tenant ID" +[peachpayments.connector_webhook_details] +merchant_secret="Webhook Secret" + +[peachpayments.metadata.merchant_name] +name="merchant_name" +label="Merchant Name" +placeholder="Enter Merchant Name" +required=true +type="Text" +[peachpayments.metadata.mcc] +name="mcc" +label="Merchant Category Code" +placeholder="Enter MCC (e.g., 5411)" +required=true +type="Text" +[peachpayments.metadata.merchant_phone] +name="merchant_phone" +label="Merchant Phone" +placeholder="Enter merchant phone (e.g., +27123456789)" +required=true +type="Text" +[peachpayments.metadata.merchant_email] +name="merchant_email" +label="Merchant Email" +placeholder="Enter merchant email" +required=true +type="Text" +[peachpayments.metadata.merchant_mobile] +name="merchant_mobile" +label="Merchant Mobile" +placeholder="Enter merchant mobile (e.g., +27123456789)" +required=true +type="Text" +[peachpayments.metadata.merchant_address] +name="merchant_address" +label="Merchant Address" +placeholder="Enter merchant address" +required=true +type="Text" +[peachpayments.metadata.merchant_city] +name="merchant_city" +label="Merchant City" +placeholder="Enter merchant city" +required=true +type="Text" +[peachpayments.metadata.merchant_postal_code] +name="merchant_postal_code" +label="Merchant Postal Code" +placeholder="Enter postal code" +required=true +type="Text" +[peachpayments.metadata.merchant_region_code] +name="merchant_region_code" +label="Merchant Region Code" +placeholder="Enter region code (e.g., WC)" +required=true +type="Text" +[peachpayments.metadata.merchant_type] +name="merchant_type" +label="Merchant Type" +placeholder="Select merchant type" +required=true +type="Select" +options=["direct", "sub"] +[peachpayments.metadata.merchant_website] +name="merchant_website" +label="Merchant Website" +placeholder="Enter merchant website URL" +required=true +type="Text" +[peachpayments.metadata.routing_mid] +name="routing_mid" +label="Routing MID" +placeholder="Enter routing MID" +required=true +type="Text" +[peachpayments.metadata.routing_tid] +name="routing_tid" +label="Routing TID" +placeholder="Enter routing TID" +required=true +type="Text" +[peachpayments.metadata.routing_route] +name="routing_route" +label="Routing Route" +placeholder="Select routing route" +required=true +type="Select" +options=["cardgateway_emulator", "exipay_emulator", "absa_base24", "nedbank_postbridge"] +[peachpayments.metadata.amex_id] +name="amex_id" +label="AmEx ID" +placeholder="Enter AmEx ID for routing" +required=false +type="Text" diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments.rs index 3c258893320..abc8caf1efc 100644 --- a/crates/hyperswitch_connectors/src/connectors/peachpayments.rs +++ b/crates/hyperswitch_connectors/src/connectors/peachpayments.rs @@ -2,7 +2,7 @@ pub mod transformers; use std::sync::LazyLock; -use common_enums::enums; +use common_enums::{self, enums}; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, @@ -11,7 +11,6 @@ use common_utils::{ }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, @@ -24,11 +23,12 @@ use hyperswitch_domain_models::{ RefundsData, SetupMandateRequestData, }, router_response_types::{ - ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -122,10 +122,14 @@ impl ConnectorCommon for Peachpayments { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = peachpayments::PeachpaymentsAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), - )]) + Ok(vec![ + ("x-api-key".to_string(), auth.api_key.expose().into_masked()), + ( + "x-tenant-id".to_string(), + auth.tenant_id.expose().into_masked(), + ), + ("x-exi-auth-ver".to_string(), "v1".to_string().into_masked()), + ]) } fn build_error_response( @@ -143,9 +147,9 @@ impl ConnectorCommon for Peachpayments { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response.error_ref.clone(), + message: response.message.clone(), + reason: Some(response.message.clone()), attempt_status: None, connector_transaction_id: None, network_advice_code: None, @@ -156,31 +160,7 @@ impl ConnectorCommon for Peachpayments { } } -impl ConnectorValidation for Peachpayments { - fn validate_mandate_payment( - &self, - _pm_type: Option<enums::PaymentMethodType>, - pm_data: PaymentMethodData, - ) -> CustomResult<(), errors::ConnectorError> { - match pm_data { - PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( - "validate_mandate_payment does not support cards".to_string(), - ) - .into()), - _ => Ok(()), - } - } - - fn validate_psync_reference_id( - &self, - _data: &PaymentsSyncData, - _is_three_ds: bool, - _status: enums::AttemptStatus, - _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, - ) -> CustomResult<(), errors::ConnectorError> { - Ok(()) - } -} +impl ConnectorValidation for Peachpayments {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Peachpayments { //TODO: implement sessions flow @@ -211,9 +191,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( @@ -298,10 +278,19 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pea 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( @@ -362,18 +351,32 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn get_url( &self, - _req: &PaymentsCaptureRouterData, - _connectors: &Connectors, + req: &PaymentsCaptureRouterData, + 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; + Ok(format!( + "{}/transactions/{}/confirm", + self.base_url(connectors), + connector_transaction_id + )) } fn get_request_body( &self, - _req: &PaymentsCaptureRouterData, + req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, + req.request.currency, + )?; + + let connector_router_data = peachpayments::PeachpaymentsRouterData::from((amount, req)); + let connector_req = + peachpayments::PeachpaymentsConfirmRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -402,7 +405,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: peachpayments::PeachpaymentsPaymentsResponse = res + let response: peachpayments::PeachpaymentsConfirmResponse = res .response .parse_struct("Peachpayments PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -424,12 +427,10 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Peachpayments {} - -impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpayments { +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Peachpayments { fn get_headers( &self, - req: &RefundsRouterData<Execute>, + req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) @@ -441,58 +442,53 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpa fn get_url( &self, - _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + req: &PaymentsCancelRouterData, + 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; + Ok(format!( + "{}/transactions/{}/void", + self.base_url(connectors), + connector_transaction_id + )) } fn get_request_body( &self, - req: &RefundsRouterData<Execute>, + req: &PaymentsCancelRouterData, _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 = - peachpayments::PeachpaymentsRouterData::from((refund_amount, req)); - let connector_req = - peachpayments::PeachpaymentsRefundRequest::try_from(&connector_router_data)?; + let connector_req = peachpayments::PeachpaymentsVoidRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &RefundsRouterData<Execute>, + req: &PaymentsCancelRouterData, 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)) + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(types::PaymentsVoidType::get_request_body( + self, req, connectors, + )?) + .build(), + )) } fn handle_response( &self, - data: &RefundsRouterData<Execute>, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: peachpayments::RefundResponse = res + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + let response: peachpayments::PeachpaymentsPaymentsResponse = res .response - .parse_struct("peachpayments RefundResponse") + .parse_struct("Peachpayments PaymentsVoidResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -512,70 +508,23 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpa } } -impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Peachpayments { - 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( +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpayments { + fn build_request( &self, - _req: &RefundSyncRouterData, + _req: &RefundsRouterData<Execute>, _connectors: &Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("Execute".to_string()).into()) } +} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Peachpayments { fn build_request( &self, - req: &RefundSyncRouterData, - connectors: &Connectors, + _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: peachpayments::RefundResponse = res - .response - .parse_struct("peachpayments 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) + Err(errors::ConnectorError::NotImplemented("Refunds Retrieve".to_string()).into()) } } @@ -604,11 +553,64 @@ impl webhooks::IncomingWebhook for Peachpayments { } static PEACHPAYMENTS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = - LazyLock::new(SupportedPaymentMethods::new); + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + ]; + + let mut peachpayments_supported_payment_methods = SupportedPaymentMethods::new(); + + peachpayments_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::NotSupported, + 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(), + } + }), + ), + }, + ); + + peachpayments_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::NotSupported, + 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(), + } + }), + ), + }, + ); + + peachpayments_supported_payment_methods + }); static PEACHPAYMENTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Peachpayments", - description: "Peachpayments connector", + description: "The secure African payment gateway with easy integrations, 365-day support, and advanced orchestration.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Beta, }; diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs index 1d403f26321..a5e34b416ac 100644 --- a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs @@ -1,18 +1,28 @@ -use common_enums::enums; -use common_utils::types::MinorUnit; +use std::str::FromStr; + +use cards::CardNumber; +use common_utils::{pii, types::MinorUnit}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + router_response_types::PaymentsResponseData, + types::{PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData}, +}; +use hyperswitch_interfaces::{ + consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, + errors, }; -use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; +use strum::Display; +use time::{format_description::well_known::Rfc3339, OffsetDateTime}; -use crate::types::{RefundsResponseRouterData, ResponseRouterData}; +use crate::{ + types::ResponseRouterData, + utils::{self, CardData}, +}; //TODO: Fill the struct with respective fields pub struct PeachpaymentsRouterData<T> { @@ -30,20 +40,288 @@ impl<T> From<(MinorUnit, T)> for PeachpaymentsRouterData<T> { } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] +impl TryFrom<&Option<pii::SecretSerdeValue>> for PeachPaymentsConnectorMetadataObject { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { + let metadata = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "metadata", + })?; + Ok(metadata) + } +} + +// Card Gateway API Transaction Request +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct PeachpaymentsPaymentsRequest { - amount: MinorUnit, - card: PeachpaymentsCard, + pub charge_method: String, + pub reference_id: String, + pub ecommerce_card_payment_only_transaction_data: EcommerceCardPaymentOnlyTransactionData, + #[serde(skip_serializing_if = "Option::is_none")] + pub pos_data: Option<serde_json::Value>, + pub send_date_time: String, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct EcommerceCardPaymentOnlyTransactionData { + pub merchant_information: MerchantInformation, + pub routing: Routing, + pub card: CardDetails, + pub amount: AmountDetails, + #[serde(skip_serializing_if = "Option::is_none")] + pub three_ds_data: Option<ThreeDSData>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct MerchantInformation { + pub client_merchant_reference_id: String, + pub name: String, + pub mcc: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub mobile: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub city: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub postal_code: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub region_code: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub merchant_type: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub website_url: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct Routing { + pub route: String, + pub mid: String, + pub tid: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub visa_payment_facilitator_id: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub master_card_payment_facilitator_id: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub sub_mid: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub amex_id: Option<String>, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct CardDetails { + pub pan: CardNumber, + #[serde(skip_serializing_if = "Option::is_none")] + pub cardholder_name: Option<Secret<String>>, + pub expiry_year: Secret<String>, + pub expiry_month: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub cvv: Option<Secret<String>>, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct RefundCardDetails { + pub pan: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub cardholder_name: Option<Secret<String>>, + pub expiry_year: Secret<String>, + pub expiry_month: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub cvv: Option<Secret<String>>, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct PeachpaymentsCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct AmountDetails { + pub amount: MinorUnit, + pub currency_code: String, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct ThreeDSData { + #[serde(skip_serializing_if = "Option::is_none")] + pub cavv: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub tavv: Option<Secret<String>>, + pub eci: String, + pub ds_trans_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub xid: Option<String>, + pub authentication_status: AuthenticationStatus, + pub three_ds_version: String, +} + +// Confirm Transaction Request (for capture) +#[derive(Debug, Serialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct PeachpaymentsConfirmRequest { + pub ecommerce_card_payment_only_confirmation_data: EcommerceCardPaymentOnlyConfirmationData, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct EcommerceCardPaymentOnlyConfirmationData { + pub amount: AmountDetails, +} + +// Void Transaction Request +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PeachpaymentsVoidRequest { + pub payment_method: PaymentMethod, + pub send_date_time: String, + pub failure_reason: FailureReason, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethod { + EcommerceCardPaymentOnly, +} + +impl TryFrom<&PeachpaymentsRouterData<&PaymentsCaptureRouterData>> for PeachpaymentsConfirmRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PeachpaymentsRouterData<&PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { + let amount_in_cents = item.amount; + + let amount = AmountDetails { + amount: amount_in_cents, + currency_code: item.router_data.request.currency.to_string(), + }; + + let confirmation_data = EcommerceCardPaymentOnlyConfirmationData { amount }; + + Ok(Self { + ecommerce_card_payment_only_confirmation_data: confirmation_data, + }) + } +} + +#[derive(Default, Debug, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum FailureReason { + UnableToSend, + #[default] + Timeout, + SecurityError, + IssuerUnavailable, + TooLateResponse, + Malfunction, + UnableToComplete, + OnlineDeclined, + SuspectedFraud, + CardDeclined, + Partial, + OfflineDeclined, + CustomerCancel, +} + +impl FromStr for FailureReason { + type Err = error_stack::Report<errors::ConnectorError>; + + fn from_str(value: &str) -> Result<Self, Self::Err> { + match value.to_lowercase().as_str() { + "unable_to_send" => Ok(Self::UnableToSend), + "timeout" => Ok(Self::Timeout), + "security_error" => Ok(Self::SecurityError), + "issuer_unavailable" => Ok(Self::IssuerUnavailable), + "too_late_response" => Ok(Self::TooLateResponse), + "malfunction" => Ok(Self::Malfunction), + "unable_to_complete" => Ok(Self::UnableToComplete), + "online_declined" => Ok(Self::OnlineDeclined), + "suspected_fraud" => Ok(Self::SuspectedFraud), + "card_declined" => Ok(Self::CardDeclined), + "partial" => Ok(Self::Partial), + "offline_declined" => Ok(Self::OfflineDeclined), + "customer_cancel" => Ok(Self::CustomerCancel), + _ => Ok(Self::Timeout), + } + } +} + +impl TryFrom<&PaymentsCancelRouterData> for PeachpaymentsVoidRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { + let send_date_time = OffsetDateTime::now_utc() + .format(&Rfc3339) + .map_err(|_| errors::ConnectorError::ParsingFailed)?; + Ok(Self { + payment_method: PaymentMethod::EcommerceCardPaymentOnly, + send_date_time, + failure_reason: item + .request + .cancellation_reason + .as_ref() + .map(|reason| FailureReason::from_str(reason)) + .transpose()? + .unwrap_or(FailureReason::Timeout), + }) + } +} + +#[derive(Debug, Serialize, PartialEq)] +pub enum AuthenticationStatus { + Y, // Fully authenticated + A, // Attempted authentication / liability shift + N, // Not authenticated / failed +} + +impl From<&str> for AuthenticationStatus { + fn from(eci: &str) -> Self { + match eci { + "05" | "06" => Self::Y, + "07" => Self::A, + _ => Self::N, + } + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PeachPaymentsConnectorMetadataObject { + pub client_merchant_reference_id: String, + pub name: String, + pub mcc: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub mobile: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub city: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub postal_code: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub region_code: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub merchant_type: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub website_url: Option<String>, + pub route: String, + pub mid: String, + pub tid: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub visa_payment_facilitator_id: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub master_card_payment_facilitator_id: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub sub_mid: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub amex_id: Option<String>, } impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>> @@ -54,58 +332,260 @@ impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>> item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( - "Card payment method not implemented".to_string(), - ) - .into()), + PaymentMethodData::Card(req_card) => { + let amount_in_cents = item.amount; + + let connector_merchant_config = PeachPaymentsConnectorMetadataObject::try_from( + &item.router_data.connector_meta_data, + )?; + + let merchant_information = MerchantInformation { + client_merchant_reference_id: connector_merchant_config + .client_merchant_reference_id, + name: connector_merchant_config.name, + mcc: connector_merchant_config.mcc, + phone: connector_merchant_config.phone, + email: connector_merchant_config.email, + mobile: connector_merchant_config.mobile, + address: connector_merchant_config.address, + city: connector_merchant_config.city, + postal_code: connector_merchant_config.postal_code, + region_code: connector_merchant_config.region_code, + merchant_type: connector_merchant_config.merchant_type, + website_url: connector_merchant_config.website_url, + }; + + // Get routing configuration from metadata + let routing = Routing { + route: connector_merchant_config.route, + mid: connector_merchant_config.mid, + tid: connector_merchant_config.tid, + visa_payment_facilitator_id: connector_merchant_config + .visa_payment_facilitator_id, + master_card_payment_facilitator_id: connector_merchant_config + .master_card_payment_facilitator_id, + sub_mid: connector_merchant_config.sub_mid, + amex_id: connector_merchant_config.amex_id, + }; + + let card = CardDetails { + pan: req_card.card_number.clone(), + cardholder_name: req_card.card_holder_name.clone(), + expiry_year: req_card.get_card_expiry_year_2_digit()?, + expiry_month: req_card.card_exp_month.clone(), + cvv: Some(req_card.card_cvc.clone()), + }; + + let amount = AmountDetails { + amount: amount_in_cents, + currency_code: item.router_data.request.currency.to_string(), + }; + + // Extract 3DS data if available + let three_ds_data = item + .router_data + .request + .authentication_data + .as_ref() + .and_then(|auth_data| { + // Only include 3DS data if we have essential fields (ECI is most critical) + if let Some(eci) = &auth_data.eci { + let ds_trans_id = auth_data + .ds_trans_id + .clone() + .or_else(|| auth_data.threeds_server_transaction_id.clone())?; + + // Determine authentication status based on ECI value + let authentication_status = eci.as_str().into(); + + // Convert message version to string, handling None case + let three_ds_version = auth_data.message_version.as_ref().map(|v| { + let version_str = v.to_string(); + let mut parts = version_str.split('.'); + match (parts.next(), parts.next()) { + (Some(major), Some(minor)) => format!("{}.{}", major, minor), + _ => v.to_string(), // fallback if format unexpected + } + })?; + + Some(ThreeDSData { + cavv: Some(auth_data.cavv.clone()), + tavv: None, // Network token field - not available in Hyperswitch AuthenticationData + eci: eci.clone(), + ds_trans_id, + xid: None, // Legacy 3DS 1.x/network token field - not available in Hyperswitch AuthenticationData + authentication_status, + three_ds_version, + }) + } else { + None + } + }); + + let ecommerce_data = EcommerceCardPaymentOnlyTransactionData { + merchant_information, + routing, + card, + amount, + three_ds_data, + }; + + // Generate current timestamp for sendDateTime (ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ) + let send_date_time = OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Iso8601::DEFAULT) + .map_err(|_| errors::ConnectorError::RequestEncodingFailed)?; + + Ok(Self { + charge_method: "ecommerce_card_payment_only".to_string(), + reference_id: item.router_data.connector_request_reference_id.clone(), + ecommerce_card_payment_only_transaction_data: ecommerce_data, + pos_data: None, + send_date_time, + }) + } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } -//TODO: Fill the struct with respective fields -// Auth Struct +// Auth Struct for Card Gateway API pub struct PeachpaymentsAuthType { - pub(super) api_key: Secret<String>, + pub(crate) api_key: Secret<String>, + pub(crate) tenant_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PeachpaymentsAuthType { 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()), + if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { + Ok(Self { + api_key: api_key.clone(), + tenant_id: key1.clone(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] +// Card Gateway API Response +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PeachpaymentsPaymentStatus { - Succeeded, + Successful, + Pending, + Authorized, + Approved, + #[serde(rename = "approved_confirmed")] + ApprovedConfirmed, + Declined, Failed, - #[default] - Processing, + Reversed, + #[serde(rename = "threeds_required")] + ThreedsRequired, + Voided, } impl From<PeachpaymentsPaymentStatus> for common_enums::AttemptStatus { fn from(item: PeachpaymentsPaymentStatus) -> Self { match item { - PeachpaymentsPaymentStatus::Succeeded => Self::Charged, - PeachpaymentsPaymentStatus::Failed => Self::Failure, - PeachpaymentsPaymentStatus::Processing => Self::Authorizing, + // PENDING means authorized but not yet captured - requires confirmation + PeachpaymentsPaymentStatus::Pending + | PeachpaymentsPaymentStatus::Authorized + | PeachpaymentsPaymentStatus::Approved => Self::Authorized, + PeachpaymentsPaymentStatus::Declined | PeachpaymentsPaymentStatus::Failed => { + Self::Failure + } + PeachpaymentsPaymentStatus::Voided | PeachpaymentsPaymentStatus::Reversed => { + Self::Voided + } + PeachpaymentsPaymentStatus::ThreedsRequired => Self::AuthenticationPending, + PeachpaymentsPaymentStatus::ApprovedConfirmed + | PeachpaymentsPaymentStatus::Successful => Self::Charged, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "camelCase"]] pub struct PeachpaymentsPaymentsResponse { - status: PeachpaymentsPaymentStatus, - id: String, + pub transaction_id: String, + pub response_code: ResponseCode, + pub transaction_result: PeachpaymentsPaymentStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub ecommerce_card_payment_only_transaction_data: Option<EcommerceCardPaymentOnlyResponseData>, +} + +// Confirm Transaction Response +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct PeachpaymentsConfirmResponse { + pub transaction_id: String, + pub response_code: ResponseCode, + pub transaction_result: PeachpaymentsPaymentStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub authorization_code: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] +pub enum ResponseCode { + Text(String), + Structured { + value: ResponseCodeValue, + description: String, + }, +} + +impl ResponseCode { + pub fn value(&self) -> Option<&ResponseCodeValue> { + match self { + Self::Structured { value, .. } => Some(value), + _ => None, + } + } + + pub fn description(&self) -> Option<&String> { + match self { + Self::Structured { description, .. } => Some(description), + _ => None, + } + } + + pub fn as_text(&self) -> Option<&String> { + match self { + Self::Text(s) => Some(s), + _ => None, + } + } +} + +#[derive(Debug, Display, Clone, Serialize, Deserialize, PartialEq)] +pub enum ResponseCodeValue { + #[serde(rename = "00", alias = "08")] + Success, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct EcommerceCardPaymentOnlyResponseData { + pub card: Option<CardResponseData>, + pub amount: Option<AmountDetails>, + pub stan: Option<String>, + pub rrn: Option<String>, + #[serde(rename = "approvalCode")] + pub approval_code: Option<String>, + #[serde(rename = "merchantAdviceCode")] + pub merchant_advice_code: Option<String>, + pub description: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde[rename_all = "camelCase"]] +pub struct CardResponseData { + pub bin_number: Option<String>, + pub masked_pan: Option<String>, + pub cardholder_name: Option<String>, + pub expiry_month: Option<String>, + pub expiry_year: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>> @@ -115,109 +595,156 @@ impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, Payme fn try_from( item: ResponseRouterData<F, PeachpaymentsPaymentsResponse, 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), + let status = common_enums::AttemptStatus::from(item.response.transaction_result); + + // Check if it's an error response + let response = if item.response.response_code.value() != Some(&ResponseCodeValue::Success) { + Err(ErrorResponse { + code: item + .response + .response_code + .value() + .map(|val| val.to_string()) + .unwrap_or(NO_ERROR_CODE.to_string()), + message: item + .response + .response_code + .description() + .map(|desc| desc.to_string()) + .unwrap_or(NO_ERROR_MESSAGE.to_string()), + reason: item + .response + .ecommerce_card_payment_only_transaction_data + .and_then(|data| data.description), + status_code: item.http_code, + attempt_status: Some(status), + connector_transaction_id: Some(item.response.transaction_id.clone()), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.transaction_id.clone(), + ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.transaction_id), incremental_authorization_allowed: None, charges: None, - }), + }) + }; + + Ok(Self { + status, + response, ..item.data }) } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct PeachpaymentsRefundRequest { - pub amount: MinorUnit, -} - -impl<F> TryFrom<&PeachpaymentsRouterData<&RefundsRouterData<F>>> for PeachpaymentsRefundRequest { +// TryFrom implementation for confirm response +impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsConfirmResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: &PeachpaymentsRouterData<&RefundsRouterData<F>>, + item: ResponseRouterData<F, PeachpaymentsConfirmResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - Ok(Self { - amount: item.amount.to_owned(), - }) - } -} - -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, -} + let status = common_enums::AttemptStatus::from(item.response.transaction_result); -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, -} + // Check if it's an error response + let response = if item.response.response_code.value() != Some(&ResponseCodeValue::Success) { + Err(ErrorResponse { + code: item + .response + .response_code + .value() + .map(|val| val.to_string()) + .unwrap_or(NO_ERROR_CODE.to_string()), + message: item + .response + .response_code + .description() + .map(|desc| desc.to_string()) + .unwrap_or(NO_ERROR_MESSAGE.to_string()), + reason: None, + status_code: item.http_code, + attempt_status: Some(status), + connector_transaction_id: Some(item.response.transaction_id.clone()), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.transaction_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: item.response.authorization_code.map(|auth_code| { + serde_json::json!({ + "authorization_code": auth_code + }) + }), + network_txn_id: None, + connector_response_reference_id: Some(item.response.transaction_id), + incremental_authorization_allowed: None, + charges: None, + }) + }; -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), - }), + status, + response, ..item.data }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { +impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>> + for PeachpaymentsConfirmRequest +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { + let amount_in_cents = item.amount; + + let amount = AmountDetails { + amount: amount_in_cents, + currency_code: item.router_data.request.currency.to_string(), + }; + + let confirmation_data = EcommerceCardPaymentOnlyConfirmationData { amount }; + Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), - }), - ..item.data + ecommerce_card_payment_only_confirmation_data: confirmation_data, }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +// Error Response +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct PeachpaymentsErrorResponse { - pub status_code: u16, - pub code: String, + pub error_ref: String, pub message: String, - pub reason: Option<String>, - pub network_advice_code: Option<String>, - pub network_decline_code: Option<String>, - pub network_error_message: Option<String>, +} + +impl TryFrom<ErrorResponse> for PeachpaymentsErrorResponse { + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from(error_response: ErrorResponse) -> Result<Self, Self::Error> { + Ok(Self { + error_ref: error_response.code, + message: error_response.message, + }) + } } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 1a4424ac5be..a6f46e0c2a8 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -3317,8 +3317,8 @@ default_imp_for_fetch_disputes!( connectors::Paysafe, connectors::Paystack, connectors::Payu, - connectors::Peachpayments, connectors::Paytm, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, @@ -3461,8 +3461,8 @@ default_imp_for_dispute_sync!( connectors::Paysafe, connectors::Paystack, connectors::Payu, - connectors::Peachpayments, connectors::Paytm, + connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index c6271341d66..8df3036e355 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -415,10 +415,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { payu::transformers::PayuAuthType::try_from(self.auth_type)?; Ok(()) } - // api_enums::Connector::Peachpayments => { - // peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?; - // Ok(()) - // } + api_enums::Connector::Peachpayments => { + peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Placetopay => { placetopay::transformers::PlacetopayAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index 28300ecbf21..2333f1c8bc1 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -352,9 +352,9 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Payone::new()))) } enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))), - // enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new( - // hyperswitch_connectors::connectors::Peachpayments::new(), - // ))), + enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new( + hyperswitch_connectors::connectors::Peachpayments::new(), + ))), enums::Connector::Placetopay => { Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new()))) } diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index d82c1968b02..d5480ab2c26 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -274,9 +274,9 @@ impl FeatureMatrixConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Payone::new()))) } enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))), - // enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new( - // connector::Peachpayments::new(), - // ))), + enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new( + connector::Peachpayments::new(), + ))), enums::Connector::Placetopay => { Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new()))) } diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index 683ba603733..6bcec0681d4 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -113,7 +113,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Paysafe => Self::Paysafe, api_enums::Connector::Paystack => Self::Paystack, api_enums::Connector::Payu => Self::Payu, - // api_enums::Connector::Peachpayments => Self::Peachpayments, + api_enums::Connector::Peachpayments => Self::Peachpayments, api_models::enums::Connector::Placetopay => Self::Placetopay, api_enums::Connector::Plaid => Self::Plaid, api_enums::Connector::Powertranz => Self::Powertranz,
2025-08-22T08:28:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR implements the complete Peachpayments connector integration for Hyperswitch, adding support for payment processing, 3DS authentication, void transactions, and comprehensive validation. Key features implemented: - Complete Peachpayments connector with payment authorization, capture, and void flows - 3DS authentication support with enhanced security features - Network token handling with TAVV/XID fields for improved authentication - ConnectorValidation implementation for request validation - Comprehensive error handling and response transformations - Configuration and API endpoint management ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This change adds Peachpayments as a new payment processor option in Hyperswitch, expanding payment gateway options for merchants. The implementation follows the connector integration pattern and includes all necessary features for production use including security validations and 3DS support. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Test 1. Payment Connector - Create Request: ``` curl --location 'http://localhost:8080/account/merchant_1757610148/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_SFgSgDzIk5bWAMdai9p76lBeX4bvrRV15SEqDicJ7OhCG6KRzOTljGHUZxpKnZN6' \ --data-raw '{ "connector_type": "payment_processor", "connector_name": "peachpayments", "connector_account_details": { "auth_type": "BodyKey", "api_key": API KEY, "key1": KEY1 }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "metadata": { "client_merchant_reference_id": CLIENT MERCHANT REFERENCE ID, "name": NAME, "mcc": MCC, "phone": "27726599258", "email": "[email protected]", "mobile": "27726599258", "address": "35 Brickfield Rd", "city": "Cape Town", "postalCode": "7925", "regionCode": "WC", "merchantType": "sub", "websiteUrl": "example.com", "route": ROUTE, "mid": MID, "tid": TID, "subMid": SUBMID, "visaPaymentFacilitatorId": VISAPAYMENTFACILITATORID, "masterCardPaymentFacilitatorId": MASTERCARDPAYMENTFACILITATORID }, "business_country": "US", "business_label": "default", "additional_merchant_data": null, "status": "active", "pm_auth_config": null }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "peachpayments", "connector_label": "peachpayments_US_default", "merchant_connector_id": "mca_ef4ONOxde7RCQQfvhHJJ", "profile_id": "pro_5BUfDMTQyz5EbHajw6SE", "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 } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, "metadata": { "client_merchant_reference_id": CLIENT MERCHANT REFERENCE ID, "name": NAME, "mcc": MCC, "phone": "27726599258", "email": "[email protected]", "mobile": "27726599258", "address": "35 Brickfield Rd", "city": "Cape Town", "postalCode": "7925", "regionCode": "WC", "merchantType": "sub", "websiteUrl": "example.com", "route": ROUTE, "mid": MID, "tid": TID, "subMid": SUBMID, "visaPaymentFacilitatorId": VISAPAYMENTFACILITATORID, "masterCardPaymentFacilitatorId": MASTERCARDPAYMENTFACILITATORID }, "test_mode": true, "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 } ``` 2. Payments - Create Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_SFgSgDzIk5bWAMdai9p76lBeX4bvrRV15SEqDicJ7OhCG6KRzOTljGHUZxpKnZN6' \ --data-raw ' { "amount": 35308, "currency": "USD", "confirm": true, "capture_method": "manual", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-US", "screen_height": 848, "screen_width": 1312, "time_zone": -330, "ip_address": "65.1.52.128", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15", "os_type": "macOS", "os_version": "10.15.7", "device_model": "Macintosh", "accept_language": "en" } }' ``` Response: ``` { "payment_id": "pay_2POhxvMBaEDy88vz9cwX", "merchant_id": "merchant_1757610148", "status": "requires_capture", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 35308, "amount_received": null, "connector": "peachpayments", "client_secret": "pay_2POhxvMBaEDy88vz9cwX_secret_1BIiQY7RkIeBsyqU7YRF", "created": "2025-09-11T17:13:57.373Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": 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, "origin_zip": 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", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1757610837, "expires": 1757614437, "secret": "epk_826cdebaa0dc4fb197d4a229381cff54" }, "manual_retry_allowed": null, "connector_transaction_id": "884be477-1865-4f40-b452-ae792e21a6d5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "884be477-1865-4f40-b452-ae792e21a6d5", "payment_link": null, "profile_id": "pro_5BUfDMTQyz5EbHajw6SE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ef4ONOxde7RCQQfvhHJJ", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-11T17:28:57.373Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "65.1.52.128", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1312, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 848, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-11T17:13:59.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", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 3. Payments - Capture Request: ``` curl --location 'http://localhost:8080/payments/pay_2POhxvMBaEDy88vz9cwX/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_SFgSgDzIk5bWAMdai9p76lBeX4bvrRV15SEqDicJ7OhCG6KRzOTljGHUZxpKnZN6' \ --data ' { "amount_to_capture": 35308, "statement_descriptor_name": "Joseph", "statement_descriptor_suffix": "JS" }' ``` Response: ``` { "payment_id": "pay_2POhxvMBaEDy88vz9cwX", "merchant_id": "merchant_1757610148", "status": "succeeded", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": 35308, "connector": "peachpayments", "client_secret": "pay_2POhxvMBaEDy88vz9cwX_secret_1BIiQY7RkIeBsyqU7YRF", "created": "2025-09-11T17:13:57.373Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": 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, "origin_zip": 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", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "884be477-1865-4f40-b452-ae792e21a6d5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "884be477-1865-4f40-b452-ae792e21a6d5", "payment_link": null, "profile_id": "pro_5BUfDMTQyz5EbHajw6SE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ef4ONOxde7RCQQfvhHJJ", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-11T17:28:57.373Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "65.1.52.128", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1312, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 848, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-11T17:15:17.517Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 4. Payments - Retrieve Request: ``` curl --location 'http://localhost:8080/payments/pay_2POhxvMBaEDy88vz9cwX?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_SFgSgDzIk5bWAMdai9p76lBeX4bvrRV15SEqDicJ7OhCG6KRzOTljGHUZxpKnZN6' ``` Response: ``` { "payment_id": "pay_2POhxvMBaEDy88vz9cwX", "merchant_id": "merchant_1757610148", "status": "succeeded", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": 35308, "connector": "peachpayments", "client_secret": "pay_2POhxvMBaEDy88vz9cwX_secret_1BIiQY7RkIeBsyqU7YRF", "created": "2025-09-11T17:13:57.373Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": 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, "origin_zip": 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", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "884be477-1865-4f40-b452-ae792e21a6d5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "884be477-1865-4f40-b452-ae792e21a6d5", "payment_link": null, "profile_id": "pro_5BUfDMTQyz5EbHajw6SE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ef4ONOxde7RCQQfvhHJJ", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-11T17:28:57.373Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "65.1.52.128", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1312, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 848, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-11T17:15:35.325Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": null } ``` 5. Payments - Cancel (with different paymentID) Request: ``` curl --location 'http://localhost:8080/payments/pay_jflZ4TICqo9uLRFDrbtc/cancel' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_SFgSgDzIk5bWAMdai9p76lBeX4bvrRV15SEqDicJ7OhCG6KRzOTljGHUZxpKnZN6' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` Response: ``` { "payment_id": "pay_jflZ4TICqo9uLRFDrbtc", "merchant_id": "merchant_1757610148", "status": "cancelled", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "peachpayments", "client_secret": "pay_jflZ4TICqo9uLRFDrbtc_secret_qDuIgBJH7F07APir1zg8", "created": "2025-09-11T17:04:35.524Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "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": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": 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, "origin_zip": 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", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": "requested_by_customer", "error_code": null, "error_message": null, "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": null, "connector_transaction_id": "0ca6ad99-d749-4a9e-96df-95fa761681ad", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "0ca6ad99-d749-4a9e-96df-95fa761681ad", "payment_link": null, "profile_id": "pro_5BUfDMTQyz5EbHajw6SE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ef4ONOxde7RCQQfvhHJJ", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-11T17:19:35.524Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "65.1.52.128", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1312, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 848, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-11T17:05:06.519Z", "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, "enable_partial_authorization": null, "enable_overcapture": null, "is_overcapture_enabled": null, "network_details": { "network_advice_code": null } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0873d93084d2a126cdfb3ebb60e92b0cec79d2ba
juspay/hyperswitch
juspay__hyperswitch-9332
Bug: Create Customer
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index 4976c5fc61c..ebc244832b0 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -20,7 +20,8 @@ use hyperswitch_domain_models::{ router_flow_types::RSync, router_request_types::ResponseId, router_response_types::{ - MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, + ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm, + RefundsResponseData, }, types::{ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, @@ -619,9 +620,9 @@ impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetCustomerResponse, T, Pay match item.response.messages.result_code { ResultCode::Ok => match item.response.customer_profile_id.clone() { Some(connector_customer_id) => Ok(Self { - response: Ok(PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - }), + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id(connector_customer_id), + )), ..item.data }), None => Err( @@ -637,9 +638,11 @@ impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetCustomerResponse, T, Pay error_message.and_then(|error| extract_customer_id(&error.text)) { Ok(Self { - response: Ok(PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - }), + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id( + connector_customer_id, + ), + )), ..item.data }) } else { diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index 7f64c2f299d..632064a893d 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -13,7 +13,7 @@ use common_utils::{ use error_stack::report; use error_stack::ResultExt; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use hyperswitch_domain_models::revenue_recovery; +use hyperswitch_domain_models::{revenue_recovery, router_data_v2::RouterDataV2}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ @@ -22,26 +22,29 @@ use hyperswitch_domain_models::{ refunds::{Execute, RSync}, revenue_recovery::InvoiceRecordBack, subscriptions::GetSubscriptionPlans, + CreateConnectorCustomer, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions::GetSubscriptionPlansRequest, - AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, + PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::GetSubscriptionPlansResponse, ConnectorInfo, PaymentsResponseData, RefundsResponseData, }, types::{ - GetSubscriptionPlansRouterData, InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, - PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, + ConnectorCustomerRouterData, GetSubscriptionPlansRouterData, InvoiceRecordBackRouterData, + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ - self, subscriptions_v2::GetSubscriptionPlansV2, ConnectorCommon, ConnectorCommonExt, - ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, + self, payments::ConnectorCustomer, subscriptions_v2::GetSubscriptionPlansV2, + ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, }, configs::Connectors, connector_integration_v2::ConnectorIntegrationV2, @@ -72,7 +75,7 @@ impl Chargebee { } } } - +impl ConnectorCustomer for Chargebee {} impl api::Payment for Chargebee {} impl api::PaymentSession for Chargebee {} impl api::ConnectorAccessToken for Chargebee {} @@ -85,6 +88,7 @@ impl api::Refund for Chargebee {} impl api::RefundExecute for Chargebee {} impl api::RefundSync for Chargebee {} impl api::PaymentToken for Chargebee {} + #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl api::revenue_recovery::RevenueRecoveryRecordBack for Chargebee {} @@ -792,6 +796,112 @@ impl // Not implemented (R) } +impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> + for Chargebee +{ + fn get_headers( + &self, + req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let metadata: chargebee::ChargebeeMetadata = + utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?; + + let site = metadata.site.peek(); + + let mut base = self.base_url(connectors).to_string(); + + base = base.replace("{{merchant_endpoint_prefix}}", site); + base = base.replace("$", site); + + if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') { + return Err(errors::ConnectorError::InvalidConnectorConfig { + config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).", + } + .into()); + } + + if !base.ends_with('/') { + base.push('/'); + } + + let url = format!("{base}v2/customers"); + Ok(url) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_request_body( + &self, + req: &ConnectorCustomerRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = chargebee::ChargebeeRouterData::from((MinorUnit::new(0), req)); + let connector_req = + chargebee::ChargebeeCustomerCreateRequest::try_from(&connector_router_data)?; + Ok(RequestContent::FormUrlEncoded(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>, + res: Response, + ) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError> { + let response: chargebee::ChargebeeCustomerCreateResponse = res + .response + .parse_struct("ChargebeeCustomerCreateResponse") + .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 Chargebee { fn get_webhook_source_verification_signature( diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 721f50a52fb..f5b950a1b04 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -2,7 +2,13 @@ use std::str::FromStr; use common_enums::enums; -use common_utils::{errors::CustomResult, ext_traits::ByteSliceExt, pii, types::MinorUnit}; +use common_utils::{ + errors::CustomResult, + ext_traits::ByteSliceExt, + id_type::CustomerId, + pii::{self, Email}, + types::MinorUnit, +}; use error_stack::ResultExt; #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use hyperswitch_domain_models::revenue_recovery; @@ -11,17 +17,19 @@ use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::{ refunds::{Execute, RSync}, - InvoiceRecordBack, + CreateConnectorCustomer, InvoiceRecordBack, + }, + router_request_types::{ + revenue_recovery::InvoiceRecordBackRequest, ConnectorCustomerData, ResponseId, }, - router_request_types::{revenue_recovery::InvoiceRecordBackRequest, ResponseId}, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::GetSubscriptionPlansResponse, - PaymentsResponseData, RefundsResponseData, + ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData, }, types::{InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -821,3 +829,94 @@ impl<F, T> }) } } + +#[derive(Debug, Serialize)] +pub struct ChargebeeCustomerCreateRequest { + #[serde(rename = "id")] + pub customer_id: CustomerId, + #[serde(rename = "first_name")] + pub name: Option<Secret<String>>, + pub email: Option<Email>, + pub billing_address: Option<api_models::payments::AddressDetails>, +} + +impl TryFrom<&ChargebeeRouterData<&hyperswitch_domain_models::types::ConnectorCustomerRouterData>> + for ChargebeeCustomerCreateRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + item: &ChargebeeRouterData<&hyperswitch_domain_models::types::ConnectorCustomerRouterData>, + ) -> Result<Self, Self::Error> { + let req = &item.router_data.request; + + Ok(Self { + customer_id: req + .customer_id + .as_ref() + .ok_or_else(|| errors::ConnectorError::MissingRequiredField { + field_name: "customer_id", + })? + .clone(), + name: req.name.clone(), + email: req.email.clone(), + billing_address: req.billing_address.clone(), + }) + } +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct ChargebeeCustomerCreateResponse { + pub customer: ChargebeeCustomerDetails, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct ChargebeeCustomerDetails { + pub id: String, + #[serde(rename = "first_name")] + pub name: Option<Secret<String>>, + pub email: Option<Email>, + pub billing_address: Option<api_models::payments::AddressDetails>, +} + +impl + TryFrom< + ResponseRouterData< + CreateConnectorCustomer, + ChargebeeCustomerCreateResponse, + ConnectorCustomerData, + PaymentsResponseData, + >, + > for hyperswitch_domain_models::types::ConnectorCustomerRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + item: ResponseRouterData< + CreateConnectorCustomer, + ChargebeeCustomerCreateResponse, + ConnectorCustomerData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let customer_response = &item.response.customer; + + Ok(Self { + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new( + customer_response.id.clone(), + customer_response + .name + .as_ref() + .map(|name| name.clone().expose()), + customer_response + .email + .as_ref() + .map(|email| email.clone().expose().expose()), + customer_response.billing_address.clone(), + ), + )), + ..item.data + }) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/dwolla.rs b/crates/hyperswitch_connectors/src/connectors/dwolla.rs index a66e05e7e4c..001436b7797 100644 --- a/crates/hyperswitch_connectors/src/connectors/dwolla.rs +++ b/crates/hyperswitch_connectors/src/connectors/dwolla.rs @@ -27,8 +27,8 @@ use hyperswitch_domain_models::{ PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData, }, router_response_types::{ - ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, - SupportedPaymentMethods, SupportedPaymentMethodsExt, + ConnectorCustomerResponseData, ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, + RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsSyncRouterData, @@ -346,9 +346,9 @@ impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, Paymen Ok(RouterData { connector_customer: Some(connector_customer_id.clone()), - response: Ok(PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - }), + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id(connector_customer_id), + )), ..data.clone() }) } diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs index 3d8c57fb6e0..955691a11f2 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs @@ -16,7 +16,9 @@ use hyperswitch_domain_models::{ refunds::{Execute, RSync}, }, router_request_types::{PaymentsCancelData, ResponseId}, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData, + }, types, }; use hyperswitch_interfaces::{ @@ -372,9 +374,11 @@ impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayCustomerResponse, T, Payment item: ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id: item.response.data.customer_id.expose(), - }), + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id( + item.response.data.customer_id.expose(), + ), + )), ..item.data }) } diff --git a/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs index 29f9525b944..b4019d98e1e 100644 --- a/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs @@ -13,7 +13,9 @@ use hyperswitch_domain_models::{ ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsSyncData, ResponseId, SetupMandateRequestData, }, - router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RefundsResponseData, + }, types, }; use hyperswitch_interfaces::errors; @@ -152,9 +154,11 @@ impl<F> >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id: item.response.customers.id.expose(), - }), + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id( + item.response.customers.id.expose(), + ), + )), ..item.data }) } diff --git a/crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs b/crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs index 220e2e55440..cb2ddd67722 100644 --- a/crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs @@ -2,7 +2,9 @@ use common_utils::pii::Email; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::vault::ExternalVaultCreateFlow, - router_response_types::{PaymentsResponseData, VaultResponseData}, + router_response_types::{ + ConnectorCustomerResponseData, PaymentsResponseData, VaultResponseData, + }, types::{ConnectorCustomerRouterData, VaultRouterData}, }; use hyperswitch_interfaces::errors; @@ -108,9 +110,9 @@ impl<F, T> >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id: item.response.id, - }), + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id(item.response.id), + )), ..item.data }) } diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs index 07515761e72..29f673302cc 100644 --- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs @@ -6,7 +6,9 @@ use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData, + }, types, }; use hyperswitch_interfaces::{api, errors}; @@ -196,9 +198,9 @@ impl<F, T> TryFrom<ResponseRouterData<F, StaxCustomerResponse, T, PaymentsRespon item: ResponseRouterData<F, StaxCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id: item.response.id.expose(), - }), + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id(item.response.id.expose()), + )), ..item.data }) } diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index cbedbd62704..c7b728db21f 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -31,8 +31,8 @@ use hyperswitch_domain_models::{ PaymentsIncrementalAuthorizationData, ResponseId, SplitRefundsRequest, }, router_response_types::{ - MandateReference, PaymentsResponseData, PreprocessingResponseId, RedirectForm, - RefundsResponseData, + ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, + PreprocessingResponseId, RedirectForm, RefundsResponseData, }, types::{ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, @@ -4136,9 +4136,9 @@ impl<F, T> TryFrom<ResponseRouterData<F, StripeCustomerResponse, T, PaymentsResp item: ResponseRouterData<F, StripeCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id: item.response.id, - }), + response: Ok(PaymentsResponseData::ConnectorCustomerResponse( + ConnectorCustomerResponseData::new_with_customer_id(item.response.id), + )), ..item.data }) } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 1e404df7f97..9d131d006b2 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -1441,7 +1441,6 @@ default_imp_for_create_customer!( connectors::Breadpay, connectors::Cashtocode, connectors::Celero, - connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index b97675006ed..38e44ef88fe 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -3,7 +3,7 @@ pub mod fraud_check; pub mod revenue_recovery; pub mod subscriptions; pub mod unified_authentication_service; -use api_models::payments::{AdditionalPaymentData, RequestSurchargeDetails}; +use api_models::payments::{AdditionalPaymentData, AddressDetails, RequestSurchargeDetails}; use common_types::payments as common_payments_types; use common_utils::{consts, errors, ext_traits::OptionExt, id_type, pii, types::MinorUnit}; use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount}; @@ -183,6 +183,8 @@ impl split_payments: data.request.split_payments.clone(), setup_future_usage: data.request.setup_future_usage, customer_acceptance: data.request.customer_acceptance.clone(), + customer_id: None, + billing_address: None, }) } } @@ -289,6 +291,8 @@ pub struct ConnectorCustomerData { // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, + pub customer_id: Option<id_type::CustomerId>, + pub billing_address: Option<AddressDetails>, } impl TryFrom<SetupMandateRequestData> for ConnectorCustomerData { @@ -304,6 +308,8 @@ impl TryFrom<SetupMandateRequestData> for ConnectorCustomerData { split_payments: None, setup_future_usage: data.setup_future_usage, customer_acceptance: data.customer_acceptance, + customer_id: None, + billing_address: None, }) } } @@ -363,6 +369,8 @@ impl split_payments: data.request.split_payments.clone(), setup_future_usage: data.request.setup_future_usage, customer_acceptance: data.request.customer_acceptance.clone(), + customer_id: None, + billing_address: None, }) } } @@ -389,6 +397,8 @@ impl TryFrom<&RouterData<flows::Session, PaymentsSessionData, response_types::Pa split_payments: None, setup_future_usage: None, customer_acceptance: None, + customer_id: None, + billing_address: None, }) } } diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index cc766a00ba8..197472bf26f 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -4,6 +4,7 @@ pub mod revenue_recovery; pub mod subscriptions; use std::collections::HashMap; +use api_models::payments::AddressDetails; use common_utils::{pii, request::Method, types::MinorUnit}; pub use disputes::{ AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, @@ -23,6 +24,33 @@ pub struct RefundsResponseData { // pub amount_received: Option<i32>, // Calculation for amount received not in place yet } +#[derive(Debug, Clone)] +pub struct ConnectorCustomerResponseData { + pub connector_customer_id: String, + pub name: Option<String>, + pub email: Option<String>, + pub billing_address: Option<AddressDetails>, +} + +impl ConnectorCustomerResponseData { + pub fn new_with_customer_id(connector_customer_id: String) -> Self { + Self::new(connector_customer_id, None, None, None) + } + pub fn new( + connector_customer_id: String, + name: Option<String>, + email: Option<String>, + billing_address: Option<AddressDetails>, + ) -> Self { + Self { + connector_customer_id, + name, + email, + billing_address, + } + } +} + #[derive(Debug, Clone)] pub enum PaymentsResponseData { TransactionResponse { @@ -55,9 +83,7 @@ pub enum PaymentsResponseData { token: String, }, - ConnectorCustomerResponse { - connector_customer_id: String, - }, + ConnectorCustomerResponse(ConnectorCustomerResponseData), ThreeDSEnrollmentResponse { enrolled_v2: bool, diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions.rs b/crates/hyperswitch_interfaces/src/api/subscriptions.rs index a9e53ec5603..1f911940d2f 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions.rs @@ -7,7 +7,9 @@ use hyperswitch_domain_models::{ }; #[cfg(feature = "v1")] -use super::{ConnectorCommon, ConnectorIntegration}; +use super::{ + payments::ConnectorCustomer as PaymentsConnectorCustomer, ConnectorCommon, ConnectorIntegration, +}; #[cfg(feature = "v1")] /// trait GetSubscriptionPlans for V1 @@ -22,7 +24,10 @@ pub trait GetSubscriptionPlansFlow: /// trait Subscriptions #[cfg(feature = "v1")] -pub trait Subscriptions: ConnectorCommon + GetSubscriptionPlansFlow {} +pub trait Subscriptions: + ConnectorCommon + GetSubscriptionPlansFlow + PaymentsConnectorCustomer +{ +} /// trait Subscriptions (disabled when not V1) #[cfg(not(feature = "v1"))] @@ -31,3 +36,7 @@ pub trait Subscriptions {} /// trait GetSubscriptionPlansFlow (disabled when not V1) #[cfg(not(feature = "v1"))] pub trait GetSubscriptionPlansFlow {} + +#[cfg(not(feature = "v1"))] +/// trait CreateCustomer (disabled when not V1) +pub trait ConnectorCustomer {} diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs index 5a37b013ef4..ba8b54062fa 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs @@ -6,10 +6,11 @@ use hyperswitch_domain_models::{ router_response_types::subscriptions::GetSubscriptionPlansResponse, }; +use super::payments_v2::ConnectorCustomerV2; use crate::connector_integration_v2::ConnectorIntegrationV2; /// trait SubscriptionsV2 -pub trait SubscriptionsV2: GetSubscriptionPlansV2 {} +pub trait SubscriptionsV2: GetSubscriptionPlansV2 + ConnectorCustomerV2 {} /// trait GetSubscriptionPlans for V1 pub trait GetSubscriptionPlansV2: diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index e263735b8af..7125c9b3b00 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -373,3 +373,11 @@ impl Default for Proxy { } } } + +/// Type alias for `ConnectorIntegrationV2<CreateConnectorCustomer, PaymentFlowData, ConnectorCustomerData, PaymentsResponseData>` +pub type CreateCustomerTypeV2 = dyn ConnectorIntegrationV2< + CreateConnectorCustomer, + flow_common_types::PaymentFlowData, + ConnectorCustomerData, + PaymentsResponseData, +>; diff --git a/crates/router/src/core/payments/customers.rs b/crates/router/src/core/payments/customers.rs index d1fc40aef39..f3926365cbe 100644 --- a/crates/router/src/core/payments/customers.rs +++ b/crates/router/src/core/payments/customers.rs @@ -60,9 +60,9 @@ pub async fn create_connector_customer<F: Clone, T: Clone>( let connector_customer_id = match resp.response { Ok(response) => match response { - types::PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - } => Some(connector_customer_id), + types::PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { + Some(customer_data.connector_customer_id) + } _ => None, }, Err(err) => { diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 2b1d1024e76..292a668a07c 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1997,7 +1997,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( types::PaymentsResponseData::TokenizationResponse { .. } => { (None, None, None) } - types::PaymentsResponseData::ConnectorCustomerResponse { .. } => { + types::PaymentsResponseData::ConnectorCustomerResponse(..) => { (None, None, None) } types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => { diff --git a/crates/router/tests/connectors/stax.rs b/crates/router/tests/connectors/stax.rs index 89b1bc7f4b9..69e241edd3b 100644 --- a/crates/router/tests/connectors/stax.rs +++ b/crates/router/tests/connectors/stax.rs @@ -92,9 +92,9 @@ async fn create_customer_and_get_token() -> Option<String> { .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { - PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - } => Some(connector_customer_id), + PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { + Some(customer_data.connector_customer_id) + } _ => None, }; @@ -468,9 +468,9 @@ async fn should_fail_payment_for_incorrect_cvc() { .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { - PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - } => Some(connector_customer_id), + PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { + Some(customer_data.connector_customer_id) + } _ => None, }; @@ -511,9 +511,9 @@ async fn should_fail_payment_for_invalid_exp_month() { .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { - PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - } => Some(connector_customer_id), + PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { + Some(customer_data.connector_customer_id) + } _ => None, }; @@ -554,9 +554,9 @@ async fn should_fail_payment_for_incorrect_expiry_year() { .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { - PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id, - } => Some(connector_customer_id), + PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { + Some(customer_data.connector_customer_id) + } _ => None, }; diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index c35654719fb..9394752fb90 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -573,7 +573,7 @@ pub trait ConnectorActions: Connector { Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, - Ok(types::PaymentsResponseData::ConnectorCustomerResponse { .. }) => None, + Ok(types::PaymentsResponseData::ConnectorCustomerResponse(..)) => None, Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, @@ -1117,6 +1117,8 @@ impl Default for CustomerType { split_payments: None, customer_acceptance: None, setup_future_usage: None, + customer_id: None, + billing_address: None, }; Self(data) } @@ -1151,7 +1153,7 @@ pub fn get_connector_transaction_id( Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None, - Ok(types::PaymentsResponseData::ConnectorCustomerResponse { .. }) => None, + Ok(types::PaymentsResponseData::ConnectorCustomerResponse(..)) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None,
2025-09-08T11:04:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ### Summary This PR introduces a **create customer handler for the Chargebee connector**. It enables merchants to create and manage customers in Chargebee directly through Hyperswitch by mapping customer data between our domain models and Chargebee’s API. ### Key Changes * **New Connector Integration** * Added `ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>` implementation for Chargebee. * Added response mapper to convert Chargebee’s response into `PaymentsResponseData::ConnectorCustomerResponse`. * **Extended Response Model** * `ConnectorCustomerResponse` now carries optional fields: * `name` * `email` * `billing_address` * **Domain Models & Flow Types** * Extended `ConnectorCustomerData` to support new fields (`customer_id`, `billing_address`). ### Benefits * Merchants can now **create customers in Chargebee** via Hyperswitch. * Unified model for customer creation across connectors. * Future-proofing: response carries richer customer metadata, making subscription flows easier to support. ## How did you test it? cargo r <img width="1723" height="1065" alt="Screenshot 2025-09-10 at 4 11 52 PM" src="https://github.com/user-attachments/assets/10a67220-94f8-4d92-950d-acc933d11de0" /> just clippy <img width="1699" height="455" alt="Screenshot 2025-09-10 at 4 17 39 PM" src="https://github.com/user-attachments/assets/5ad6b2f9-84d0-4434-ad4e-ed98fbccc8eb" /> just clippy_v2 <img width="1728" height="459" alt="Screenshot 2025-09-10 at 4 22 46 PM" src="https://github.com/user-attachments/assets/65336216-67e5-4900-b638-c6543bb47b83" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
f3ab3d63f69279af9254f15eba5654c0680a0747
juspay/hyperswitch
juspay__hyperswitch-9293
Bug: [BUG] Post capture void in nuvei resulting in `partial_captured` instead of `cancelled_post_capture` ### Bug Description Make a automatic (successful) nuvei payment ```json { "amount": 4324, "capture_method": "automatic", "currency": "EUR", "confirm": true, "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" } }, "connector":["nuvei"], "customer_id": "nidthxxinn", "return_url": "https://www.google.com", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "[email protected]", "payment_method_data": { "card": { "card_number": "4000000000009995", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } } } ``` ## post capture void ```json curl --location 'localhost:8080/payments/pay_o40YH0Mu3Dyv1uHM9qQ1/cancel_post_capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_HmswxSLAU3iCrFmcLOha4WYjM9fLTazyr39hYPPbNbRJEeVCVdQq2KwAbzrXZQ8N' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` ## Response ```json { "payment_id": "pay_BPAMSLv9apKd34AY6cUH", "merchant_id": "merchant_1756789409", "status": "partially_captured", "amount": 4324, "net_amount": 4324, "shipping_cost": null, "amount_capturable": 0, "amount_received": 4324, "connector": "nuvei", "client_secret": "pay_BPAMSLv9apKd34AY6cUH_secret_RfhKfM0p2MIkaRpZ5bs3", "created": "2025-09-07T05:22:50.859Z", "currency": "EUR", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "9995", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "INTL HDQTRS-CENTER OWNED", "card_issuing_country": "UNITEDSTATES", "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_Eap5TljtgSZHikmOYd37", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "8110000000013734833", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8566793111", "payment_link": null, "profile_id": "pro_EzO6xGQZdE5pd9I5Rdzs", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_i5QVCDvXmBLbZg7n97n2", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-07T05:37:50.859Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_Aw1IrDbk9NErXLkw6Bvc", "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-07T05:22:57.510Z", "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, "enable_partial_authorization": null } ``` ### Expected Behavior Response of {{baseUrl}}/payments/{{payment_id}}/cancel_post_capture : "status": "cancelled_post_capture", ### Actual Behavior Response of {{baseUrl}}/payments/{{payment_id}}/cancel_post_capture : "status": "partially_captured", ### Steps To Reproduce - ### 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/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 791261d9ee0..6c26964612d 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -2180,6 +2180,7 @@ pub struct FraudDetails { fn get_payment_status( response: &NuveiPaymentsResponse, amount: Option<i64>, + is_post_capture_void: bool, ) -> enums::AttemptStatus { // ZERO dollar authorization if amount == Some(0) && response.transaction_type.clone() == Some(NuveiTransactionType::Auth) { @@ -2200,6 +2201,7 @@ fn get_payment_status( }, }; } + match response.transaction_status.clone() { Some(status) => match status { NuveiTransactionStatus::Approved => match response.transaction_type { @@ -2207,7 +2209,11 @@ fn get_payment_status( Some(NuveiTransactionType::Sale) | Some(NuveiTransactionType::Settle) => { enums::AttemptStatus::Charged } + Some(NuveiTransactionType::Void) if is_post_capture_void => { + enums::AttemptStatus::VoidedPostCharge + } Some(NuveiTransactionType::Void) => enums::AttemptStatus::Voided, + _ => enums::AttemptStatus::Pending, }, NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => { @@ -2268,13 +2274,21 @@ fn build_error_response(response: &NuveiPaymentsResponse, http_code: u16) -> Opt } } -pub trait NuveiPaymentsGenericResponse {} +pub trait NuveiPaymentsGenericResponse { + fn is_post_capture_void() -> bool { + false + } +} impl NuveiPaymentsGenericResponse for CompleteAuthorize {} impl NuveiPaymentsGenericResponse for Void {} impl NuveiPaymentsGenericResponse for PSync {} impl NuveiPaymentsGenericResponse for Capture {} -impl NuveiPaymentsGenericResponse for PostCaptureVoid {} +impl NuveiPaymentsGenericResponse for PostCaptureVoid { + fn is_post_capture_void() -> bool { + true + } +} impl TryFrom< @@ -2298,7 +2312,7 @@ impl let amount = item.data.request.amount; let (status, redirection_data, connector_response_data) = - process_nuvei_payment_response(&item, amount)?; + process_nuvei_payment_response(&item, amount, false)?; let (amount_captured, minor_amount_capturable) = item.response.get_amount_captured()?; @@ -2341,6 +2355,7 @@ impl fn process_nuvei_payment_response<F, T>( item: &ResponseRouterData<F, NuveiPaymentsResponse, T, PaymentsResponseData>, amount: Option<i64>, + is_post_capture_void: bool, ) -> Result< ( enums::AttemptStatus, @@ -2377,7 +2392,7 @@ where convert_to_additional_payment_method_connector_response(&item.response) .map(ConnectorResponseData::with_additional_payment_method_data); - let status = get_payment_status(&item.response, amount); + let status = get_payment_status(&item.response, amount, is_post_capture_void); Ok((status, redirection_data, connector_response_data)) } @@ -2451,7 +2466,7 @@ impl let amount = Some(item.data.request.amount); let (status, redirection_data, connector_response_data) = - process_nuvei_payment_response(&item, amount)?; + process_nuvei_payment_response(&item, amount, false)?; let (amount_captured, minor_amount_capturable) = item.response.get_amount_captured()?; @@ -2497,9 +2512,8 @@ where .data .minor_amount_capturable .map(|amount| amount.get_amount_as_i64()); - let (status, redirection_data, connector_response_data) = - process_nuvei_payment_response(&item, amount)?; + process_nuvei_payment_response(&item, amount, F::is_post_capture_void())?; let (amount_captured, minor_amount_capturable) = item.response.get_amount_captured()?; Ok(Self { @@ -2538,7 +2552,7 @@ impl TryFrom<PaymentsPreprocessingResponseRouterData<NuveiPaymentsResponse>> .map(to_boolean) .unwrap_or_default(); Ok(Self { - status: get_payment_status(&response, item.data.request.amount), + status: get_payment_status(&response, item.data.request.amount, false), response: Ok(PaymentsResponseData::ThreeDSEnrollmentResponse { enrolled_v2: is_enrolled_for_3ds, related_transaction_id: response.transaction_id,
2025-09-07T05:24:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - previously post capture void in nuvei was resulting in `partially_captured` response in hyperswitch, Ideally it should give `cancelled_post_capture`. - Cause we were passing `Voided` payment instead of `VoidedPostCharge` . Ideally it should move to payment Request ```json { "amount": 4324, "capture_method": "automatic", "currency": "EUR", "confirm": true, "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "connector":["nuvei"], "customer_id": "nidthxxinn", "return_url": "https://www.google.com", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "[email protected]", "payment_method_data": { "card": { "card_number": "4000000000009995", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } } } ``` ## Response ```json { "payment_id": "pay_BPAMSLv9apKd34AY6cUH", "merchant_id": "merchant_1756789409", "status": "succeeded", "amount": 4324, "net_amount": 4324, "shipping_cost": null, "amount_capturable": 0, "amount_received": 4324, "connector": "nuvei", "client_secret": "pay_BPAMSLv9apKd34AY6cUH_secret_RfhKfM0p2MIkaRpZ5bs3", "created": "2025-09-07T05:22:50.859Z", "currency": "EUR", "customer_id": "nidthxxinn", "customer": { "id": "nidthxxinn", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "9995", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "INTL HDQTRS-CENTER OWNED", "card_issuing_country": "UNITEDSTATES", "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_Eap5TljtgSZHikmOYd37", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nidthxxinn", "created_at": 1757222570, "expires": 1757226170, "secret": "epk_0a5ce9afbec14498b36893a4d66ad916" }, "manual_retry_allowed": false, "connector_transaction_id": "8110000000013734831", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8566793111", "payment_link": null, "profile_id": "pro_EzO6xGQZdE5pd9I5Rdzs", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_i5QVCDvXmBLbZg7n97n2", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-07T05:37:50.859Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-07T05:22:53.495Z", "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, "enable_partial_authorization": null } ``` ## post capture request ```sh curl --location 'localhost:8080/payments/pay_BPAMSLv9apKd34AY6cUH/cancel_post_capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_HmswxSLAU3iCrFmcLOha4WYjM9fLTazyr39hYPPbNbRJEeVCVdQq2KwAbzrXZQ8N' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` ## Post capture response ```json { "payment_id": "pay_BPAMSLv9apKd34AY6cUH", "merchant_id": "merchant_1756789409", "status": "cancelled_post_capture", "amount": 4324, "net_amount": 4324, "shipping_cost": null, "amount_capturable": 0, "amount_received": 4324, "connector": "nuvei", "client_secret": "pay_BPAMSLv9apKd34AY6cUH_secret_RfhKfM0p2MIkaRpZ5bs3", "created": "2025-09-07T05:22:50.859Z", "currency": "EUR", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "9995", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "INTL HDQTRS-CENTER OWNED", "card_issuing_country": "UNITEDSTATES", "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_Eap5TljtgSZHikmOYd37", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "8110000000013734833", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8566793111", "payment_link": null, "profile_id": "pro_EzO6xGQZdE5pd9I5Rdzs", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_i5QVCDvXmBLbZg7n97n2", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-07T05:37:50.859Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_Aw1IrDbk9NErXLkw6Bvc", "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-07T05:22:57.510Z", "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, "enable_partial_authorization": null } ``` ## make a manual request and call void for sanity ```json { "payment_id": "pay_o40YH0Mu3Dyv1uHM9qQ1", "merchant_id": "merchant_1756789409", "status": "cancelled", "amount": 4324, "net_amount": 4324, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_o40YH0Mu3Dyv1uHM9qQ1_secret_bkgxvGpkIZGQT8asrsLq", "created": "2025-09-07T05:31:32.909Z", "currency": "EUR", "customer_id": "nidthxxinn", "customer": { "id": "nidthxxinn", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "9995", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "INTL HDQTRS-CENTER OWNED", "card_issuing_country": "UNITEDSTATES", "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_pZf0tkyWL08kGOlyPTeL", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": "requested_by_customer", "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "8110000000013735128", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8566843111", "payment_link": null, "profile_id": "pro_EzO6xGQZdE5pd9I5Rdzs", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_i5QVCDvXmBLbZg7n97n2", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-07T05:46:32.908Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_lJ8QqYSKpiCmkefL59n1", "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-07T05:31:40.915Z", "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, "enable_partial_authorization": null } ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
641cd8d2a20c93e0ec7e20d362451c345fd6ad3e
juspay/hyperswitch
juspay__hyperswitch-9291
Bug: [FEATURE] L2 L3 data support for nuvei ### Feature Description Add support for L2 & L3 Data support for nuvei ### Possible Implementation - ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 355e6f0c4ff..0e032c3c804 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -19,7 +19,7 @@ use hyperswitch_domain_models::{ }, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, - ErrorResponse, RouterData, + ErrorResponse, L2L3Data, RouterData, }, router_flow_types::{ refunds::{Execute, RSync}, @@ -94,9 +94,6 @@ trait NuveiAuthorizePreprocessingCommon { &self, ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>>; fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag>; - fn get_order_tax_amount( - &self, - ) -> Result<Option<MinorUnit>, error_stack::Report<errors::ConnectorError>>; fn is_customer_initiated_mandate_payment(&self) -> bool; } @@ -158,11 +155,6 @@ impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData { ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> { Ok(self.payment_method_data.clone()) } - fn get_order_tax_amount( - &self, - ) -> Result<Option<MinorUnit>, error_stack::Report<errors::ConnectorError>> { - Ok(None) - } fn get_minor_amount_required( &self, @@ -243,11 +235,6 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> { Ok(self.payment_method_data.clone()) } - fn get_order_tax_amount( - &self, - ) -> Result<Option<MinorUnit>, error_stack::Report<errors::ConnectorError>> { - Ok(self.order_tax_amount) - } fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { self.get_email() @@ -325,11 +312,6 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { .into(), ) } - fn get_order_tax_amount( - &self, - ) -> Result<Option<MinorUnit>, error_stack::Report<errors::ConnectorError>> { - Ok(None) - } fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag> { None @@ -376,8 +358,62 @@ pub struct NuveiSessionResponse { #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] -pub struct NuvieAmountDetails { - total_tax: Option<StringMajorUnit>, +pub struct NuveiAmountDetails { + pub total_tax: Option<StringMajorUnit>, + pub total_shipping: Option<StringMajorUnit>, + pub total_handling: Option<StringMajorUnit>, + pub total_discount: Option<StringMajorUnit>, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Default)] +#[serde(rename_all = "snake_case")] +pub enum NuveiItemType { + #[default] + Physical, + Discount, + #[serde(rename = "Shipping_fee")] + ShippingFee, + Digital, + #[serde(rename = "Gift_card")] + GiftCard, + #[serde(rename = "Store_credit")] + StoreCredit, + Surcharge, + #[serde(rename = "Sales_tax")] + SalesTax, +} +impl From<Option<enums::ProductType>> for NuveiItemType { + fn from(value: Option<enums::ProductType>) -> Self { + match value { + Some(enums::ProductType::Digital) => Self::Digital, + Some(enums::ProductType::Physical) => Self::Physical, + Some(enums::ProductType::Ride) + | Some(enums::ProductType::Travel) + | Some(enums::ProductType::Accommodation) => Self::ShippingFee, + _ => Self::Physical, + } + } +} + +#[serde_with::skip_serializing_none] +#[derive(Debug, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct NuveiItem { + pub name: String, + #[serde(rename = "type")] + pub item_type: NuveiItemType, + pub price: StringMajorUnit, + pub quantity: String, + pub group_id: Option<String>, + pub discount: Option<StringMajorUnit>, + pub discount_rate: Option<String>, + pub shipping: Option<StringMajorUnit>, + pub shipping_tax: Option<StringMajorUnit>, + pub shipping_tax_rate: Option<String>, + pub tax: Option<StringMajorUnit>, + pub tax_rate: Option<String>, + pub image_url: Option<String>, + pub product_url: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Serialize, Default)] @@ -404,7 +440,8 @@ pub struct NuveiPaymentsRequest { pub shipping_address: Option<ShippingAddress>, pub related_transaction_id: Option<String>, pub url_details: Option<UrlDetails>, - pub amount_details: Option<NuvieAmountDetails>, + pub amount_details: Option<NuveiAmountDetails>, + pub items: Option<Vec<NuveiItem>>, pub is_partial_approval: Option<PartialApprovalFlag>, pub external_scheme_details: Option<ExternalSchemeDetails>, } @@ -1424,6 +1461,94 @@ where ..Default::default() }) } +fn get_l2_l3_items( + l2_l3_data: &Option<L2L3Data>, + currency: enums::Currency, +) -> Result<Option<Vec<NuveiItem>>, error_stack::Report<errors::ConnectorError>> { + l2_l3_data.as_ref().map_or(Ok(None), |data| { + data.order_details + .as_ref() + .map_or(Ok(None), |order_details_list| { + // Map each order to a Result<NuveiItem> + let results: Vec<Result<NuveiItem, error_stack::Report<errors::ConnectorError>>> = + order_details_list + .iter() + .map(|order| { + let discount = order + .unit_discount_amount + .map(|amount| { + convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency) + }) + .transpose()?; + let tax = order + .total_tax_amount + .map(|amount| { + convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency) + }) + .transpose()?; + Ok(NuveiItem { + name: order.product_name.clone(), + item_type: order.product_type.clone().into(), + price: convert_amount( + NUVEI_AMOUNT_CONVERTOR, + order.amount, + currency, + )?, + quantity: order.quantity.to_string(), + group_id: order.product_id.clone(), + discount, + discount_rate: None, + shipping: None, + shipping_tax: None, + shipping_tax_rate: None, + tax, + tax_rate: order.tax_rate.map(|rate| rate.to_string()), + image_url: order.product_img_link.clone(), + product_url: None, + }) + }) + .collect(); + let mut items = Vec::with_capacity(results.len()); + for result in results { + match result { + Ok(item) => items.push(item), + Err(err) => return Err(err), + } + } + Ok(Some(items)) + }) + }) +} + +fn get_amount_details( + l2_l3_data: &Option<L2L3Data>, + currency: enums::Currency, +) -> Result<Option<NuveiAmountDetails>, error_stack::Report<errors::ConnectorError>> { + l2_l3_data.as_ref().map_or(Ok(None), |data| { + let total_tax = data + .order_tax_amount + .map(|amount| convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency)) + .transpose()?; + let total_shipping = data + .shipping_cost + .map(|amount| convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency)) + .transpose()?; + let total_discount = data + .discount_amount + .map(|amount| convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency)) + .transpose()?; + let total_handling = data + .duty_amount + .map(|amount| convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency)) + .transpose()?; + Ok(Some(NuveiAmountDetails { + total_tax, + total_shipping, + total_handling, + total_discount, + })) + }) +} impl<F, Req> TryFrom<(&RouterData<F, Req, PaymentsResponseData>, String)> for NuveiPaymentsRequest where @@ -1578,12 +1703,8 @@ where })?; let return_url = item.request.get_return_url_required()?; - let amount_details = match item.request.get_order_tax_amount()? { - Some(tax) => Some(NuvieAmountDetails { - total_tax: Some(convert_amount(NUVEI_AMOUNT_CONVERTOR, tax, currency)?), - }), - None => None, - }; + let amount_details = get_amount_details(&item.l2_l3_data, currency)?; + let l2_l3_items: Option<Vec<NuveiItem>> = get_l2_l3_items(&item.l2_l3_data, currency)?; let address = { if let Some(billing_address) = item.get_optional_billing() { let mut billing_address = billing_address.clone(); @@ -1631,6 +1752,7 @@ where pending_url: return_url.clone(), }), amount_details, + items: l2_l3_items, is_partial_approval: item.request.get_is_partial_approval(), ..request }) @@ -3011,9 +3133,9 @@ fn convert_to_additional_payment_method_connector_response( merchant_advice_code.and_then(|code| get_merchant_advice_code_description(code)); let payment_checks = serde_json::json!({ - "avs_result_code": avs_code, + "avs_result": avs_code, "avs_description": avs_description, - "cvv_2_reply_code": cvv2_code, + "cvv_2_reply": cvv2_code, "cvv_2_description": cvv_description, "merchant_advice_code": merchant_advice_code, "merchant_advice_code_description": merchant_advice_description
2025-09-07T03:58:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Include support for L2L3Data for nuvei connector - L2L3 data is primarily used for B2B, government, and corporate card transactions where detailed purchase information is required for lower interchange rates and compliance purposes. - `NOTE` : In Nuvei shipping details can be passed for each item but we are not supporting it as of now as it will be included if required practically. Other connectors doesn't support this <details> <summary> Payment test </summary> # Request ```json { "amount": 4324, "currency": "EUR", "confirm": true, "setup_future_usage": "on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "connector": [ "nuvei" ], "customer_id": "nidthxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "[email protected]", "payment_method_data": { "card": { "card_number": "4000000000009995", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } }, // l2 l3 data 's "order_tax_amount": 8900, "shipping_cost": 8299, "discount_amount": 3000, "duty_amount": 2409, "order_details": [ //l2 l3data { "product_name": "Laptop", "quantity": 1, "amount": 8000, "description": "Business laptop 23214324", "sku": "LAP-001", "upc": "123456789012", "commodity_code": "8471", "unit_of_measure": "EA", "unit_price": 8000, "unit_discount_amount": 200, "tax_rate": 0.08, "total_tax_amount": 640 }, { "product_name": "Mouse", "quantity": 2, "amount": 2000, "description": "Wireless office mouse", "sku": "MOU-001", "upc": "123456789013", "commodity_code": "8471", "unit_of_measure": "EA", "unit_price": 1000, "unit_discount_amount": 50, "tax_rate": 0.08, "total_tax_amount": 160 } ] } ``` # Response ```json { "payment_id": "pay_t0Izz9tAgCQtylk9Mcbf", "merchant_id": "merchant_1756789409", "status": "succeeded", "amount": 4324, "net_amount": 12623, "shipping_cost": 8299, "amount_capturable": 0, "amount_received": 12623, "connector": "nuvei", "client_secret": "pay_t0Izz9tAgCQtylk9Mcbf_secret_cjXmBdaE9S6gTQorZcq8", "created": "2025-09-07T03:38:00.787Z", "currency": "EUR", "customer_id": "nidthxxinn", "customer": { "id": "nidthxxinn", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "9995", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "INTL HDQTRS-CENTER OWNED", "card_issuing_country": "UNITEDSTATES", "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_result": "", "cvv_2_reply": "", "avs_description": null, "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_pKckYLN5M2Qcs4MJuGDz", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": [ { "sku": "LAP-001", "upc": "123456789012", "brand": null, "amount": 8000, "category": null, "quantity": 1, "tax_rate": 0.08, "product_id": null, "description": "Business laptop 23214324", "product_name": "Laptop", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": "8471", "unit_of_measure": "EA", "product_img_link": null, "product_tax_code": null, "total_tax_amount": 640, "requires_shipping": null, "unit_discount_amount": 200 }, { "sku": "MOU-001", "upc": "123456789013", "brand": null, "amount": 2000, "category": null, "quantity": 2, "tax_rate": 0.08, "product_id": null, "description": "Wireless office mouse", "product_name": "Mouse", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": "8471", "unit_of_measure": "EA", "product_img_link": null, "product_tax_code": null, "total_tax_amount": 160, "requires_shipping": null, "unit_discount_amount": 50 } ], "email": "[email protected]", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nidthxxinn", "created_at": 1757216280, "expires": 1757219880, "secret": "epk_e4ed9423c18546afac8b4c6540f4b193" }, "manual_retry_allowed": false, "connector_transaction_id": "8110000000013731386", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8566044111", "payment_link": null, "profile_id": "pro_EzO6xGQZdE5pd9I5Rdzs", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_i5QVCDvXmBLbZg7n97n2", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-07T03:53:00.787Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-07T03:38:04.582Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": 8900, "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, "enable_partial_authorization": null } ``` </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
0eaea06a73d5209d8fa5688ec544af0883b787a2