repo
stringclasses
1 value
instance_id
stringlengths
24
24
problem_statement
stringlengths
24
8.41k
patch
stringlengths
0
367k
test_patch
stringclasses
1 value
created_at
stringdate
2023-04-18 16:43:29
2025-10-07 09:18:54
hints_text
stringlengths
57
132k
version
stringclasses
8 values
base_commit
stringlengths
40
40
environment_setup_commit
stringlengths
40
40
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 9378d7796f..2829d58b88 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 b1859cc6c2..b9053b46bc 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 8ffd54c288..59ef0b272d 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 1ec8514fc6..2d3fd64966 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 3809474acf..8cc026fb37 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 e483469be9..e530a5843c 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 f207c243d2..657655c25b 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 ec2d2d7a91..c6daab0211 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
v1.117.0
c172f03c31e9b29b69490c7c5dfb3b4c78206f79
c172f03c31e9b29b69490c7c5dfb3b4c78206f79
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 e9a917153f..e3d153f2aa 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
v1.117.0
cc4eaed5702dbcaa6c54a32714b52f479dfbe85b
cc4eaed5702dbcaa6c54a32714b52f479dfbe85b
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
v1.117.0
b3beda7d7172396452e34858cb6bd701962f75ab
b3beda7d7172396452e34858cb6bd701962f75ab
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
v1.117.0
c172f03c31e9b29b69490c7c5dfb3b4c78206f79
c172f03c31e9b29b69490c7c5dfb3b4c78206f79
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/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 6ac0ad192b1..42443a3cf40 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -26605,6 +26605,7 @@ "cybersource", "ebanx", "nomupay", + "nuvei", "payone", "paypal", "stripe", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 523732de9e5..3c04e9af7e7 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -20717,6 +20717,7 @@ "cybersource", "ebanx", "nomupay", + "nuvei", "payone", "paypal", "stripe", 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
v1.117.0
efab34f0ef0bd032b049778f18f3cb688faa7fa7
efab34f0ef0bd032b049778f18f3cb688faa7fa7
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
v1.117.0
9312cfa3c85e350c12bd64306037a72753b532bd
9312cfa3c85e350c12bd64306037a72753b532bd
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
v1.117.0
2d580b3afbca861028e010853dc33c75818c9288
2d580b3afbca861028e010853dc33c75818c9288
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/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 49ce347b1b8..9851859547c 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -12091,6 +12091,7 @@ "jpmorgan", "juspaythreedsserver", "klarna", + "loonio", "mifinity", "mollie", "moneris", @@ -30297,6 +30298,7 @@ "itaubank", "jpmorgan", "klarna", + "loonio", "mifinity", "mollie", "moneris", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index e89f7abdf19..dbd2a11fa65 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8698,6 +8698,7 @@ "jpmorgan", "juspaythreedsserver", "klarna", + "loonio", "mifinity", "mollie", "moneris", @@ -23982,6 +23983,7 @@ "itaubank", "jpmorgan", "klarna", + "loonio", "mifinity", "mollie", "moneris", 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
v1.117.0
efab34f0ef0bd032b049778f18f3cb688faa7fa7
efab34f0ef0bd032b049778f18f3cb688faa7fa7
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
v1.117.0
efab34f0ef0bd032b049778f18f3cb688faa7fa7
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
v1.117.0
90c7cffcd5b555bb5f18e320f723fce265781e9e
90c7cffcd5b555bb5f18e320f723fce265781e9e
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/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 973b3391e2d..a5ac51d096a 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -11058,6 +11058,11 @@ "type": "string", "description": "The error message" }, + "reason": { + "type": "string", + "description": "The detailed error reason that was returned by the connector.", + "nullable": true + }, "unified_code": { "type": "string", "description": "The unified error code across all connectors.\nThis can be relied upon for taking decisions based on the error.", 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
v1.117.0
9cd8f001f7360d9b8877fe94b9c185fc237e525c
9cd8f001f7360d9b8877fe94b9c185fc237e525c
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
v1.117.0
9cd8f001f7360d9b8877fe94b9c185fc237e525c
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
v1.117.0
9cd8f001f7360d9b8877fe94b9c185fc237e525c
9cd8f001f7360d9b8877fe94b9c185fc237e525c
juspay/hyperswitch
juspay__hyperswitch-9567
Bug: [FEATURE]: [GIGADAT] Implement Interac payouts Implement Interac payouts
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index eb14c882721..8b385870775 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -10939,6 +10939,16 @@ "type": "string", "description": "The device model of the client", "nullable": true + }, + "accept_language": { + "type": "string", + "description": "Accept-language of the browser", + "nullable": true + }, + "referer": { + "type": "string", + "description": "Identifier of the source that initiated the request.", + "nullable": true } } }, @@ -26637,6 +26647,14 @@ "type": "string", "description": "Identifier for payout method", "nullable": true + }, + "browser_info": { + "allOf": [ + { + "$ref": "#/components/schemas/BrowserInformation" + } + ], + "nullable": true } } }, @@ -26647,6 +26665,7 @@ "adyenplatform", "cybersource", "ebanx", + "gigadat", "nomupay", "nuvei", "payone", @@ -27614,6 +27633,14 @@ "type": "string", "description": "Identifier for payout method", "nullable": true + }, + "browser_info": { + "allOf": [ + { + "$ref": "#/components/schemas/BrowserInformation" + } + ], + "nullable": true } } }, @@ -27838,6 +27865,14 @@ "type": "string", "description": "Identifier for payout method", "nullable": true + }, + "browser_info": { + "allOf": [ + { + "$ref": "#/components/schemas/BrowserInformation" + } + ], + "nullable": true } } }, diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 67350969a6c..b38b5139be3 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -20741,6 +20741,7 @@ "adyenplatform", "cybersource", "ebanx", + "gigadat", "nomupay", "nuvei", "payone", @@ -21041,6 +21042,14 @@ "type": "string", "description": "Identifier for payout method", "nullable": true + }, + "browser_info": { + "allOf": [ + { + "$ref": "#/components/schemas/BrowserInformation" + } + ], + "nullable": true } }, "additionalProperties": false 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
v1.117.0
2d580b3afbca861028e010853dc33c75818c9288
2d580b3afbca861028e010853dc33c75818c9288
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
v1.117.0
9cd8f001f7360d9b8877fe94b9c185fc237e525c
9cd8f001f7360d9b8877fe94b9c185fc237e525c
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/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 49ce347b1b8..724c58027a4 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -16152,6 +16152,15 @@ } } }, + "GooglePayCardFundingSource": { + "type": "string", + "enum": [ + "CREDIT", + "DEBIT", + "PREPAID", + "UNKNOWN" + ] + }, "GooglePayPaymentMethodInfo": { "type": "object", "required": [ @@ -16174,6 +16183,14 @@ } ], "nullable": true + }, + "card_funding_source": { + "allOf": [ + { + "$ref": "#/components/schemas/GooglePayCardFundingSource" + } + ], + "nullable": true } } }, diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index e89f7abdf19..a220f2d4c0b 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -12365,6 +12365,15 @@ } } }, + "GooglePayCardFundingSource": { + "type": "string", + "enum": [ + "CREDIT", + "DEBIT", + "PREPAID", + "UNKNOWN" + ] + }, "GooglePayPaymentMethodInfo": { "type": "object", "required": [ @@ -12387,6 +12396,14 @@ } ], "nullable": true + }, + "card_funding_source": { + "allOf": [ + { + "$ref": "#/components/schemas/GooglePayCardFundingSource" + } + ], + "nullable": true } } }, 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 -->
v1.117.0
efab34f0ef0bd032b049778f18f3cb688faa7fa7
efab34f0ef0bd032b049778f18f3cb688faa7fa7
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
v1.117.0
af159867ae3594e1b66f5b20d1e61132ec1d2bf4
af159867ae3594e1b66f5b20d1e61132ec1d2bf4
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
v1.117.0
1ff66a720b29a169870b2141e6ffd585b4d5b640
1ff66a720b29a169870b2141e6ffd585b4d5b640
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
v1.117.0
e45bad38d602634c1bf9019978545f28ba19db23
e45bad38d602634c1bf9019978545f28ba19db23
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
v1.117.0
b26e845198407f3672a7f80d8eea670419858e0e
b26e845198407f3672a7f80d8eea670419858e0e
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
v1.117.0
94beaf915d62d678fca715ec18bfc64f9166f794
94beaf915d62d678fca715ec18bfc64f9166f794
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
v1.117.0
93b97ef5202c592aded23d7819bcef8eb27a2977
93b97ef5202c592aded23d7819bcef8eb27a2977
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
v1.117.0
f02d18038c854466907ef7d296f97bc921c60a90
f02d18038c854466907ef7d296f97bc921c60a90
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
v1.117.0
1ff66a720b29a169870b2141e6ffd585b4d5b640
1ff66a720b29a169870b2141e6ffd585b4d5b640
juspay/hyperswitch
juspay__hyperswitch-9544
Bug: [FEATURE]: [GIGADAT] integrate interac bank redirect payment method
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 2a57fdbb45c..bd1d8887c40 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -12077,6 +12077,7 @@ "flexiti", "forte", "getnet", + "gigadat", "globalpay", "globepay", "gocardless", @@ -30267,6 +30268,7 @@ "flexiti", "forte", "getnet", + "gigadat", "globalpay", "globepay", "gocardless", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 91b3e956717..468c1c33521 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8679,6 +8679,7 @@ "flexiti", "forte", "getnet", + "gigadat", "globalpay", "globepay", "gocardless", @@ -23931,6 +23932,7 @@ "flexiti", "forte", "getnet", + "gigadat", "globalpay", "globepay", "gocardless", 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
v1.117.0
9dbfeda43de895d66729e6d88401e400f4f8ebed
9dbfeda43de895d66729e6d88401e400f4f8ebed
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
v1.117.0
f02d18038c854466907ef7d296f97bc921c60a90
f02d18038c854466907ef7d296f97bc921c60a90
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
v1.117.0
9dbfeda43de895d66729e6d88401e400f4f8ebed
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
v1.117.0
bf048e4d830ee5088a7451e0da57a45e9a444394
bf048e4d830ee5088a7451e0da57a45e9a444394
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
v1.117.0
ceacec909bdeb4287571eb00622e60f7c21f30e4
ceacec909bdeb4287571eb00622e60f7c21f30e4
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/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 91b3e956717..3ca393170c9 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -23793,11 +23793,13 @@ "schedule_time_for_payment": { "type": "string", "format": "date-time", + "example": "2022-09-10T10:11:12Z", "nullable": true }, "schedule_time_for_psync": { "type": "string", "format": "date-time", + "example": "2022-09-10T10:11:12Z", "nullable": true }, "status": { 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
v1.117.0
9dbfeda43de895d66729e6d88401e400f4f8ebed
9dbfeda43de895d66729e6d88401e400f4f8ebed
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/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 49ce347b1b8..405ab5b8c11 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -23116,6 +23116,12 @@ "description": "Allow partial authorization for this payment", "default": false, "nullable": true + }, + "is_stored_credential": { + "type": "boolean", + "description": "Boolean flag indicating whether this payment method is stored and has been previously used for payments", + "example": true, + "nullable": true } } }, @@ -23596,6 +23602,12 @@ "description": "Boolean indicating whether to enable overcapture for this payment", "example": true, "nullable": true + }, + "is_stored_credential": { + "type": "boolean", + "description": "Boolean flag indicating whether this payment method is stored and has been previously used for payments", + "example": true, + "nullable": true } } }, @@ -24227,6 +24239,12 @@ } ], "nullable": true + }, + "is_stored_credential": { + "type": "boolean", + "description": "Boolean flag indicating whether this payment method is stored and has been previously used for payments", + "example": true, + "nullable": true } } }, @@ -25002,6 +25020,12 @@ "description": "Boolean indicating whether to enable overcapture for this payment", "example": true, "nullable": true + }, + "is_stored_credential": { + "type": "boolean", + "description": "Boolean flag indicating whether this payment method is stored and has been previously used for payments", + "example": true, + "nullable": true } }, "additionalProperties": false @@ -25659,6 +25683,12 @@ } ], "nullable": true + }, + "is_stored_credential": { + "type": "boolean", + "description": "Boolean flag indicating whether this payment method is stored and has been previously used for payments", + "example": true, + "nullable": true } } }, @@ -26272,6 +26302,12 @@ "description": "Boolean indicating whether to enable overcapture for this payment", "example": true, "nullable": true + }, + "is_stored_credential": { + "type": "boolean", + "description": "Boolean flag indicating whether this payment method is stored and has been previously used for payments", + "example": true, + "nullable": true } } }, 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" } } ```
v1.117.0
5427b07afb1300d9a0ca2f7a7c05e533bd3eb515
5427b07afb1300d9a0ca2f7a7c05e533bd3eb515
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
v1.117.0
ab00b083e963a5d5228af6b061b603a68d7efa17
ab00b083e963a5d5228af6b061b603a68d7efa17
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
v1.117.0
ab00b083e963a5d5228af6b061b603a68d7efa17
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
v1.117.0
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
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
v1.117.0
ab00b083e963a5d5228af6b061b603a68d7efa17
ab00b083e963a5d5228af6b061b603a68d7efa17
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/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 6bdb7e6fed2..0599e170d58 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -7522,6 +7522,11 @@ "type": "string", "description": "Accept-language of the browser", "nullable": true + }, + "referer": { + "type": "string", + "description": "Identifier of the source that initiated the request.", + "nullable": true } } }, 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
v1.117.0
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
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
v1.117.0
85da1b2bc80d4befd392cf7a9d2060d1e2f5cbe9
85da1b2bc80d4befd392cf7a9d2060d1e2f5cbe9
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/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 64a8751993d..5b03c951307 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -12131,6 +12131,7 @@ "stripebilling", "taxjar", "threedsecureio", + "tokenex", "tokenio", "trustpay", "trustpayments", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 8c768053eb1..32fc9db02c0 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8733,6 +8733,7 @@ "stripebilling", "taxjar", "threedsecureio", + "tokenex", "tokenio", "trustpay", "trustpayments", 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
v1.117.0
3bd78ac5c1ff120d6afd46e02df498a16ece6f5f
3bd78ac5c1ff120d6afd46e02df498a16ece6f5f
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/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 55640e81910..026119f2989 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -15238,6 +15238,31 @@ } } }, + "ExternalVaultConnectorDetails": { + "type": "object", + "properties": { + "vault_connector_id": { + "type": "string", + "description": "Merchant Connector id to be stored for vault connector", + "nullable": true + }, + "vault_sdk": { + "allOf": [ + { + "$ref": "#/components/schemas/VaultSdk" + } + ], + "nullable": true + } + } + }, + "ExternalVaultEnabled": { + "type": "string", + "enum": [ + "enable", + "skip" + ] + }, "FeatureMatrixListResponse": { "type": "object", "required": [ @@ -28616,6 +28641,22 @@ "type": "boolean", "description": "Bool indicating if overcapture must be requested for all payments", "nullable": true + }, + "is_external_vault_enabled": { + "allOf": [ + { + "$ref": "#/components/schemas/ExternalVaultEnabled" + } + ], + "nullable": true + }, + "external_vault_connector_details": { + "allOf": [ + { + "$ref": "#/components/schemas/ExternalVaultConnectorDetails" + } + ], + "nullable": true } }, "additionalProperties": false @@ -28952,6 +28993,22 @@ "type": "boolean", "description": "Bool indicating if overcapture must be requested for all payments", "nullable": true + }, + "is_external_vault_enabled": { + "allOf": [ + { + "$ref": "#/components/schemas/ExternalVaultEnabled" + } + ], + "nullable": true + }, + "external_vault_connector_details": { + "allOf": [ + { + "$ref": "#/components/schemas/ExternalVaultConnectorDetails" + } + ], + "nullable": true } } }, @@ -32699,6 +32756,13 @@ "propertyName": "type" } }, + "VaultSdk": { + "type": "string", + "enum": [ + "vgs_sdk", + "hyperswitch_sdk" + ] + }, "Venmo": { "type": "object", "required": [ 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
v1.117.0
0b263179af1b9dc3186c09c53b700b6a1f754d0e
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
v1.117.0
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
juspay/hyperswitch
juspay__hyperswitch-9477
Bug: [FEATURE]: add client_auth auth type for list_blocked_payment_methods
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 55640e81910..64a8751993d 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -17178,6 +17178,10 @@ "type": "integer", "format": "int32", "minimum": 0 + }, + "client_secret": { + "type": "string", + "nullable": true } } }, diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 6bdb7e6fed2..8f5568fadcf 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -13421,6 +13421,10 @@ "type": "integer", "format": "int32", "minimum": 0 + }, + "client_secret": { + "type": "string", + "nullable": true } } }, 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
v1.117.0
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
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 } } ```
v1.117.0
740f3af64304469f9a6d781de349cf762a311c6f
740f3af64304469f9a6d781de349cf762a311c6f
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/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 6bdb7e6fed2..bd1485b76dc 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -19033,6 +19033,14 @@ "payment_method_data": { "$ref": "#/components/schemas/PaymentMethodDataRequest" }, + "split_payment_method_data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SplitPaymentMethodDataRequest" + }, + "description": "The payment instrument data to be used for the payment in case of split payments", + "nullable": true + }, "payment_method_type": { "$ref": "#/components/schemas/PaymentMethod" }, @@ -24966,6 +24974,25 @@ "created" ] }, + "SplitPaymentMethodDataRequest": { + "type": "object", + "required": [ + "payment_method_data", + "payment_method_type", + "payment_method_subtype" + ], + "properties": { + "payment_method_data": { + "$ref": "#/components/schemas/PaymentMethodData" + }, + "payment_method_type": { + "$ref": "#/components/schemas/PaymentMethod" + }, + "payment_method_subtype": { + "$ref": "#/components/schemas/PaymentMethodType" + } + } + }, "SplitPaymentsRequest": { "oneOf": [ { 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
v1.117.0
2553780051e3a2fe54fcb99384e4bd8021d52048
2553780051e3a2fe54fcb99384e4bd8021d52048
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
v1.117.0
0513c2cd719f59a23843104146e2f5f6863378a1
0513c2cd719f59a23843104146e2f5f6863378a1
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
v1.117.0
0b263179af1b9dc3186c09c53b700b6a1f754d0e
0b263179af1b9dc3186c09c53b700b6a1f754d0e
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
v1.117.0
2553780051e3a2fe54fcb99384e4bd8021d52048
2553780051e3a2fe54fcb99384e4bd8021d52048
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" />
v1.117.0
e2f1a456a17645b9ccac771d3608794c4956277d
e2f1a456a17645b9ccac771d3608794c4956277d
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
v1.117.0
90c7cffcd5b555bb5f18e320f723fce265781e9e
90c7cffcd5b555bb5f18e320f723fce265781e9e
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
v1.117.0
ab00b083e963a5d5228af6b061b603a68d7efa17
ab00b083e963a5d5228af6b061b603a68d7efa17
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
v1.117.0
e29a121bfd10f00486dfa33e9d8cbd18ecc625eb
e29a121bfd10f00486dfa33e9d8cbd18ecc625eb
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
v1.117.0
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
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
v1.117.0
8930e1ed289bb4c128da664849af1095bafd45a7
8930e1ed289bb4c128da664849af1095bafd45a7
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
v1.117.0
1c0fc496d1f639de4b7a94b971ce4526a3452c01
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
v1.117.0
1c0fc496d1f639de4b7a94b971ce4526a3452c01
1c0fc496d1f639de4b7a94b971ce4526a3452c01
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
v1.117.0
213165968462168a59d5c56423a7c10aa04fc186
213165968462168a59d5c56423a7c10aa04fc186
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
v1.117.0
15406557c11041bab6358f2b4b916d7333fc0a0f
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
v1.117.0
a05827e0ed8c25463a56cd973f475fbe8fbef145
a05827e0ed8c25463a56cd973f475fbe8fbef145
juspay/hyperswitch
juspay__hyperswitch-9430
Bug: Add support to configure default billing processor for a profile
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index ee3ac6ea3ac..e3db673db67 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -28661,6 +28661,11 @@ } ], "nullable": true + }, + "billing_processor_id": { + "type": "string", + "description": "Merchant Connector id to be stored for billing_processor connector", + "nullable": true } }, "additionalProperties": false @@ -29013,6 +29018,11 @@ } ], "nullable": true + }, + "billing_processor_id": { + "type": "string", + "description": "Merchant Connector id to be stored for billing_processor connector", + "nullable": true } } }, diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 8c768053eb1..45110efc24f 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -22274,6 +22274,11 @@ ], "default": "skip", "nullable": true + }, + "billing_processor_id": { + "type": "string", + "description": "Merchant Connector id to be stored for billing_processor connector", + "nullable": true } }, "additionalProperties": false @@ -22576,6 +22581,11 @@ } ], "nullable": true + }, + "billing_processor_id": { + "type": "string", + "description": "Merchant Connector id to be stored for billing_processor connector", + "nullable": true } } }, 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
v1.117.0
e410af26ffffc63273f9a83ae28c982f37f47484
e410af26ffffc63273f9a83ae28c982f37f47484
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
v1.117.0
5b6409d4ebdcd7b1820d72b2cc7850ded21a1ad5
5b6409d4ebdcd7b1820d72b2cc7850ded21a1ad5
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
v1.117.0
15406557c11041bab6358f2b4b916d7333fc0a0f
15406557c11041bab6358f2b4b916d7333fc0a0f
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
v1.117.0
f3ab3d63f69279af9254f15eba5654c0680a0747
f3ab3d63f69279af9254f15eba5654c0680a0747
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
v1.117.0
8ed3f7dbf27e939a72957fb5751abbf61bd642c0
8ed3f7dbf27e939a72957fb5751abbf61bd642c0
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
v1.117.0
ee12d44c5f13d0612dde3b6b24a412f6ddd870c8
ee12d44c5f13d0612dde3b6b24a412f6ddd870c8
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
v1.117.0
655b374feca2d53cdd4598eae2c8646aa3c092e1
655b374feca2d53cdd4598eae2c8646aa3c092e1
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
v1.117.0
b69ed06959c9d9d2bb139465aa75e5d2a66b5a16
b69ed06959c9d9d2bb139465aa75e5d2a66b5a16
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
v1.117.0
4ce1c8c284d8cfa41671ca70c0aecdf145584906
4ce1c8c284d8cfa41671ca70c0aecdf145584906
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
v1.117.0
ee12d44c5f13d0612dde3b6b24a412f6ddd870c8
ee12d44c5f13d0612dde3b6b24a412f6ddd870c8
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
v1.117.0
0e30fb6b5562bd641df6f0229d09e4311df8900e
0e30fb6b5562bd641df6f0229d09e4311df8900e
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/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index e60d1eab85f..34cd0c51473 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -12111,6 +12111,7 @@ "paystack", "paytm", "payu", + "peachpayments", "phonepe", "placetopay", "powertranz", @@ -30218,6 +30219,7 @@ "paystack", "paytm", "payu", + "peachpayments", "phonepe", "placetopay", "powertranz", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 100dc665e91..64841a574c9 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8655,6 +8655,7 @@ "paystack", "paytm", "payu", + "peachpayments", "phonepe", "placetopay", "powertranz", @@ -23835,6 +23836,7 @@ "paystack", "paytm", "payu", + "peachpayments", "phonepe", "placetopay", "powertranz", 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
v1.116.0
0873d93084d2a126cdfb3ebb60e92b0cec79d2ba
0873d93084d2a126cdfb3ebb60e92b0cec79d2ba
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
v1.116.0
cadfcf7c22bfd1124f19e2f1cc1c98c3d152be99
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
v1.117.0
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
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
v1.116.0
5ab8a27c10786885b91b79fbb9fb8b5e990029e1
5ab8a27c10786885b91b79fbb9fb8b5e990029e1
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
v1.117.0
32dd9e10e3103a906cfef49c7baa117778ea02f3
32dd9e10e3103a906cfef49c7baa117778ea02f3
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
v1.117.0
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
40357ae298ac8327b08f6b5c7b1d4f8cfe7c9acb
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
v1.117.0
c611b8145596e61d0f1aad8ec9a0f7f2f83b4ae6
c611b8145596e61d0f1aad8ec9a0f7f2f83b4ae6
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
v1.117.0
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
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
v1.117.0
7355a83ef9316a6cc7f9fa0c9c9aec7397e9fc4b
7355a83ef9316a6cc7f9fa0c9c9aec7397e9fc4b
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
v1.117.0
f3ab3d63f69279af9254f15eba5654c0680a0747
f3ab3d63f69279af9254f15eba5654c0680a0747
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
v1.117.0
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
juspay/hyperswitch
juspay__hyperswitch-9322
Bug: Rename existing RevenueRecoveryRecordBack trait to InvoiceRecordBack After a payment is successful for a invoice, we need to record the invoice as paid with the subscription provider. this implementation is already done for revenue recovery usecase. making it generic so that subscription also can use it
diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index 19ec99fc1d0..5e2e23a8a90 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -13,28 +13,28 @@ use common_utils::{ use error_stack::report; use error_stack::ResultExt; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use hyperswitch_domain_models::{ - revenue_recovery, router_flow_types::revenue_recovery::RecoveryRecordBack, - router_request_types::revenue_recovery::RevenueRecoveryRecordBackRequest, - router_response_types::revenue_recovery::RevenueRecoveryRecordBackResponse, - types::RevenueRecoveryRecordBackRouterData, -}; +use hyperswitch_domain_models::revenue_recovery; 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::InvoiceRecordBack, }, router_request_types::{ - AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + revenue_recovery::InvoiceRecordBackRequest, AccessTokenRequestData, + PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, + SetupMandateRequestData, + }, + router_response_types::{ + revenue_recovery::InvoiceRecordBackResponse, ConnectorInfo, PaymentsResponseData, + RefundsResponseData, }, - router_response_types::{ConnectorInfo, PaymentsResponseData, RefundsResponseData}, types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -560,24 +560,19 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Chargebee } } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -impl - ConnectorIntegration< - RecoveryRecordBack, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, - > for Chargebee +impl ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> + for Chargebee { fn get_headers( &self, - req: &RevenueRecoveryRecordBackRouterData, + req: &InvoiceRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - req: &RevenueRecoveryRecordBackRouterData, + req: &InvoiceRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let metadata: chargebee::ChargebeeMetadata = @@ -600,7 +595,7 @@ impl fn get_request_body( &self, - req: &RevenueRecoveryRecordBackRouterData, + req: &InvoiceRecordBackRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( @@ -616,20 +611,20 @@ impl fn build_request( &self, - req: &RevenueRecoveryRecordBackRouterData, + req: &InvoiceRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) - .url(&types::RevenueRecoveryRecordBackType::get_url( + .url(&types::InvoiceRecordBackType::get_url( self, req, connectors, )?) .attach_default_headers() - .headers(types::RevenueRecoveryRecordBackType::get_headers( + .headers(types::InvoiceRecordBackType::get_headers( self, req, connectors, )?) - .set_body(types::RevenueRecoveryRecordBackType::get_request_body( + .set_body(types::InvoiceRecordBackType::get_request_body( self, req, connectors, )?) .build(), @@ -638,10 +633,10 @@ impl fn handle_response( &self, - data: &RevenueRecoveryRecordBackRouterData, + data: &InvoiceRecordBackRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<RevenueRecoveryRecordBackRouterData, errors::ConnectorError> { + ) -> CustomResult<InvoiceRecordBackRouterData, errors::ConnectorError> { let response: chargebee::ChargebeeRecordbackResponse = res .response .parse_struct("chargebee ChargebeeRecordbackResponse") diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 95f105c67b9..6d942980e2f 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -11,14 +11,13 @@ use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::{ refunds::{Execute, RSync}, - RecoveryRecordBack, + InvoiceRecordBack, }, - router_request_types::{revenue_recovery::RevenueRecoveryRecordBackRequest, ResponseId}, + router_request_types::{revenue_recovery::InvoiceRecordBackRequest, ResponseId}, router_response_types::{ - revenue_recovery::RevenueRecoveryRecordBackResponse, PaymentsResponseData, - RefundsResponseData, + revenue_recovery::InvoiceRecordBackResponse, PaymentsResponseData, RefundsResponseData, }, - types::{PaymentsAuthorizeRouterData, RefundsRouterData, RevenueRecoveryRecordBackRouterData}, + types::{InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; @@ -673,13 +672,10 @@ pub enum ChargebeeRecordStatus { Failure, } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -impl TryFrom<&ChargebeeRouterData<&RevenueRecoveryRecordBackRouterData>> - for ChargebeeRecordPaymentRequest -{ +impl TryFrom<&ChargebeeRouterData<&InvoiceRecordBackRouterData>> for ChargebeeRecordPaymentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: &ChargebeeRouterData<&RevenueRecoveryRecordBackRouterData>, + item: &ChargebeeRouterData<&InvoiceRecordBackRouterData>, ) -> Result<Self, Self::Error> { let req = &item.router_data.request; Ok(Self { @@ -694,7 +690,6 @@ impl TryFrom<&ChargebeeRouterData<&RevenueRecoveryRecordBackRouterData>> } } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom<enums::AttemptStatus> for ChargebeeRecordStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(status: enums::AttemptStatus) -> Result<Self, Self::Error> { @@ -748,25 +743,25 @@ pub struct ChargebeeRecordbackInvoice { impl TryFrom< ResponseRouterData< - RecoveryRecordBack, + InvoiceRecordBack, ChargebeeRecordbackResponse, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, >, - > for RevenueRecoveryRecordBackRouterData + > for InvoiceRecordBackRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< - RecoveryRecordBack, + InvoiceRecordBack, ChargebeeRecordbackResponse, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, >, ) -> Result<Self, Self::Error> { let merchant_reference_id = item.response.invoice.id; Ok(Self { - response: Ok(RevenueRecoveryRecordBackResponse { + response: Ok(InvoiceRecordBackResponse { merchant_reference_id, }), ..item.data diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index 35b736b844e..693095cfeb9 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -300,15 +300,15 @@ impl #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl ConnectorIntegrationV2< - recovery_router_flows::RecoveryRecordBack, - recovery_flow_common_types::RevenueRecoveryRecordBackData, - recovery_request_types::RevenueRecoveryRecordBackRequest, - recovery_response_types::RevenueRecoveryRecordBackResponse, + recovery_router_flows::InvoiceRecordBack, + recovery_flow_common_types::InvoiceRecordBackData, + recovery_request_types::InvoiceRecordBackRequest, + recovery_response_types::InvoiceRecordBackResponse, > for Recurly { fn get_headers( &self, - req: &recovery_router_data_types::RevenueRecoveryRecordBackRouterDataV2, + req: &recovery_router_data_types::InvoiceRecordBackRouterDataV2, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), @@ -321,7 +321,7 @@ impl fn get_url( &self, - req: &recovery_router_data_types::RevenueRecoveryRecordBackRouterDataV2, + req: &recovery_router_data_types::InvoiceRecordBackRouterDataV2, ) -> CustomResult<String, errors::ConnectorError> { let invoice_id = req .request @@ -344,16 +344,14 @@ impl fn build_request_v2( &self, - req: &recovery_router_data_types::RevenueRecoveryRecordBackRouterDataV2, + req: &recovery_router_data_types::InvoiceRecordBackRouterDataV2, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Put) - .url(&types::RevenueRecoveryRecordBackTypeV2::get_url(self, req)?) + .url(&types::InvoiceRecordBackTypeV2::get_url(self, req)?) .attach_default_headers() - .headers(types::RevenueRecoveryRecordBackTypeV2::get_headers( - self, req, - )?) + .headers(types::InvoiceRecordBackTypeV2::get_headers(self, req)?) .header("Content-Length", "0") .build(), )) @@ -361,11 +359,11 @@ impl fn handle_response_v2( &self, - data: &recovery_router_data_types::RevenueRecoveryRecordBackRouterDataV2, + data: &recovery_router_data_types::InvoiceRecordBackRouterDataV2, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< - recovery_router_data_types::RevenueRecoveryRecordBackRouterDataV2, + recovery_router_data_types::InvoiceRecordBackRouterDataV2, errors::ConnectorError, > { let response: recurly::RecurlyRecordBackResponse = res @@ -374,13 +372,11 @@ impl .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - recovery_router_data_types::RevenueRecoveryRecordBackRouterDataV2::try_from( - ResponseRouterDataV2 { - response, - data: data.clone(), - http_code: res.status_code, - }, - ) + recovery_router_data_types::InvoiceRecordBackRouterDataV2::try_from(ResponseRouterDataV2 { + response, + data: data.clone(), + http_code: res.status_code, + }) } fn get_error_response_v2( diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs index 7338500db80..b17a01952ab 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs @@ -316,27 +316,27 @@ pub struct RecurlyRecordBackResponse { impl TryFrom< ResponseRouterDataV2< - recovery_router_flows::RecoveryRecordBack, + recovery_router_flows::InvoiceRecordBack, RecurlyRecordBackResponse, - recovery_flow_common_types::RevenueRecoveryRecordBackData, - recovery_request_types::RevenueRecoveryRecordBackRequest, - recovery_response_types::RevenueRecoveryRecordBackResponse, + recovery_flow_common_types::InvoiceRecordBackData, + recovery_request_types::InvoiceRecordBackRequest, + recovery_response_types::InvoiceRecordBackResponse, >, - > for recovery_router_data_types::RevenueRecoveryRecordBackRouterDataV2 + > for recovery_router_data_types::InvoiceRecordBackRouterDataV2 { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterDataV2< - recovery_router_flows::RecoveryRecordBack, + recovery_router_flows::InvoiceRecordBack, RecurlyRecordBackResponse, - recovery_flow_common_types::RevenueRecoveryRecordBackData, - recovery_request_types::RevenueRecoveryRecordBackRequest, - recovery_response_types::RevenueRecoveryRecordBackResponse, + recovery_flow_common_types::InvoiceRecordBackData, + recovery_request_types::InvoiceRecordBackRequest, + recovery_response_types::InvoiceRecordBackResponse, >, ) -> Result<Self, Self::Error> { let merchant_reference_id = item.response.id; Ok(Self { - response: Ok(recovery_response_types::RevenueRecoveryRecordBackResponse { + response: Ok(recovery_response_types::InvoiceRecordBackResponse { merchant_reference_id, }), ..item.data diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs index 79f0bcc88d8..99d83e4ef82 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -663,14 +663,14 @@ impl #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl ConnectorIntegration< - recovery_router_flows::RecoveryRecordBack, - recovery_request_types::RevenueRecoveryRecordBackRequest, - recovery_response_types::RevenueRecoveryRecordBackResponse, + recovery_router_flows::InvoiceRecordBack, + recovery_request_types::InvoiceRecordBackRequest, + recovery_response_types::InvoiceRecordBackResponse, > for Stripebilling { fn get_headers( &self, - req: &recovery_router_data_types::RevenueRecoveryRecordBackRouterData, + req: &recovery_router_data_types::InvoiceRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) @@ -682,7 +682,7 @@ impl fn get_url( &self, - req: &recovery_router_data_types::RevenueRecoveryRecordBackRouterData, + req: &recovery_router_data_types::InvoiceRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let invoice_id = req @@ -705,17 +705,17 @@ impl fn build_request( &self, - req: &recovery_router_data_types::RevenueRecoveryRecordBackRouterData, + req: &recovery_router_data_types::InvoiceRecordBackRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) - .url(&types::RevenueRecoveryRecordBackType::get_url( + .url(&types::InvoiceRecordBackType::get_url( self, req, connectors, )?) .attach_default_headers() - .headers(types::RevenueRecoveryRecordBackType::get_headers( + .headers(types::InvoiceRecordBackType::get_headers( self, req, connectors, )?) .build(), @@ -724,13 +724,11 @@ impl fn handle_response( &self, - data: &recovery_router_data_types::RevenueRecoveryRecordBackRouterData, + data: &recovery_router_data_types::InvoiceRecordBackRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult< - recovery_router_data_types::RevenueRecoveryRecordBackRouterData, - errors::ConnectorError, - > { + ) -> CustomResult<recovery_router_data_types::InvoiceRecordBackRouterData, errors::ConnectorError> + { let response = res .response .parse_struct::<stripebilling::StripebillingRecordBackResponse>( @@ -739,13 +737,11 @@ impl .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - recovery_router_data_types::RevenueRecoveryRecordBackRouterData::try_from( - ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }, - ) + recovery_router_data_types::InvoiceRecordBackRouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) } fn get_error_response( diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs index a5e4610ffdb..a44a4d31a95 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs @@ -627,24 +627,24 @@ pub struct StripebillingRecordBackResponse { impl TryFrom< ResponseRouterData< - recovery_router_flows::RecoveryRecordBack, + recovery_router_flows::InvoiceRecordBack, StripebillingRecordBackResponse, - recovery_request_types::RevenueRecoveryRecordBackRequest, - recovery_response_types::RevenueRecoveryRecordBackResponse, + recovery_request_types::InvoiceRecordBackRequest, + recovery_response_types::InvoiceRecordBackResponse, >, - > for recovery_router_data_types::RevenueRecoveryRecordBackRouterData + > for recovery_router_data_types::InvoiceRecordBackRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< - recovery_router_flows::RecoveryRecordBack, + recovery_router_flows::InvoiceRecordBack, StripebillingRecordBackResponse, - recovery_request_types::RevenueRecoveryRecordBackRequest, - recovery_response_types::RevenueRecoveryRecordBackResponse, + recovery_request_types::InvoiceRecordBackRequest, + recovery_response_types::InvoiceRecordBackResponse, >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(recovery_response_types::RevenueRecoveryRecordBackResponse { + response: Ok(recovery_response_types::InvoiceRecordBackResponse { merchant_reference_id: id_type::PaymentReferenceId::from_str( item.response.id.as_str(), ) diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 0535088c884..2d366f3f99e 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, RecoveryRecordBack, + BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }; #[cfg(feature = "dummy_connector")] use hyperswitch_domain_models::router_request_types::authentication::{ @@ -17,12 +17,12 @@ 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, - RevenueRecoveryRecordBackRequest, + InvoiceRecordBackRequest, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackResponse, }; use hyperswitch_domain_models::{ router_data::AccessTokenAuthenticationResponse, @@ -6611,9 +6611,9 @@ macro_rules! default_imp_for_revenue_recovery_record_back { $( impl recovery_traits::RevenueRecoveryRecordBack for $path::$connector {} impl ConnectorIntegration< - RecoveryRecordBack, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse + InvoiceRecordBack, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse > for $path::$connector {} )* @@ -8358,11 +8358,8 @@ impl<const T: u8> api::revenue_recovery::RevenueRecoveryRecordBack #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> - ConnectorIntegration< - RecoveryRecordBack, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, - > for connectors::DummyConnector<T> + ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> + for connectors::DummyConnector<T> { } diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 5dc07ab43d4..f175c52e93f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -3,8 +3,8 @@ use hyperswitch_domain_models::{ router_data_v2::{ flow_common_types::{ BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, - DisputesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, - RevenueRecoveryRecordBackData, WebhookSourceVerifyData, + DisputesFlowData, InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, + RefundFlowData, WebhookSourceVerifyData, }, AccessTokenFlowData, AuthenticationTokenFlowData, ExternalAuthenticationFlowData, FilesFlowData, VaultConnectorFlowData, @@ -24,7 +24,7 @@ use hyperswitch_domain_models::{ }, refunds::{Execute, RSync}, revenue_recovery::{ - BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack, + BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }, webhooks::VerifyWebhookSource, AccessTokenAuth, AccessTokenAuthentication, ExternalVaultCreateFlow, @@ -34,7 +34,7 @@ use hyperswitch_domain_models::{ authentication, revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, - RevenueRecoveryRecordBackRequest, + InvoiceRecordBackRequest, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, @@ -52,7 +52,7 @@ use hyperswitch_domain_models::{ router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackResponse, }, AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, MandateRevokeResponseData, @@ -4120,10 +4120,10 @@ macro_rules! default_imp_for_new_connector_integration_revenue_recovery { impl BillingConnectorInvoiceSyncIntegrationV2 for $path::$connector {} impl ConnectorIntegrationV2< - RecoveryRecordBack, - RevenueRecoveryRecordBackData, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBack, + InvoiceRecordBackData, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, > for $path::$connector {} impl 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 686912c6dca..1b5c48df929 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,7 @@ pub struct FilesFlowData { } #[derive(Debug, Clone)] -pub struct RevenueRecoveryRecordBackData; +pub struct InvoiceRecordBackData; #[derive(Debug, Clone)] pub struct UasFlowData { diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs index ec784f7d464..da496656c65 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs @@ -1,7 +1,7 @@ #[derive(Debug, Clone)] pub struct BillingConnectorPaymentsSync; #[derive(Debug, Clone)] -pub struct RecoveryRecordBack; +pub struct InvoiceRecordBack; #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSync; diff --git a/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs index 9e1a59110f9..197de0b0fb5 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs @@ -11,7 +11,7 @@ pub struct BillingConnectorPaymentsSyncRequest { } #[derive(Debug, Clone)] -pub struct RevenueRecoveryRecordBackRequest { +pub struct InvoiceRecordBackRequest { pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, pub amount: common_utils::types::MinorUnit, pub currency: enums::Currency, diff --git a/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs index 65a62f62125..dabdf981e3d 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs @@ -35,7 +35,7 @@ pub struct BillingConnectorPaymentsSyncResponse { } #[derive(Debug, Clone)] -pub struct RevenueRecoveryRecordBackResponse { +pub struct InvoiceRecordBackResponse { pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, } diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index bcca0ba12a9..e907bbdfa20 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -4,7 +4,7 @@ use crate::{ router_data::{AccessToken, AccessTokenAuthenticationResponse, RouterData}, router_data_v2::{self, RouterDataV2}, router_flow_types::{ - mandate_revoke::MandateRevoke, revenue_recovery::RecoveryRecordBack, AccessTokenAuth, + mandate_revoke::MandateRevoke, revenue_recovery::InvoiceRecordBack, AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute, @@ -15,7 +15,7 @@ use crate::{ router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, - RevenueRecoveryRecordBackRequest, + InvoiceRecordBackRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, @@ -35,7 +35,7 @@ use crate::{ router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackResponse, }, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, VaultResponseData, VerifyWebhookSourceResponseData, @@ -114,11 +114,8 @@ pub type VerifyWebhookSourceRouterData = RouterData< #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; -pub type RevenueRecoveryRecordBackRouterData = RouterData< - RecoveryRecordBack, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, ->; +pub type InvoiceRecordBackRouterData = + RouterData<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>; pub type UasAuthenticationRouterData = RouterData<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>; @@ -149,11 +146,11 @@ pub type BillingConnectorPaymentsSyncRouterDataV2 = RouterDataV2< BillingConnectorPaymentsSyncResponse, >; -pub type RevenueRecoveryRecordBackRouterDataV2 = RouterDataV2< - RecoveryRecordBack, - router_data_v2::flow_common_types::RevenueRecoveryRecordBackData, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, +pub type InvoiceRecordBackRouterDataV2 = RouterDataV2< + InvoiceRecordBack, + router_data_v2::flow_common_types::InvoiceRecordBackData, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, >; pub type VaultRouterData<F> = RouterData<F, VaultRequestData, VaultResponseData>; diff --git a/crates/hyperswitch_interfaces/src/api/revenue_recovery.rs b/crates/hyperswitch_interfaces/src/api/revenue_recovery.rs index 053d3cdde35..998c1888e64 100644 --- a/crates/hyperswitch_interfaces/src/api/revenue_recovery.rs +++ b/crates/hyperswitch_interfaces/src/api/revenue_recovery.rs @@ -2,15 +2,15 @@ use hyperswitch_domain_models::{ router_flow_types::{ - BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack, + BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }, router_request_types::revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, - RevenueRecoveryRecordBackRequest, + InvoiceRecordBackRequest, }, router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackResponse, }, }; @@ -40,11 +40,7 @@ pub trait BillingConnectorPaymentsSyncIntegration: /// trait RevenueRecoveryRecordBack pub trait RevenueRecoveryRecordBack: - ConnectorIntegration< - RecoveryRecordBack, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, -> + ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> { } diff --git a/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs b/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs index 11a854c6dec..08efb664f9b 100644 --- a/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs @@ -3,18 +3,18 @@ use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, - RevenueRecoveryRecordBackData, + InvoiceRecordBackData, }, router_flow_types::{ - BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack, + BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }, router_request_types::revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, - RevenueRecoveryRecordBackRequest, + InvoiceRecordBackRequest, }, router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackResponse, }, }; @@ -47,10 +47,10 @@ pub trait BillingConnectorPaymentsSyncIntegrationV2: /// trait RevenueRecoveryRecordBackV2 pub trait RevenueRecoveryRecordBackV2: ConnectorIntegrationV2< - RecoveryRecordBack, - RevenueRecoveryRecordBackData, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBack, + InvoiceRecordBackData, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, > { } diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index 23fb9e76bcd..d0612172561 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -11,9 +11,9 @@ use hyperswitch_domain_models::{ flow_common_types::{ AccessTokenFlowData, AuthenticationTokenFlowData, BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData, ExternalAuthenticationFlowData, - ExternalVaultProxyFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, - RefundFlowData, RevenueRecoveryRecordBackData, UasFlowData, VaultConnectorFlowData, - WebhookSourceVerifyData, + ExternalVaultProxyFlowData, FilesFlowData, InvoiceRecordBackData, + MandateRevokeFlowData, PaymentFlowData, RefundFlowData, UasFlowData, + VaultConnectorFlowData, WebhookSourceVerifyData, }, RouterDataV2, }, @@ -759,9 +759,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> } } -impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> - for RevenueRecoveryRecordBackData -{ +impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for InvoiceRecordBackData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index eed89fe00ba..acb3dcfaa28 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -15,7 +15,7 @@ use hyperswitch_domain_models::{ SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, - revenue_recovery::{BillingConnectorPaymentsSync, RecoveryRecordBack}, + revenue_recovery::{BillingConnectorPaymentsSync, InvoiceRecordBack}, unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, @@ -29,7 +29,7 @@ use hyperswitch_domain_models::{ router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, - RevenueRecoveryRecordBackRequest, + InvoiceRecordBackRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, @@ -51,7 +51,7 @@ use hyperswitch_domain_models::{ router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackResponse, }, AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, @@ -264,11 +264,11 @@ pub type UasAuthenticationType = dyn ConnectorIntegration< UasAuthenticationResponseData, >; -/// Type alias for `ConnectorIntegration<RecoveryRecordBack, RevenueRecoveryRecordBackRequest, RevenueRecoveryRecordBackResponse>` -pub type RevenueRecoveryRecordBackType = dyn ConnectorIntegration< - RecoveryRecordBack, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, +/// Type alias for `ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>` +pub type InvoiceRecordBackType = dyn ConnectorIntegration< + InvoiceRecordBack, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, >; /// Type alias for `ConnectorIntegration<BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse>` @@ -285,12 +285,12 @@ pub type BillingConnectorInvoiceSyncType = dyn ConnectorIntegration< BillingConnectorInvoiceSyncResponse, >; -/// Type alias for `ConnectorIntegrationV2<RecoveryRecordBack, RevenueRecoveryRecordBackData, RevenueRecoveryRecordBackRequest, RevenueRecoveryRecordBackResponse>` -pub type RevenueRecoveryRecordBackTypeV2 = dyn ConnectorIntegrationV2< - RecoveryRecordBack, - flow_common_types::RevenueRecoveryRecordBackData, - RevenueRecoveryRecordBackRequest, - RevenueRecoveryRecordBackResponse, +/// Type alias for `ConnectorIntegrationV2<InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse>` +pub type InvoiceRecordBackTypeV2 = dyn ConnectorIntegrationV2< + InvoiceRecordBack, + flow_common_types::InvoiceRecordBackData, + InvoiceRecordBackRequest, + InvoiceRecordBackResponse, >; /// Type alias for `ConnectorIntegrationV2<BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse>` diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index d9e3e9ee34b..4f63e0005cc 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -19,7 +19,7 @@ use async_trait::async_trait; use common_types::payments::CustomerAcceptance; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_flow_types::{ - BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack, + BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }; use hyperswitch_domain_models::router_request_types::PaymentsCaptureData; diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index d2667cc63b0..f63259b0c85 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -1361,12 +1361,12 @@ async fn record_back_to_billing_connector( .attach_printable("invalid connector name received in billing merchant connector account")?; let connector_integration: services::BoxedRevenueRecoveryRecordBackInterface< - router_flow_types::RecoveryRecordBack, - revenue_recovery_request::RevenueRecoveryRecordBackRequest, - revenue_recovery_response::RevenueRecoveryRecordBackResponse, + router_flow_types::InvoiceRecordBack, + revenue_recovery_request::InvoiceRecordBackRequest, + revenue_recovery_response::InvoiceRecordBackResponse, > = connector_data.connector.get_connector_integration(); - let router_data = construct_recovery_record_back_router_data( + let router_data = construct_invoice_record_back_router_data( state, billing_mca, payment_attempt, @@ -1396,13 +1396,13 @@ async fn record_back_to_billing_connector( Ok(()) } -pub fn construct_recovery_record_back_router_data( +pub fn construct_invoice_record_back_router_data( state: &SessionState, billing_mca: &merchant_connector_account::MerchantConnectorAccount, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, -) -> RecoveryResult<hyperswitch_domain_models::types::RevenueRecoveryRecordBackRouterData> { - logger::info!("Entering construct_recovery_record_back_router_data"); +) -> RecoveryResult<hyperswitch_domain_models::types::InvoiceRecordBackRouterData> { + logger::info!("Entering construct_invoice_record_back_router_data"); let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(Box::new(billing_mca.clone())) @@ -1433,11 +1433,11 @@ pub fn construct_recovery_record_back_router_data( ))?; let router_data = router_data_v2::RouterDataV2 { - flow: PhantomData::<router_flow_types::RecoveryRecordBack>, + flow: PhantomData::<router_flow_types::InvoiceRecordBack>, tenant_id: state.tenant.tenant_id.clone(), - resource_common_data: flow_common_types::RevenueRecoveryRecordBackData, + resource_common_data: flow_common_types::InvoiceRecordBackData, connector_auth_type: auth_type, - request: revenue_recovery_request::RevenueRecoveryRecordBackRequest { + request: revenue_recovery_request::InvoiceRecordBackRequest { merchant_reference_id, amount: payment_attempt.get_total_amount(), currency: payment_intent.amount_details.currency, @@ -1451,10 +1451,9 @@ pub fn construct_recovery_record_back_router_data( }, response: Err(types::ErrorResponse::default()), }; - let old_router_data = - flow_common_types::RevenueRecoveryRecordBackData::to_old_router_data(router_data) - .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) - .attach_printable("Cannot construct record back router data")?; + let old_router_data = flow_common_types::InvoiceRecordBackData::to_old_router_data(router_data) + .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) + .attach_printable("Cannot construct record back router data")?; Ok(old_router_data) } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index fa8e840fdea..7d59a1cad30 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -105,7 +105,7 @@ pub type BoxedAccessTokenConnectorIntegrationInterface<T, Req, Resp> = pub type BoxedFilesConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::FilesFlowData, Req, Resp>; pub type BoxedRevenueRecoveryRecordBackInterface<T, Req, Res> = - BoxedConnectorIntegrationInterface<T, common_types::RevenueRecoveryRecordBackData, Req, Res>; + BoxedConnectorIntegrationInterface<T, common_types::InvoiceRecordBackData, Req, Res>; pub type BoxedBillingConnectorInvoiceSyncIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface< T, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 525c25f7369..a4f024eb81c 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -61,7 +61,7 @@ pub use hyperswitch_domain_models::{ router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, - RevenueRecoveryRecordBackRequest, + InvoiceRecordBackRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, @@ -87,7 +87,7 @@ pub use hyperswitch_domain_models::{ router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, - RevenueRecoveryRecordBackResponse, + InvoiceRecordBackResponse, }, AcceptDisputeResponse, CaptureSyncResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, MandateReference, MandateRevokeResponseData, PaymentsResponseData,
2025-09-09T10:54:34Z
## 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 --> Make the RevenueRecoveryRecordBack functionality generic to make it usable by subscription after making a successful payment. This pull request refactors the "record back" functionality in the revenue recovery flow by renaming types and data structures from RevenueRecoveryRecordBack* and RecoveryRecordBack to InvoiceRecordBack* and InvoiceRecordBack. This change is applied consistently across domain models, connector implementations, interfaces, and transformers, improving clarity and aligning naming with their purpose (handling invoice record backs). ### 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)? --> Only removing the feature flag and renamed it. compilation and PR checks should be sufficient ## 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
v1.116.0
876ea3f61d599a4fdb9e509523619fe4a8c56c61
876ea3f61d599a4fdb9e509523619fe4a8c56c61
juspay/hyperswitch
juspay__hyperswitch-9313
Bug: [BUG] Nuvei 3ds + psync fix ### Bug Description - 3ds transaction done via hyperswitch was not marked as 3ds in nuvei system. Make a successful 3ds transaction and search the connector transaction id in nuvei dashboard , click `linkage` . InitAuth and Auth3d is not seen. ### Expected Behavior Actual 3ds call should have have 3 calls in linkage 1, `InitAuth` 2. `Auth3d` and 3. `sale` ### 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 - Make a 3ds transaction and go to nuvei dashboard . - - Make a psync , you will see it as completed. ### 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.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs index 259495d0545..9c906abeefc 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs @@ -53,6 +53,7 @@ use masking::ExposeInterface; use transformers as nuvei; use crate::{ + connectors::nuvei::transformers::{NuveiPaymentsResponse, NuveiTransactionSyncResponse}, constants::headers, types::ResponseRouterData, utils::{self, is_mandate_supported, PaymentMethodDataType, RouterData as _}, @@ -211,7 +212,7 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, errors::ConnectorError, > { - let response: nuvei::NuveiPaymentsResponse = res + let response: NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; @@ -234,72 +235,68 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons } } -impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> - for Nuvei -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nuvei { fn get_headers( &self, - req: &PaymentsCompleteAuthorizeRouterData, + 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: &PaymentsCompleteAuthorizeRouterData, + _req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( - "{}ppp/api/v1/payment.do", + "{}ppp/api/v1/voidTransaction.do", ConnectorCommon::base_url(self, connectors) )) } + fn get_request_body( &self, - req: &PaymentsCompleteAuthorizeRouterData, + req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let meta: nuvei::NuveiMeta = utils::to_connector_meta(req.request.connector_meta.clone())?; - let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, meta.session_token))?; + let connector_req = nuvei::NuveiPaymentFlowRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } + fn build_request( &self, - req: &PaymentsCompleteAuthorizeRouterData, + req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { - Ok(Some( - RequestBuilder::new() - .method(Method::Post) - .url(&types::PaymentsCompleteAuthorizeType::get_url( - self, req, connectors, - )?) - .attach_default_headers() - .headers(types::PaymentsCompleteAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( - self, req, connectors, - )?) - .build(), - )) + let request = 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(); + Ok(Some(request)) } + fn handle_response( &self, - data: &PaymentsCompleteAuthorizeRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { - let response: nuvei::NuveiPaymentsResponse = res + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + let response: NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .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(), @@ -317,63 +314,66 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nuvei { +impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> + for Nuvei +{ fn get_headers( &self, - req: &PaymentsCancelRouterData, + req: &PaymentsCompleteAuthorizeRouterData, 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, + _req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( - "{}ppp/api/v1/voidTransaction.do", + "{}ppp/api/v1/payment.do", ConnectorCommon::base_url(self, connectors) )) } - fn get_request_body( &self, - req: &PaymentsCancelRouterData, + req: &PaymentsCompleteAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = nuvei::NuveiPaymentFlowRequest::try_from(req)?; + let meta: nuvei::NuveiMeta = utils::to_connector_meta(req.request.connector_meta.clone())?; + let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, meta.session_token))?; Ok(RequestContent::Json(Box::new(connector_req))) } - fn build_request( &self, - req: &PaymentsCancelRouterData, + req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { - let request = 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(); - Ok(Some(request)) + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) } - fn handle_response( &self, - data: &PaymentsCancelRouterData, + data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { - let response: nuvei::NuveiPaymentsResponse = res + ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { + let response: NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; @@ -458,7 +458,7 @@ impl ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, Paymen event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelPostCaptureRouterData, errors::ConnectorError> { - let response: nuvei::NuveiPaymentsResponse = res + let response: NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; @@ -501,7 +501,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nuv connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( - "{}ppp/api/v1/getPaymentStatus.do", + "{}ppp/api/v1/getTransactionDetails.do", ConnectorCommon::base_url(self, connectors) )) } @@ -546,9 +546,9 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nuv event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: nuvei::NuveiPaymentsResponse = res + let response: NuveiTransactionSyncResponse = res .response - .parse_struct("NuveiPaymentsResponse") + .parse_struct("NuveiTransactionSyncResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); @@ -622,7 +622,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: nuvei::NuveiPaymentsResponse = res + let response: NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; @@ -678,7 +678,6 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; - Ok(RequestContent::Json(Box::new(connector_req))) } @@ -710,7 +709,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: nuvei::NuveiPaymentsResponse = res + let response: NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; @@ -883,13 +882,12 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { - let response: nuvei::NuveiPaymentsResponse = res + let response: NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .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(), @@ -965,7 +963,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nuvei { event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: nuvei::NuveiPaymentsResponse = res + let response: NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; @@ -1124,10 +1122,8 @@ impl IncomingWebhook for Nuvei { // Parse the webhook payload let webhook = serde_urlencoded::from_str::<nuvei::NuveiWebhook>(&request.query_params) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - // Convert webhook to payments response - let payment_response = nuvei::NuveiPaymentsResponse::from(webhook); - + let payment_response = NuveiPaymentsResponse::from(webhook); Ok(Box::new(payment_response)) } } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 0e032c3c804..2092fc40a20 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -49,7 +49,8 @@ use crate::{ utils::{ self, convert_amount, missing_field_err, AddressData, AddressDetailsData, BrowserInformationData, ForeignTryFrom, PaymentsAuthorizeRequestData, - PaymentsCancelRequestData, PaymentsPreProcessingRequestData, RouterData as _, + PaymentsCancelRequestData, PaymentsPreProcessingRequestData, + PaymentsSetupMandateRequestData, RouterData as _, }, }; @@ -136,9 +137,7 @@ impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData { fn get_return_url_required( &self, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { - self.router_return_url - .clone() - .ok_or_else(missing_field_err("return_url")) + self.get_router_return_url() } fn get_capture_method(&self) -> Option<CaptureMethod> { @@ -201,10 +200,6 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { self.customer_id.clone() } - fn get_complete_authorize_url(&self) -> Option<String> { - self.complete_authorize_url.clone() - } - fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id().clone() } @@ -219,6 +214,10 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { self.capture_method } + fn get_complete_authorize_url(&self) -> Option<String> { + self.complete_authorize_url.clone() + } + fn get_minor_amount_required( &self, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { @@ -273,10 +272,6 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { && self.setup_future_usage == Some(FutureUsage::OffSession) } - fn get_complete_authorize_url(&self) -> Option<String> { - self.complete_authorize_url.clone() - } - fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id() } @@ -291,6 +286,10 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { self.capture_method } + fn get_complete_authorize_url(&self) -> Option<String> { + self.complete_authorize_url.clone() + } + fn get_minor_amount_required( &self, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { @@ -502,7 +501,11 @@ pub struct NuveiPaymentFlowRequest { #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuveiPaymentSyncRequest { - pub session_token: Secret<String>, + pub merchant_id: Secret<String>, + pub merchant_site_id: Secret<String>, + pub time_stamp: String, + pub checksum: Secret<String>, + pub transaction_id: String, } #[derive(Debug, Default, Serialize, Deserialize)] @@ -848,9 +851,9 @@ pub struct NuveiACSResponse { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum LiabilityShift { - #[serde(rename = "Y", alias = "1")] + #[serde(rename = "Y", alias = "1", alias = "y")] Success, - #[serde(rename = "N", alias = "0")] + #[serde(rename = "N", alias = "0", alias = "n")] Failed, } @@ -1724,8 +1727,8 @@ where let shipping_address: Option<ShippingAddress> = item.get_optional_shipping().map(|address| address.into()); - let billing_address: Option<BillingAddress> = address.map(|ref address| address.into()); - + let billing_address: Option<BillingAddress> = + address.clone().map(|ref address| address.into()); let device_details = if request_data .device_details .ip_address @@ -1902,25 +1905,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> ..Default::default() }) } - Some(PaymentMethodData::Wallet(..)) - | Some(PaymentMethodData::PayLater(..)) - | Some(PaymentMethodData::BankDebit(..)) - | Some(PaymentMethodData::BankRedirect(..)) - | Some(PaymentMethodData::BankTransfer(..)) - | Some(PaymentMethodData::Crypto(..)) - | Some(PaymentMethodData::MandatePayment) - | Some(PaymentMethodData::GiftCard(..)) - | Some(PaymentMethodData::Voucher(..)) - | Some(PaymentMethodData::CardRedirect(..)) - | Some(PaymentMethodData::Reward) - | Some(PaymentMethodData::RealTimePayment(..)) - | Some(PaymentMethodData::MobilePayment(..)) - | Some(PaymentMethodData::Upi(..)) - | Some(PaymentMethodData::OpenBanking(_)) - | Some(PaymentMethodData::CardToken(..)) - | Some(PaymentMethodData::NetworkToken(..)) - | Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_)) - | None => Err(errors::ConnectorError::NotImplemented( + _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), )), }?; @@ -1938,7 +1923,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> ..Default::default() })?; Ok(Self { - related_transaction_id: request_data.related_transaction_id, + related_transaction_id: item.request.connector_transaction_id.clone(), payment_option: request_data.payment_option, device_details: request_data.device_details, ..request @@ -2071,9 +2056,33 @@ impl TryFrom<&types::RefundExecuteRouterData> for NuveiPaymentFlowRequest { impl TryFrom<&types::PaymentsSyncRouterData> for NuveiPaymentSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { - let meta: NuveiMeta = utils::to_connector_meta(value.request.connector_meta.clone())?; + let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&value.connector_auth_type)?; + let merchant_id = connector_meta.merchant_id.clone(); + let merchant_site_id = connector_meta.merchant_site_id.clone(); + let merchant_secret = connector_meta.merchant_secret.clone(); + let time_stamp = + date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let transaction_id = value + .request + .connector_transaction_id + .clone() + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + let checksum = Secret::new(encode_payload(&[ + merchant_id.peek(), + merchant_site_id.peek(), + &transaction_id, + &time_stamp, + merchant_secret.peek(), + ])?); + Ok(Self { - session_token: meta.session_token, + merchant_id, + merchant_site_id, + time_stamp, + checksum, + transaction_id, }) } } @@ -2189,11 +2198,17 @@ pub enum NuveiPaymentStatus { #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum NuveiTransactionStatus { + #[serde(alias = "Approved", alias = "APPROVED")] Approved, + #[serde(alias = "Declined", alias = "DECLINED")] Declined, + #[serde(alias = "Filter Error", alias = "ERROR", alias = "Error")] Error, + #[serde(alias = "Redirect", alias = "REDIRECT")] Redirect, + #[serde(alias = "Pending", alias = "PENDING")] Pending, + #[serde(alias = "Processing", alias = "PROCESSING")] #[default] Processing, } @@ -2251,35 +2266,105 @@ pub struct NuveiPaymentsResponse { pub client_request_id: Option<String>, pub merchant_advice_code: Option<String>, } -impl NuveiPaymentsResponse { - /// returns amount_captured and minor_amount_capturable - pub fn get_amount_captured( - &self, - ) -> Result<(Option<i64>, Option<MinorUnit>), error_stack::Report<errors::ConnectorError>> { + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiTxnPartialApproval { + requested_amount: Option<StringMajorUnit>, + requested_currency: Option<enums::Currency>, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiTransactionSyncResponseDetails { + gw_error_code: Option<i64>, + gw_error_reason: Option<String>, + gw_extended_error_code: Option<i64>, + transaction_id: Option<String>, + transaction_status: Option<NuveiTransactionStatus>, + transaction_type: Option<NuveiTransactionType>, + auth_code: Option<String>, + processed_amount: Option<StringMajorUnit>, + processed_currency: Option<enums::Currency>, + acquiring_bank_name: Option<String>, +} +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiTransactionSyncResponse { + pub payment_option: Option<PaymentOption>, + pub partial_approval: Option<NuveiTxnPartialApproval>, + pub is_currency_converted: Option<bool>, + pub transaction_details: Option<NuveiTransactionSyncResponseDetails>, + pub fraud_details: Option<FraudDetails>, + pub client_unique_id: Option<String>, + pub internal_request_id: Option<i64>, + pub status: NuveiPaymentStatus, + pub err_code: Option<i64>, + pub reason: Option<String>, + pub merchant_id: Option<Secret<String>>, + pub merchant_site_id: Option<Secret<String>>, + pub version: Option<String>, + pub client_request_id: Option<String>, + pub merchant_advice_code: Option<String>, +} +impl NuveiTransactionSyncResponse { + pub fn get_partial_approval(&self) -> Option<NuveiPartialApproval> { match &self.partial_approval { - Some(partial_approval) => { - let amount = utils::convert_back_amount_to_minor_units( - NUVEI_AMOUNT_CONVERTOR, - partial_approval.processed_amount.clone(), - partial_approval.processed_currency, - )?; - match self.transaction_type { - None => Ok((None, None)), - Some(NuveiTransactionType::Sale) => { - Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) - } - Some(NuveiTransactionType::Auth) => Ok((None, Some(amount))), - Some(NuveiTransactionType::Auth3D) => { - Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) - } - Some(NuveiTransactionType::InitAuth3D) => Ok((None, Some(amount))), - Some(NuveiTransactionType::Credit) => Ok((None, None)), - Some(NuveiTransactionType::Void) => Ok((None, None)), - Some(NuveiTransactionType::Settle) => Ok((None, None)), + Some(partial_approval) => match ( + partial_approval.requested_amount.clone(), + partial_approval.requested_currency, + self.transaction_details + .as_ref() + .and_then(|txn| txn.processed_amount.clone()), + self.transaction_details + .as_ref() + .and_then(|txn| txn.processed_currency), + ) { + ( + Some(requested_amount), + Some(requested_currency), + Some(processed_amount), + Some(processed_currency), + ) => Some(NuveiPartialApproval { + requested_amount, + requested_currency, + processed_amount, + processed_currency, + }), + _ => None, + }, + None => None, + } + } +} + +pub fn get_amount_captured( + partial_approval_data: Option<NuveiPartialApproval>, + transaction_type: Option<NuveiTransactionType>, +) -> Result<(Option<i64>, Option<MinorUnit>), error_stack::Report<errors::ConnectorError>> { + match partial_approval_data { + Some(partial_approval) => { + let amount = utils::convert_back_amount_to_minor_units( + NUVEI_AMOUNT_CONVERTOR, + partial_approval.processed_amount.clone(), + partial_approval.processed_currency, + )?; + match transaction_type { + None => Ok((None, None)), + Some(NuveiTransactionType::Sale) => { + Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) + } + Some(NuveiTransactionType::Auth) => Ok((None, Some(amount))), + Some(NuveiTransactionType::Auth3D) => { + Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) } + Some(NuveiTransactionType::InitAuth3D) => Ok((None, Some(amount))), + Some(NuveiTransactionType::Credit) => Ok((None, None)), + Some(NuveiTransactionType::Void) => Ok((None, None)), + Some(NuveiTransactionType::Settle) => Ok((None, None)), } - None => Ok((None, None)), } + None => Ok((None, None)), } } @@ -2301,13 +2386,15 @@ pub struct FraudDetails { } fn get_payment_status( - response: &NuveiPaymentsResponse, amount: Option<i64>, is_post_capture_void: bool, + transaction_type: Option<NuveiTransactionType>, + transaction_status: Option<NuveiTransactionStatus>, + status: NuveiPaymentStatus, ) -> enums::AttemptStatus { // ZERO dollar authorization - if amount == Some(0) && response.transaction_type.clone() == Some(NuveiTransactionType::Auth) { - return match response.transaction_status.clone() { + if amount == Some(0) && transaction_type == Some(NuveiTransactionType::Auth) { + return match transaction_status { Some(NuveiTransactionStatus::Approved) => enums::AttemptStatus::Charged, Some(NuveiTransactionStatus::Declined) | Some(NuveiTransactionStatus::Error) => { enums::AttemptStatus::AuthorizationFailed @@ -2316,7 +2403,7 @@ fn get_payment_status( enums::AttemptStatus::Pending } Some(NuveiTransactionStatus::Redirect) => enums::AttemptStatus::AuthenticationPending, - None => match response.status { + None => match status { NuveiPaymentStatus::Failed | NuveiPaymentStatus::Error => { enums::AttemptStatus::Failure } @@ -2325,10 +2412,12 @@ fn get_payment_status( }; } - match response.transaction_status.clone() { + match transaction_status { Some(status) => match status { - NuveiTransactionStatus::Approved => match response.transaction_type { - Some(NuveiTransactionType::Auth) => enums::AttemptStatus::Authorized, + NuveiTransactionStatus::Approved => match transaction_type { + Some(NuveiTransactionType::InitAuth3D) | Some(NuveiTransactionType::Auth) => { + enums::AttemptStatus::Authorized + } Some(NuveiTransactionType::Sale) | Some(NuveiTransactionType::Settle) => { enums::AttemptStatus::Charged } @@ -2336,14 +2425,14 @@ fn get_payment_status( enums::AttemptStatus::VoidedPostCharge } Some(NuveiTransactionType::Void) => enums::AttemptStatus::Voided, - + Some(NuveiTransactionType::Auth3D) => enums::AttemptStatus::AuthenticationPending, _ => enums::AttemptStatus::Pending, }, NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => { - match response.transaction_type { + match transaction_type { Some(NuveiTransactionType::Auth) => enums::AttemptStatus::AuthorizationFailed, Some(NuveiTransactionType::Void) => enums::AttemptStatus::VoidFailed, - Some(NuveiTransactionType::Auth3D) => { + Some(NuveiTransactionType::Auth3D) | Some(NuveiTransactionType::InitAuth3D) => { enums::AttemptStatus::AuthenticationFailed } _ => enums::AttemptStatus::Failure, @@ -2354,37 +2443,49 @@ fn get_payment_status( } NuveiTransactionStatus::Redirect => enums::AttemptStatus::AuthenticationPending, }, - None => match response.status { + None => match status { NuveiPaymentStatus::Failed | NuveiPaymentStatus::Error => enums::AttemptStatus::Failure, _ => enums::AttemptStatus::Pending, }, } } -fn build_error_response(response: &NuveiPaymentsResponse, http_code: u16) -> Option<ErrorResponse> { - match response.status { +#[derive(Debug)] +struct ErrorResponseParams { + http_code: u16, + status: NuveiPaymentStatus, + err_code: Option<i64>, + err_msg: Option<String>, + merchant_advice_code: Option<String>, + gw_error_code: Option<i64>, + gw_error_reason: Option<String>, + transaction_status: Option<NuveiTransactionStatus>, +} + +fn build_error_response(params: ErrorResponseParams) -> Option<ErrorResponse> { + match params.status { NuveiPaymentStatus::Error => Some(get_error_response( - response.err_code, - &response.reason, - http_code, - &response.merchant_advice_code, - &response.gw_error_code.map(|e| e.to_string()), - &response.gw_error_reason, + params.err_code, + params.err_msg.clone(), + params.http_code, + params.merchant_advice_code.clone(), + params.gw_error_code.map(|code| code.to_string()), + params.gw_error_reason.clone(), )), _ => { let err = Some(get_error_response( - response.gw_error_code, - &response.gw_error_reason, - http_code, - &response.merchant_advice_code, - &response.gw_error_code.map(|e| e.to_string()), - &response.gw_error_reason, + params.gw_error_code, + params.gw_error_reason.clone(), + params.http_code, + params.merchant_advice_code, + params.gw_error_code.map(|e| e.to_string()), + params.gw_error_reason.clone(), )); - match response.transaction_status { + match params.transaction_status { Some(NuveiTransactionStatus::Error) | Some(NuveiTransactionStatus::Declined) => err, - _ => match response + _ => match params .gw_error_reason .as_ref() .map(|r| r.eq("Missing argument")) @@ -2433,11 +2534,15 @@ impl >, ) -> Result<Self, Self::Error> { let amount = item.data.request.amount; + let response = &item.response; + let (status, redirection_data, connector_response_data) = process_nuvei_payment_response( + NuveiPaymentResponseData::new(amount, false, item.data.payment_method, response), + )?; - let (status, redirection_data, connector_response_data) = - process_nuvei_payment_response(&item, amount, false)?; - - let (amount_captured, minor_amount_capturable) = item.response.get_amount_captured()?; + let (amount_captured, minor_amount_capturable) = get_amount_captured( + response.partial_approval.clone(), + response.transaction_type.clone(), + )?; let ip_address = item .data @@ -2453,16 +2558,31 @@ impl field_name: "browser_info.ip_address", })? .to_string(); + let response = &item.response; Ok(Self { status, - response: if let Some(err) = build_error_response(&item.response, item.http_code) { + response: if let Some(err) = build_error_response(ErrorResponseParams { + http_code: item.http_code, + status: response.status.clone(), + err_code: response.err_code, + err_msg: response.reason.clone(), + merchant_advice_code: response.merchant_advice_code.clone(), + gw_error_code: response.gw_error_code, + gw_error_reason: response.gw_error_reason.clone(), + transaction_status: response.transaction_status.clone(), + }) { Err(err) } else { + let response = &item.response; Ok(create_transaction_response( - &item.response, redirection_data, Some(ip_address), + response.transaction_id.clone(), + response.order_id.clone(), + response.session_token.clone(), + response.external_scheme_transaction_id.clone(), + response.payment_option.clone(), )?) }, amount_captured, @@ -2475,10 +2595,64 @@ impl // Helper function to process Nuvei payment response -fn process_nuvei_payment_response<F, T>( - item: &ResponseRouterData<F, NuveiPaymentsResponse, T, PaymentsResponseData>, - amount: Option<i64>, - is_post_capture_void: bool, +/// Struct to encapsulate parameters for processing Nuvei payment responses +#[derive(Debug)] +pub struct NuveiPaymentResponseData { + pub amount: Option<i64>, + pub is_post_capture_void: bool, + pub payment_method: enums::PaymentMethod, + pub payment_option: Option<PaymentOption>, + pub transaction_type: Option<NuveiTransactionType>, + pub transaction_status: Option<NuveiTransactionStatus>, + pub status: NuveiPaymentStatus, + pub merchant_advice_code: Option<String>, +} + +impl NuveiPaymentResponseData { + pub fn new( + amount: Option<i64>, + is_post_capture_void: bool, + payment_method: enums::PaymentMethod, + response: &NuveiPaymentsResponse, + ) -> Self { + Self { + amount, + is_post_capture_void, + payment_method, + payment_option: response.payment_option.clone(), + transaction_type: response.transaction_type.clone(), + transaction_status: response.transaction_status.clone(), + status: response.status.clone(), + merchant_advice_code: response.merchant_advice_code.clone(), + } + } + + pub fn new_from_sync_response( + amount: Option<i64>, + is_post_capture_void: bool, + payment_method: enums::PaymentMethod, + response: &NuveiTransactionSyncResponse, + ) -> Self { + let transaction_details = &response.transaction_details; + Self { + amount, + is_post_capture_void, + payment_method, + payment_option: response.payment_option.clone(), + transaction_type: transaction_details + .as_ref() + .and_then(|details| details.transaction_type.clone()), + transaction_status: transaction_details + .as_ref() + .and_then(|details| details.transaction_status.clone()), + status: response.status.clone(), + merchant_advice_code: None, + } + } +} + +fn process_nuvei_payment_response( + data: NuveiPaymentResponseData, ) -> Result< ( enums::AttemptStatus, @@ -2486,20 +2660,14 @@ fn process_nuvei_payment_response<F, T>( Option<ConnectorResponseData>, ), error_stack::Report<errors::ConnectorError>, -> -where - F: std::fmt::Debug, - T: std::fmt::Debug, -{ - let redirection_data = match item.data.payment_method { - enums::PaymentMethod::Wallet | enums::PaymentMethod::BankRedirect => item - .response +> { + let redirection_data = match data.payment_method { + enums::PaymentMethod::Wallet | enums::PaymentMethod::BankRedirect => data .payment_option .as_ref() .and_then(|po| po.redirect_url.clone()) .map(|base_url| RedirectForm::from((base_url, Method::Get))), - _ => item - .response + _ => data .payment_option .as_ref() .and_then(|o| o.card.clone()) @@ -2511,32 +2679,42 @@ where form_fields: std::collections::HashMap::from([("creq".to_string(), creq.expose())]), }), }; - let connector_response_data = - convert_to_additional_payment_method_connector_response(&item.response) - .map(ConnectorResponseData::with_additional_payment_method_data); - let status = get_payment_status(&item.response, amount, is_post_capture_void); + let connector_response_data = convert_to_additional_payment_method_connector_response( + data.payment_option.clone(), + data.merchant_advice_code, + ) + .map(ConnectorResponseData::with_additional_payment_method_data); + let status = get_payment_status( + data.amount, + data.is_post_capture_void, + data.transaction_type, + data.transaction_status, + data.status, + ); Ok((status, redirection_data, connector_response_data)) } // Helper function to create transaction response fn create_transaction_response( - response: &NuveiPaymentsResponse, redirection_data: Option<RedirectForm>, ip_address: Option<String>, + transaction_id: Option<String>, + order_id: Option<String>, + session_token: Option<Secret<String>>, + external_scheme_transaction_id: Option<Secret<String>>, + payment_option: Option<PaymentOption>, ) -> Result<PaymentsResponseData, error_stack::Report<errors::ConnectorError>> { Ok(PaymentsResponseData::TransactionResponse { - resource_id: response - .transaction_id + resource_id: transaction_id .clone() - .map_or(response.order_id.clone(), Some) // For paypal there will be no transaction_id, only order_id will be present + .map_or(order_id.clone(), Some) // For paypal there will be no transaction_id, only order_id will be present .map(ResponseId::ConnectorTransactionId) .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, redirection_data: Box::new(redirection_data), mandate_reference: Box::new( - response - .payment_option + payment_option .as_ref() .and_then(|po| po.user_payment_option_id.clone()) .map(|id| MandateReference { @@ -2548,7 +2726,7 @@ fn create_transaction_response( }), ), // we don't need to save session token for capture, void flow so ignoring if it is not present - connector_metadata: if let Some(token) = response.session_token.clone() { + connector_metadata: if let Some(token) = session_token { Some( serde_json::to_value(NuveiMeta { session_token: token, @@ -2558,11 +2736,10 @@ fn create_transaction_response( } else { None }, - network_txn_id: response - .external_scheme_transaction_id + network_txn_id: external_scheme_transaction_id .as_ref() .map(|ntid| ntid.clone().expose()), - connector_response_reference_id: response.order_id.clone(), + connector_response_reference_id: order_id.clone(), incremental_authorization_allowed: None, charges: None, }) @@ -2590,11 +2767,15 @@ impl ) -> Result<Self, Self::Error> { // Get amount directly from the authorize data let amount = Some(item.data.request.amount); + let response = &item.response; + let (status, redirection_data, connector_response_data) = process_nuvei_payment_response( + NuveiPaymentResponseData::new(amount, false, item.data.payment_method, response), + )?; - let (status, redirection_data, connector_response_data) = - process_nuvei_payment_response(&item, amount, false)?; - - let (amount_captured, minor_amount_capturable) = item.response.get_amount_captured()?; + let (amount_captured, minor_amount_capturable) = get_amount_captured( + response.partial_approval.clone(), + response.transaction_type.clone(), + )?; let ip_address = item .data @@ -2605,13 +2786,27 @@ impl Ok(Self { status, - response: if let Some(err) = build_error_response(&item.response, item.http_code) { + response: if let Some(err) = build_error_response(ErrorResponseParams { + http_code: item.http_code, + status: response.status.clone(), + err_code: response.err_code, + err_msg: response.reason.clone(), + merchant_advice_code: response.merchant_advice_code.clone(), + gw_error_code: response.gw_error_code, + gw_error_reason: response.gw_error_reason.clone(), + transaction_status: response.transaction_status.clone(), + }) { Err(err) } else { + let response = &item.response; Ok(create_transaction_response( - &item.response, redirection_data, ip_address, + response.transaction_id.clone(), + response.order_id.clone(), + response.session_token.clone(), + response.external_scheme_transaction_id.clone(), + response.payment_option.clone(), )?) }, amount_captured, @@ -2638,19 +2833,113 @@ where .data .minor_amount_capturable .map(|amount| amount.get_amount_as_i64()); + let response = &item.response; let (status, redirection_data, connector_response_data) = - process_nuvei_payment_response(&item, amount, F::is_post_capture_void())?; + process_nuvei_payment_response(NuveiPaymentResponseData::new( + amount, + F::is_post_capture_void(), + item.data.payment_method, + response, + ))?; + + let (amount_captured, minor_amount_capturable) = get_amount_captured( + response.partial_approval.clone(), + response.transaction_type.clone(), + )?; + Ok(Self { + status, + response: if let Some(err) = build_error_response(ErrorResponseParams { + http_code: item.http_code, + status: response.status.clone(), + err_code: response.err_code, + err_msg: response.reason.clone(), + merchant_advice_code: response.merchant_advice_code.clone(), + gw_error_code: response.gw_error_code, + gw_error_reason: response.gw_error_reason.clone(), + transaction_status: response.transaction_status.clone(), + }) { + Err(err) + } else { + let response = &item.response; + Ok(create_transaction_response( + redirection_data, + None, + response.transaction_id.clone(), + response.order_id.clone(), + response.session_token.clone(), + response.external_scheme_transaction_id.clone(), + response.payment_option.clone(), + )?) + }, + amount_captured, + minor_amount_capturable, + connector_response: connector_response_data, + ..item.data + }) + } +} - let (amount_captured, minor_amount_capturable) = item.response.get_amount_captured()?; +// Generic implementation for other flow types +impl<F, T> TryFrom<ResponseRouterData<F, NuveiTransactionSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +where + F: NuveiPaymentsGenericResponse + std::fmt::Debug, + T: std::fmt::Debug, + F: std::any::Any, +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, NuveiTransactionSyncResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let amount = item + .data + .minor_amount_capturable + .map(|amount| amount.get_amount_as_i64()); + let response = &item.response; + let transaction_details = &response.transaction_details; + let transaction_type = transaction_details + .as_ref() + .and_then(|details| details.transaction_type.clone()); + let (status, redirection_data, connector_response_data) = + process_nuvei_payment_response(NuveiPaymentResponseData::new_from_sync_response( + amount, + F::is_post_capture_void(), + item.data.payment_method, + response, + ))?; + + let (amount_captured, minor_amount_capturable) = + get_amount_captured(response.get_partial_approval(), transaction_type.clone())?; Ok(Self { status, - response: if let Some(err) = build_error_response(&item.response, item.http_code) { + response: if let Some(err) = build_error_response(ErrorResponseParams { + http_code: item.http_code, + status: response.status.clone(), + err_code: response.err_code, + err_msg: response.reason.clone(), + merchant_advice_code: None, + gw_error_code: transaction_details + .as_ref() + .and_then(|details| details.gw_error_code), + gw_error_reason: transaction_details + .as_ref() + .and_then(|details| details.gw_error_reason.clone()), + transaction_status: transaction_details + .as_ref() + .and_then(|details| details.transaction_status.clone()), + }) { Err(err) } else { Ok(create_transaction_response( - &item.response, redirection_data, None, + transaction_details + .as_ref() + .and_then(|data| data.transaction_id.clone()), + None, + None, + None, + response.payment_option.clone(), )?) }, amount_captured, @@ -2678,12 +2967,17 @@ impl TryFrom<PaymentsPreprocessingResponseRouterData<NuveiPaymentsResponse>> .map(to_boolean) .unwrap_or_default(); Ok(Self { - status: get_payment_status(&response, item.data.request.amount, false), + status: get_payment_status( + item.data.request.amount, + false, + response.transaction_type, + response.transaction_status, + response.status, + ), response: Ok(PaymentsResponseData::ThreeDSEnrollmentResponse { enrolled_v2: is_enrolled_for_3ds, related_transaction_id: response.transaction_id, }), - ..item.data }) } @@ -2760,11 +3054,7 @@ where .request .get_customer_id_required() .ok_or(missing_field_err("customer_id")())?; - let related_transaction_id = if item.is_three_ds() { - item.request.get_related_transaction_id().clone() - } else { - None - }; + let related_transaction_id = item.request.get_related_transaction_id().clone(); let ip_address = data .recurring_mandate_payment_data @@ -2823,20 +3113,20 @@ fn get_refund_response( match response.status { NuveiPaymentStatus::Error => Err(Box::new(get_error_response( response.err_code, - &response.reason, + response.reason.clone(), http_code, - &response.merchant_advice_code, - &response.gw_error_code.map(|e| e.to_string()), - &response.gw_error_reason, + response.merchant_advice_code, + response.gw_error_code.map(|e| e.to_string()), + response.gw_error_reason, ))), _ => match response.transaction_status { Some(NuveiTransactionStatus::Error) => Err(Box::new(get_error_response( response.err_code, - &response.reason, + response.reason, http_code, - &response.merchant_advice_code, - &response.gw_error_code.map(|e| e.to_string()), - &response.gw_error_reason, + response.merchant_advice_code, + response.gw_error_code.map(|e| e.to_string()), + response.gw_error_reason, ))), _ => Ok(RefundsResponseData { connector_refund_id: txn_id, @@ -2848,11 +3138,11 @@ fn get_refund_response( fn get_error_response( error_code: Option<i64>, - error_msg: &Option<String>, + error_msg: Option<String>, http_code: u16, - network_advice_code: &Option<String>, - network_decline_code: &Option<String>, - network_error_message: &Option<String>, + network_advice_code: Option<String>, + network_decline_code: Option<String>, + network_error_message: Option<String>, ) -> ErrorResponse { ErrorResponse { code: error_code @@ -3049,6 +3339,7 @@ impl From<NuveiWebhook> for NuveiPaymentsResponse { TransactionStatus::Declined => NuveiTransactionStatus::Declined, TransactionStatus::Error => NuveiTransactionStatus::Error, TransactionStatus::Settled => NuveiTransactionStatus::Approved, + _ => NuveiTransactionStatus::Processing, }), transaction_id: notification.transaction_id, @@ -3116,21 +3407,17 @@ pub fn concat_strings(strings: &[String]) -> String { } fn convert_to_additional_payment_method_connector_response( - transaction_response: &NuveiPaymentsResponse, + payment_option: Option<PaymentOption>, + merchant_advice_code: Option<String>, ) -> Option<AdditionalPaymentMethodConnectorResponse> { - let card = transaction_response - .payment_option - .as_ref()? - .card - .as_ref()?; + let card = payment_option.as_ref()?.card.as_ref()?; let avs_code = card.avs_code.as_ref(); let cvv2_code = card.cvv2_reply.as_ref(); - let merchant_advice_code = transaction_response.merchant_advice_code.as_ref(); - let avs_description = avs_code.and_then(|code| get_avs_response_description(code)); let cvv_description = cvv2_code.and_then(|code| get_cvv2_response_description(code)); - let merchant_advice_description = - merchant_advice_code.and_then(|code| get_merchant_advice_code_description(code)); + let merchant_advice_description = merchant_advice_code + .as_ref() + .and_then(|code| get_merchant_advice_code_description(code)); let payment_checks = serde_json::json!({ "avs_result": avs_code,
2025-09-04T10:06:21Z
## 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 --> - 3ds transaction were not actually 3ds transactions in Nuvei system. This occurred because we were not passing previous transaction data while making 3ds complete-authorize call. - Prevoiusly psync was implemeted with session token. If we make 3ds payment but not confirm and make psycn the nuvei would return error as session transaction not found. Now we have implemented psync with transaction_id . ## TEST ### Trigger 3ds payment <details> <summary> Request </summary> ```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" } } } ``` </details> <details> <summary> Response </summary> ``` { "payment_id": "pay_wiZYcVFqfCNBOJMEpznT", "merchant_id": "merchant_1756789409", "status": "requires_customer_action", "amount": 15100, "net_amount": 15100, "shipping_cost": null, "amount_capturable": 15100, "amount_received": null, "connector": "nuvei", "client_secret": "pay_wiZYcVFqfCNBOJMEpznT_secret_GiNUpAUyDpT4rK5COmn9", "created": "2025-09-10T05:09:57.712Z", "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_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "cReq": "eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjE4MWEzOTQ4LWI5ZmYtNGMyZi05ODJkLTAzOTU1OTYzMjhjMSIsImFjc1RyYW5zSUQiOiIwMjcwOTg4OC0xNWIxLTRjOWMtYTA2OC04ZWVlMTBlZmRlODIiLCJjaGFsbGVuZ2VXaW5kb3dTaXplIjoiMDUiLCJtZXNzYWdlVHlwZSI6IkNSZXEiLCJtZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0", "flow": "challenge", "acsUrl": "https://3dsn.sandbox.safecharge.com/ThreeDSACSEmulatorChallenge/api/ThreeDSACSChallengeController/ChallengePage?eyJub3RpZmljYXRpb25VUkwiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcGF5bWVudHMvcGF5X3dpWlljVkZxZkNOQk9KTUVwem5UL21lcmNoYW50XzE3NTY3ODk0MDkvcmVkaXJlY3QvY29tcGxldGUvbnV2ZWkiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjE4MWEzOTQ4LWI5ZmYtNGMyZi05ODJkLTAzOTU1OTYzMjhjMSIsImFjc1RyYW5zSUQiOiIwMjcwOTg4OC0xNWIxLTRjOWMtYTA2OC04ZWVlMTBlZmRlODIiLCJkc1RyYW5zSUQiOiJmMmRhYTg2Yi1kZWM2LTQ0ZmItODQzMC0zNGI4ZGFhZGVlMjAiLCJkYXRhIjpudWxsLCJNZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0=", "version": "2.2.0", "threeDFlow": "1", "decisionReason": "NoPreference", "threeDReasonId": "", "acquirerDecision": "ExemptionRequest", "challengePreferenceReason": "12", "isExemptionRequestInAuthentication": "0" } }, "billing": null }, "payment_token": "token_zab9VyBWQCNOWzesgwEe", "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_wiZYcVFqfCNBOJMEpznT/merchant_1756789409/pay_wiZYcVFqfCNBOJMEpznT_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": 1757480997, "expires": 1757484597, "secret": "epk_f4e147f4736a41c0bf152be511495bd2" }, "manual_retry_allowed": null, "connector_transaction_id": "8110000000013946637", "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": "8656791111", "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-10T05:24:57.712Z", "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_PNtSuuIcOnjnfMyAoL8x", "network_transaction_id": null, "payment_method_status": "inactive", "updated": "2025-09-10T05:10:01.440Z", "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 } ``` </details> - connector_transaction_id = `8110000000013946637` ### Make psync Before redirection <details> <summary>Response </summary> ```json { "payment_id": "pay_wiZYcVFqfCNBOJMEpznT", "merchant_id": "merchant_1756789409", "status": "requires_customer_action", "amount": 15100, "net_amount": 15100, "shipping_cost": null, "amount_capturable": 15100, "amount_received": null, "connector": "nuvei", "client_secret": "pay_wiZYcVFqfCNBOJMEpznT_secret_GiNUpAUyDpT4rK5COmn9", "created": "2025-09-10T05:09:57.712Z", "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_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "cReq": "eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjE4MWEzOTQ4LWI5ZmYtNGMyZi05ODJkLTAzOTU1OTYzMjhjMSIsImFjc1RyYW5zSUQiOiIwMjcwOTg4OC0xNWIxLTRjOWMtYTA2OC04ZWVlMTBlZmRlODIiLCJjaGFsbGVuZ2VXaW5kb3dTaXplIjoiMDUiLCJtZXNzYWdlVHlwZSI6IkNSZXEiLCJtZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0", "flow": "challenge", "acsUrl": "https://3dsn.sandbox.safecharge.com/ThreeDSACSEmulatorChallenge/api/ThreeDSACSChallengeController/ChallengePage?eyJub3RpZmljYXRpb25VUkwiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcGF5bWVudHMvcGF5X3dpWlljVkZxZkNOQk9KTUVwem5UL21lcmNoYW50XzE3NTY3ODk0MDkvcmVkaXJlY3QvY29tcGxldGUvbnV2ZWkiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjE4MWEzOTQ4LWI5ZmYtNGMyZi05ODJkLTAzOTU1OTYzMjhjMSIsImFjc1RyYW5zSUQiOiIwMjcwOTg4OC0xNWIxLTRjOWMtYTA2OC04ZWVlMTBlZmRlODIiLCJkc1RyYW5zSUQiOiJmMmRhYTg2Yi1kZWM2LTQ0ZmItODQzMC0zNGI4ZGFhZGVlMjAiLCJkYXRhIjpudWxsLCJNZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0=", "version": "2.2.0", "threeDFlow": "1", "decisionReason": "NoPreference", "threeDReasonId": "", "acquirerDecision": "ExemptionRequest", "challengePreferenceReason": "12", "isExemptionRequestInAuthentication": "0" } }, "billing": null }, "payment_token": "token_zab9VyBWQCNOWzesgwEe", "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_wiZYcVFqfCNBOJMEpznT/merchant_1756789409/pay_wiZYcVFqfCNBOJMEpznT_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": null, "manual_retry_allowed": null, "connector_transaction_id": "8110000000013946637", "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": "8656791111", "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-10T05:24:57.712Z", "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_PNtSuuIcOnjnfMyAoL8x", "network_transaction_id": null, "payment_method_status": "inactive", "updated": "2025-09-10T05:11:10.384Z", "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 } ``` </details> ### Complete redirection challenge ### Check Psync again <details> <summary>Response </summary> ```json { "payment_id": "pay_wiZYcVFqfCNBOJMEpznT", "merchant_id": "merchant_1756789409", "status": "succeeded", "amount": 15100, "net_amount": 15100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 15100, "connector": "nuvei", "client_secret": "pay_wiZYcVFqfCNBOJMEpznT_secret_GiNUpAUyDpT4rK5COmn9", "created": "2025-09-10T05:09:57.712Z", "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_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "flow": "challenge", "version": "2.2.0", "decisionReason": "NoPreference", "threeDReasonId": "", "acquirerDecision": "ExemptionRequest", "isLiabilityOnIssuer": "1", "challengeCancelReason": "", "challengeCancelReasonId": "", "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_zab9VyBWQCNOWzesgwEe", "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": 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": "8110000000013946718", "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": "8656791111", "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-10T05:24:57.712Z", "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_PNtSuuIcOnjnfMyAoL8x", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-09-10T05:11:56.957Z", "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 } ``` </details> - connector_transaction_id : `8110000000013946718` ### Check transaction in nuvei dashboard for complete validation <img width="1857" height="938" alt="Screenshot 2025-09-10 at 10 43 50 AM" src="https://github.com/user-attachments/assets/2985795f-8c0b-43d8-a58f-fecd59af3273" /> <img width="1761" height="859" alt="Screenshot 2025-09-10 at 10 44 16 AM" src="https://github.com/user-attachments/assets/7d2436df-1004-4de0-b1e3-d6fcfb83adef" /> <img width="1356" height="1029" alt="Screenshot 2025-09-10 at 11 04 41 AM" src="https://github.com/user-attachments/assets/bd1bafeb-19e3-475d-a4a5-266d1cca0ce9" /> <img width="1728" height="1078" alt="Screenshot 2025-09-10 at 11 08 15 AM" src="https://github.com/user-attachments/assets/43c00bb3-1c0c-4366-92d2-1fed1f498f64" /> | InitAuth3d | Auth3d | Sale | |----------|----------|----------| | 8110000000013946633 | 8110000000013946637 | 8110000000013946718 | <!-- Similarly test txn id for manual capture 8110000000013946951 --> ## 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
v1.116.0
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
juspay/hyperswitch
juspay__hyperswitch-9309
Bug: FEATURE: [Paysafe] Implement card 3ds flow - Implement card 3ds flow
diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe.rs b/crates/hyperswitch_connectors/src/connectors/paysafe.rs index 64296c2ebe6..8d463966748 100644 --- a/crates/hyperswitch_connectors/src/connectors/paysafe.rs +++ b/crates/hyperswitch_connectors/src/connectors/paysafe.rs @@ -17,15 +17,15 @@ use hyperswitch_domain_models::{ router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{ - Authorize, Capture, PSync, PaymentMethodToken, PreProcessing, Session, SetupMandate, - Void, + Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, PreProcessing, + Session, SetupMandate, Void, }, refunds::{Execute, RSync}, }, router_request_types::{ - AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, - PaymentsSyncData, RefundsData, SetupMandateRequestData, + AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, + PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, @@ -33,8 +33,8 @@ use hyperswitch_domain_models::{ }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData, - RefundsRouterData, + PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -54,7 +54,10 @@ use transformers as paysafe; use crate::{ constants::headers, types::ResponseRouterData, - utils::{self, RefundsRequestData as OtherRefundsRequestData}, + utils::{ + self, PaymentsSyncRequestData, RefundsRequestData as OtherRefundsRequestData, + RouterData as _, + }, }; #[derive(Clone)] @@ -262,7 +265,6 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); let connector_req = paysafe::PaysafePaymentHandleRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) } @@ -333,10 +335,15 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, - _req: &PaymentsAuthorizeRouterData, + req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}v1/payments", self.base_url(connectors),)) + match req.payment_method { + enums::PaymentMethod::Card if !req.is_three_ds() => { + Ok(format!("{}v1/payments", self.base_url(connectors))) + } + _ => Ok(format!("{}v1/paymenthandles", self.base_url(connectors),)), + } } fn get_request_body( @@ -351,8 +358,19 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData )?; let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); - let connector_req = paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + match req.payment_method { + //Card No 3DS + enums::PaymentMethod::Card if !req.is_three_ds() => { + 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)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + } } fn build_request( @@ -383,17 +401,122 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + match data.payment_method { + enums::PaymentMethod::Card if !data.is_three_ds() => { + 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 + .parse_struct("Paysafe PaymentHandleResponse") + .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 api::PaymentsCompleteAuthorize for Paysafe {} + +impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> + for Paysafe +{ + fn get_headers( + &self, + req: &PaymentsCompleteAuthorizeRouterData, + 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: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}v1/payments", self.base_url(connectors),)) + } + fn get_request_body( + &self, + req: &PaymentsCompleteAuthorizeRouterData, + _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 = paysafe::PaysafeRouterData::from((amount, req)); + let connector_req = paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + fn handle_response( + &self, + data: &PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { 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, }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( @@ -424,11 +547,17 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pay connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.connector_request_reference_id.clone(); - Ok(format!( - "{}v1/payments?merchantRefNum={}", - self.base_url(connectors), - connector_payment_id - )) + let connector_transaction_id = req.request.get_optional_connector_transaction_id(); + + let base_url = self.base_url(connectors); + + let url = if connector_transaction_id.is_some() { + format!("{base_url}v1/payments?merchantRefNum={connector_payment_id}") + } else { + format!("{base_url}v1/paymenthandles?merchantRefNum={connector_payment_id}") + }; + + Ok(url) } fn build_request( @@ -452,9 +581,9 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pay event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: paysafe::PaysafePaymentsSyncResponse = res + let response: paysafe::PaysafeSyncResponse = res .response - .parse_struct("paysafe PaysafePaymentsSyncResponse") + .parse_struct("paysafe PaysafeSyncResponse") .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/paysafe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs index 50c665a65bd..26e9d8de48d 100644 --- a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs @@ -1,5 +1,7 @@ +use std::collections::HashMap; + use cards::CardNumber; -use common_enums::enums; +use common_enums::{enums, Currency}; use common_utils::{ pii::{IpAddress, SecretSerdeValue}, request::Method, @@ -11,12 +13,13 @@ use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ - PaymentsAuthorizeData, PaymentsPreProcessingData, PaymentsSyncData, ResponseId, + CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreProcessingData, PaymentsSyncData, + ResponseId, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsPreProcessingRouterData, RefundsRouterData, + PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; @@ -26,8 +29,8 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ - self, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, - PaymentsPreProcessingRequestData, RouterData as _, + self, to_connector_meta, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, + PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _, }, }; @@ -47,7 +50,18 @@ impl<T> From<(MinorUnit, T)> for PaysafeRouterData<T> { #[derive(Debug, Default, Serialize, Deserialize)] pub struct PaysafeConnectorMetadataObject { - pub account_id: Secret<String>, + pub account_id: PaysafePaymentMethodDetails, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct PaysafePaymentMethodDetails { + pub card: Option<HashMap<Currency, CardAccountId>>, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct CardAccountId { + no_three_ds: Option<Secret<String>>, + three_ds: Option<Secret<String>>, } impl TryFrom<&Option<SecretSerdeValue>> for PaysafeConnectorMetadataObject { @@ -61,18 +75,65 @@ impl TryFrom<&Option<SecretSerdeValue>> for PaysafeConnectorMetadataObject { } } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThreeDs { + pub merchant_url: String, + pub device_channel: DeviceChannel, + pub message_category: ThreeDsMessageCategory, + pub authentication_purpose: ThreeDsAuthenticationPurpose, + pub requestor_challenge_preference: ThreeDsChallengePreference, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum DeviceChannel { + Browser, + Sdk, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ThreeDsMessageCategory { + Payment, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ThreeDsAuthenticationPurpose { + PaymentTransaction, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ThreeDsChallengePreference { + ChallengeMandated, + NoPreference, + NoChallengeRequested, + ChallengeRequested, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafePaymentHandleRequest { pub merchant_ref_num: String, pub amount: MinorUnit, pub settle_with_auth: bool, - pub card: PaysafeCard, - pub currency_code: enums::Currency, + #[serde(flatten)] + pub payment_method: PaysafePaymentMethod, + pub currency_code: Currency, pub payment_type: PaysafePaymentType, pub transaction_type: TransactionType, pub return_links: Vec<ReturnLink>, pub account_id: Secret<String>, + pub three_ds: Option<ThreeDs>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum PaysafePaymentMethod { + Card { card: PaysafeCard }, } #[derive(Debug, Serialize)] @@ -103,6 +164,34 @@ pub enum TransactionType { Payment, } +impl PaysafePaymentMethodDetails { + pub fn get_no_three_ds_account_id( + &self, + currency: Currency, + ) -> Result<Secret<String>, errors::ConnectorError> { + self.card + .as_ref() + .and_then(|cards| cards.get(&currency)) + .and_then(|card| card.no_three_ds.clone()) + .ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig { + config: "Missing no_3ds account_id", + }) + } + + pub fn get_three_ds_account_id( + &self, + currency: Currency, + ) -> Result<Secret<String>, errors::ConnectorError> { + self.card + .as_ref() + .and_then(|cards| cards.get(&currency)) + .and_then(|card| card.three_ds.clone()) + .ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig { + config: "Missing 3ds account_id", + }) + } +} + impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePaymentHandleRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( @@ -119,6 +208,7 @@ impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePa .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 { @@ -134,8 +224,9 @@ impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePa }, holder_name: item.router_data.get_optional_billing_full_name(), }; - let account_id = metadata.account_id; + 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; @@ -170,12 +261,13 @@ impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePa item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None ), - card, - currency_code: item.router_data.request.get_currency()?, + payment_method, + currency_code: currency, payment_type, transaction_type, return_links, account_id, + three_ds: None, }) } _ => Err(errors::ConnectorError::NotImplemented( @@ -192,6 +284,13 @@ pub struct PaysafePaymentHandleResponse { pub merchant_ref_num: String, pub payment_handle_token: Secret<String>, pub status: PaysafePaymentHandleStatus, + pub links: Option<Vec<PaymentLink>>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaymentLink { + pub rel: String, + pub href: String, } #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] @@ -206,6 +305,23 @@ pub enum PaysafePaymentHandleStatus { Completed, } +impl TryFrom<PaysafePaymentHandleStatus> for common_enums::AttemptStatus { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: PaysafePaymentHandleStatus) -> Result<Self, Self::Error> { + match item { + PaysafePaymentHandleStatus::Completed => Ok(Self::Authorized), + PaysafePaymentHandleStatus::Failed | PaysafePaymentHandleStatus::Expired => { + 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 => { + Ok(Self::Pending) + } + } + } +} + #[derive(Debug, Serialize, Deserialize)] pub struct PaysafeMeta { pub payment_handle_token: Secret<String>, @@ -287,6 +403,54 @@ impl<F> } } +impl<F> + TryFrom< + ResponseRouterData< + F, + PaysafePaymentHandleResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + PaysafePaymentHandleResponse, + PaymentsAuthorizeData, + 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 connector_metadata = serde_json::json!(PaysafeMeta { + payment_handle_token: item.response.payment_handle_token.clone(), + }); + Ok(Self { + status: common_enums::AttemptStatus::try_from(item.response.status)?, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), + connector_metadata: Some(connector_metadata), + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafePaymentsRequest { @@ -294,11 +458,11 @@ pub struct PaysafePaymentsRequest { pub amount: MinorUnit, pub settle_with_auth: bool, pub payment_handle_token: Secret<String>, - pub currency_code: enums::Currency, + pub currency_code: Currency, pub customer_ip: Option<Secret<String, IpAddress>>, } -#[derive(Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaysafeCard { pub card_num: CardNumber, @@ -319,12 +483,6 @@ impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymen fn try_from( item: &PaysafeRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - if item.router_data.is_three_ds() { - Err(errors::ConnectorError::NotSupported { - message: "Card 3DS".to_string(), - connector: "Paysafe", - })? - }; let payment_handle_token = Secret::new(item.router_data.get_preprocessing_id()?); let amount = item.amount; let customer_ip = Some( @@ -345,6 +503,169 @@ impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymen } } +impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentHandleRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PaysafeRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + 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 redirect_url_success = item.router_data.request.get_complete_authorize_url()?; + 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_success.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 amount = item.amount; + let currency_code = item.router_data.request.currency; + let settle_with_auth = matches!( + item.router_data.request.capture_method, + 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, + }); + + 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(), + ))?, + } + } +} + +impl TryFrom<&PaysafeRouterData<&PaymentsCompleteAuthorizeRouterData>> for PaysafePaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PaysafeRouterData<&PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let paysafe_meta: PaysafeMeta = to_connector_meta( + item.router_data.request.connector_meta.clone(), + ) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "connector_metadata", + })?; + let payment_handle_token = paysafe_meta.payment_handle_token; + let amount = item.amount; + let customer_ip = Some( + item.router_data + .request + .get_browser_info()? + .get_ip_address()?, + ); + + Ok(Self { + merchant_ref_num: item.router_data.connector_request_reference_id.clone(), + payment_handle_token, + amount, + settle_with_auth: item.router_data.request.is_auto_capture()?, + currency_code: item.router_data.request.currency, + customer_ip, + }) + } +} + +impl<F> + TryFrom< + ResponseRouterData<F, PaysafePaymentsResponse, CompleteAuthorizeData, PaymentsResponseData>, + > for RouterData<F, CompleteAuthorizeData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + PaysafePaymentsResponse, + CompleteAuthorizeData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: get_paysafe_payment_status( + item.response.status, + item.data.request.capture_method, + ), + 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 + }) + } +} + pub struct PaysafeAuthType { pub(super) username: Secret<String>, pub(super) password: Secret<String>, @@ -402,6 +723,13 @@ pub fn get_paysafe_payment_status( } } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PaysafeSyncResponse { + Payments(PaysafePaymentsSyncResponse), + PaymentHandles(PaysafePaymentHandlesSyncResponse), +} + // Paysafe Payments Response Structure #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -409,6 +737,12 @@ pub struct PaysafePaymentsSyncResponse { pub payments: Vec<PaysafePaymentsResponse>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafePaymentHandlesSyncResponse { + pub payment_handles: Vec<PaysafePaymentHandleResponse>, +} + // Paysafe Payments Response Structure #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] @@ -427,30 +761,34 @@ pub struct PaysafeSettlementResponse { pub status: PaysafeSettlementStatus, } -impl<F> - TryFrom< - ResponseRouterData<F, PaysafePaymentsSyncResponse, PaymentsSyncData, PaymentsResponseData>, - > for RouterData<F, PaymentsSyncData, PaymentsResponseData> +impl<F> TryFrom<ResponseRouterData<F, PaysafeSyncResponse, PaymentsSyncData, PaymentsResponseData>> + for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData< - F, - PaysafePaymentsSyncResponse, - PaymentsSyncData, - PaymentsResponseData, - >, + item: ResponseRouterData<F, PaysafeSyncResponse, PaymentsSyncData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let payment_handle = item - .response - .payments - .first() - .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + let status = match &item.response { + PaysafeSyncResponse::Payments(sync_response) => { + let payment_response = sync_response + .payments + .first() + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + get_paysafe_payment_status( + payment_response.status, + item.data.request.capture_method, + ) + } + PaysafeSyncResponse::PaymentHandles(sync_response) => { + let payment_handle_response = sync_response + .payment_handles + .first() + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + common_enums::AttemptStatus::try_from(payment_handle_response.status)? + } + }; Ok(Self { - status: get_paysafe_payment_status( - payment_handle.status, - item.data.request.capture_method, - ), + status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), @@ -700,6 +1038,6 @@ pub struct Error { #[derive(Debug, Serialize, Deserialize)] pub struct FieldError { - pub field: String, + pub field: Option<String>, pub error: String, } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 0535088c884..ce4f694b7c5 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -1145,7 +1145,6 @@ macro_rules! default_imp_for_complete_authorize { } default_imp_for_complete_authorize!( - connectors::Paysafe, connectors::Silverflow, connectors::Vgs, connectors::Aci, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index c6bb9f10f0d..4b7d75ed772 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -2078,6 +2078,7 @@ pub trait PaymentsSyncRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>; fn is_mandate_payment(&self) -> bool; + fn get_optional_connector_transaction_id(&self) -> Option<String>; } impl PaymentsSyncRequestData for PaymentsSyncData { @@ -2105,6 +2106,13 @@ impl PaymentsSyncRequestData for PaymentsSyncData { fn is_mandate_payment(&self) -> bool { matches!(self.setup_future_usage, Some(FutureUsage::OffSession)) } + + fn get_optional_connector_transaction_id(&self) -> Option<String> { + match self.connector_transaction_id.clone() { + ResponseId::ConnectorTransactionId(txn_id) => Some(txn_id), + _ => None, + } + } } pub trait PaymentsPostSessionTokensRequestData {
2025-09-08T16:59:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Implement card 3ds flow for Paysafe ### 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 card 3ds payment for paysafe ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: _' \ --data '{ "amount": 1500, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "payment_method": "card", "payment_method_type": "credit", "profile_id": "pro_ndJetHbOnmgPs4ed6FLr", "authentication_type" : "three_ds", "payment_method_data": { "card": { "card_number": "4000000000001091", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph", "card_cvc": "111" } }, "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" } }, "shipping": { "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" } }, "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_UZEf5nPy4rjBtygB8Wm1", "merchant_id": "merchant_1757407144", "status": "requires_customer_action", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 1500, "amount_received": null, "connector": "paysafe", "client_secret": "pay_UZEf5nPy4rjBtygB8Wm1_secret_mMQoKXN8QCHYDAl0fYKQ", "created": "2025-09-09T09:23:44.962Z", "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": "card", "payment_method_data": { "card": { "last4": "1091", "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": "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": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_UZEf5nPy4rjBtygB8Wm1/merchant_1757407144/pay_UZEf5nPy4rjBtygB8Wm1_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": "aaaa", "created_at": 1757409824, "expires": 1757413424, "secret": "epk_e1f53385eb104247b6d2a830b38696de" }, "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_ndJetHbOnmgPs4ed6FLr", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uXktUCjj5V9CBf3x48Pz", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-09T09:38:44.962Z", "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-09T09:23:46.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 } ``` complete the payment using redirection 2. sync payment ``` curl --location 'http://localhost:8080/payments/pay_UZEf5nPy4rjBtygB8Wm1?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_tFbrAdIUEDW40STTsNQNk5dFxYgRoZPtPW7GtKCP7tbSapty2u1UuDBxl4zkLCxf' ``` Response ``` { "payment_id": "pay_UZEf5nPy4rjBtygB8Wm1", "merchant_id": "merchant_1757407144", "status": "succeeded", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1500, "connector": "paysafe", "client_secret": "pay_UZEf5nPy4rjBtygB8Wm1_secret_mMQoKXN8QCHYDAl0fYKQ", "created": "2025-09-09T09:23:44.962Z", "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": "card", "payment_method_data": { "card": { "last4": "1091", "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": "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": false, "connector_transaction_id": "3dbc45d1-878b-446c-8b97-3d299aa3effc", "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_ndJetHbOnmgPs4ed6FLr", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uXktUCjj5V9CBf3x48Pz", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-09T09:38:44.962Z", "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-09T09:25:27.509Z", "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 } ``` cypress <img width="1131" height="846" alt="Screenshot 2025-09-11 at 6 33 31 PM" src="https://github.com/user-attachments/assets/6e7669a6-6af3-4362-9afe-8cc8f832fd15" /> <img width="1201" height="813" alt="Screenshot 2025-09-11 at 6 33 59 PM" src="https://github.com/user-attachments/assets/3429e33b-6fbf-41a0-bb70-3de0add2f46c" /> After redirection i m using ngrok as , connector only allows https redirection. ## 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
v1.116.0
5ab8a27c10786885b91b79fbb9fb8b5e990029e1
5ab8a27c10786885b91b79fbb9fb8b5e990029e1
juspay/hyperswitch
juspay__hyperswitch-9297
Bug: [Bug] Update Redis TTL for customer locks after token selection The revenue recovery workflow currently does not update the Redis TTL for a connector customer lock after the decider service selects the best PSP token. This behavior can lead to a customer lock expiring prematurely, which breaks the consistency of the recovery process.
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index ce683012090..100dc665e91 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -22451,6 +22451,14 @@ } ], "default": "skip" + }, + "revenue_recovery_retry_algorithm_type": { + "allOf": [ + { + "$ref": "#/components/schemas/RevenueRecoveryAlgorithmType" + } + ], + "nullable": true } } }, @@ -23599,6 +23607,14 @@ } } }, + "RevenueRecoveryAlgorithmType": { + "type": "string", + "enum": [ + "monitoring", + "smart", + "cascading" + ] + }, "RevenueRecoveryMetadata": { "type": "object", "description": "Revenue recovery metadata for merchant connector account", diff --git a/config/config.example.toml b/config/config.example.toml index b725be102c1..4ce52dfac4f 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1241,6 +1241,7 @@ initial_timestamp_in_seconds = 3600 # number of seconds added to start job_schedule_buffer_time_in_seconds = 3600 # buffer time in seconds to schedule the job for Revenue Recovery reopen_workflow_buffer_time_in_seconds = 3600 # time in seconds to be added in scheduling for calculate workflow max_random_schedule_delay_in_seconds = 300 # max random delay in seconds to schedule the payment for Revenue Recovery +redis_ttl_buffer_in_seconds= 300 # buffer time in seconds to be added to redis ttl for Revenue Recovery [clone_connector_allowlist] merchant_ids = "merchant_ids" # Comma-separated list of allowed merchant IDs diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index bfba035c1f3..726bdbe21a9 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -415,6 +415,7 @@ initial_timestamp_in_seconds = 3600 # number of seconds added to start ti 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 = 3600 # time in seconds to be added in scheduling for calculate workflow max_random_schedule_delay_in_seconds = 300 # max random delay in seconds to schedule the payment for Revenue Recovery +redis_ttl_buffer_in_seconds=300 # buffer time in seconds to be added to redis ttl for Revenue Recovery [chat] enabled = false # Enable or disable chat features diff --git a/config/development.toml b/config/development.toml index 940e43b50ca..07cadbf3058 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1340,6 +1340,7 @@ initial_timestamp_in_seconds = 3600 job_schedule_buffer_time_in_seconds = 3600 reopen_workflow_buffer_time_in_seconds = 3600 max_random_schedule_delay_in_seconds = 300 +redis_ttl_buffer_in_seconds= 300 [revenue_recovery.card_config.amex] max_retries_per_day = 20 diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 3844fa34bc4..b0b656a1ede 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2718,6 +2718,11 @@ pub struct ProfileResponse { /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = SplitTxnsEnabled, default = "skip")] pub split_txns_enabled: common_enums::SplitTxnsEnabled, + + /// Indicates the state of revenue recovery algorithm type + #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] + pub revenue_recovery_retry_algorithm_type: + Option<common_enums::enums::RevenueRecoveryAlgorithmType>, } #[cfg(feature = "v1")] diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index c0b042b182f..71fe216322d 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -801,6 +801,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodSessionResponse, api_models::payment_methods::AuthenticationDetails, api_models::process_tracker::revenue_recovery::RevenueRecoveryResponse, + api_models::enums::RevenueRecoveryAlgorithmType, api_models::enums::ProcessTrackerStatus, api_models::proxy::ProxyRequest, api_models::proxy::ProxyResponse, diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index d63cbd5f906..f714564e1f3 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -671,8 +671,9 @@ async fn update_calculate_job_schedule_time( base_time: Option<time::PrimitiveDateTime>, connector_customer_id: &str, ) -> Result<(), sch_errors::ProcessTrackerError> { - let new_schedule_time = - base_time.unwrap_or_else(common_utils::date_time::now) + additional_time; + let now = common_utils::date_time::now(); + + let new_schedule_time = base_time.filter(|&t| t > now).unwrap_or(now) + additional_time; logger::info!( new_schedule_time = %new_schedule_time, process_id = %process.id, diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index f63259b0c85..40532480d38 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -806,17 +806,13 @@ impl Action { .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; - let is_hard_decline = - revenue_recovery::check_hard_decline(state, &payment_attempt) - .await - .ok(); - // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &None, - &is_hard_decline, + // Since this is succeeded, 'hard_decine' will be false. + &Some(false), used_token.as_deref(), ) .await; @@ -900,13 +896,25 @@ impl Action { logger::info!("Entering psync_response_handler"); let db = &*state.store; + + let connector_customer_id = payment_intent + .feature_metadata + .as_ref() + .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref()) + .map(|rr| { + rr.billing_connector_payment_details + .connector_customer_id + .clone() + }); + match self { Self::SyncPayment(payment_attempt) => { // get a schedule time for psync // and retry the process if there is a schedule time // if None mark the pt status as Retries Exceeded and finish the task - payment_sync::retry_sync_task( - db, + payment_sync::recovery_retry_sync_task( + state, + connector_customer_id, revenue_recovery_metadata.connector.to_string(), revenue_recovery_payment_data .merchant_account diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 2576bfbd8fc..0e8cb60ff81 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -322,6 +322,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { merchant_category_code: item.merchant_category_code, 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, }) } } diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index 5a3f9f1bf7e..48110eb92ed 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -81,6 +81,7 @@ pub struct RecoveryTimestamp { pub job_schedule_buffer_time_in_seconds: i64, pub reopen_workflow_buffer_time_in_seconds: i64, pub max_random_schedule_delay_in_seconds: i64, + pub redis_ttl_buffer_in_seconds: i64, } impl Default for RecoveryTimestamp { @@ -90,6 +91,7 @@ impl Default for RecoveryTimestamp { job_schedule_buffer_time_in_seconds: 15, reopen_workflow_buffer_time_in_seconds: 60, max_random_schedule_delay_in_seconds: 300, + redis_ttl_buffer_in_seconds: 300, } } } 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 e4eec924a98..f083e8bbbed 100644 --- a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs +++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs @@ -61,12 +61,22 @@ pub struct PaymentProcessorTokenWithRetryInfo { pub retry_wait_time_hours: i64, /// Number of retries remaining in the 30-day rolling window pub monthly_retry_remaining: i32, + // Current total retry count in 30-day window + pub total_30_day_retries: i32, } /// Redis-based token management struct pub struct RedisTokenManager; impl RedisTokenManager { + fn get_connector_customer_lock_key(connector_customer_id: &str) -> String { + format!("customer:{connector_customer_id}:status") + } + + fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String { + format!("customer:{connector_customer_id}:tokens") + } + /// Lock connector customer #[instrument(skip_all)] pub async fn lock_connector_customer_status( @@ -82,7 +92,7 @@ impl RedisTokenManager { errors::RedisError::RedisConnectionError.into(), ))?; - let lock_key = format!("customer:{connector_customer_id}:status"); + let lock_key = Self::get_connector_customer_lock_key(connector_customer_id); let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds; let result: bool = match redis_conn @@ -109,6 +119,42 @@ impl RedisTokenManager { Ok(result) } + #[instrument(skip_all)] + pub async fn update_connector_customer_lock_ttl( + state: &SessionState, + connector_customer_id: &str, + exp_in_seconds: i64, + ) -> CustomResult<bool, errors::StorageError> { + let redis_conn = + state + .store + .get_redis_conn() + .change_context(errors::StorageError::RedisError( + errors::RedisError::RedisConnectionError.into(), + ))?; + + let lock_key = Self::get_connector_customer_lock_key(connector_customer_id); + + let result: bool = redis_conn + .set_expiry(&lock_key.into(), exp_in_seconds) + .await + .map_or_else( + |error| { + tracing::error!(operation = "update_lock_ttl", err = ?error); + false + }, + |_| true, + ); + + tracing::debug!( + connector_customer_id = connector_customer_id, + new_ttl_in_seconds = exp_in_seconds, + ttl_updated = %result, + "Connector customer lock TTL update with new expiry time" + ); + + Ok(result) + } /// Unlock connector customer status #[instrument(skip_all)] @@ -124,7 +170,7 @@ impl RedisTokenManager { errors::RedisError::RedisConnectionError.into(), ))?; - let lock_key = format!("customer:{connector_customer_id}:status"); + let lock_key = Self::get_connector_customer_lock_key(connector_customer_id); match redis_conn.delete_key(&lock_key.into()).await { Ok(DelReply::KeyDeleted) => { @@ -158,7 +204,7 @@ impl RedisTokenManager { .change_context(errors::StorageError::RedisError( errors::RedisError::RedisConnectionError.into(), ))?; - let tokens_key = format!("customer:{connector_customer_id}:tokens"); + let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id); let get_hash_err = errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into()); @@ -209,7 +255,7 @@ impl RedisTokenManager { .change_context(errors::StorageError::RedisError( errors::RedisError::RedisConnectionError.into(), ))?; - let tokens_key = format!("customer:{connector_customer_id}:tokens"); + let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id); // allocate capacity up-front to avoid rehashing let mut serialized_payment_processor_tokens: HashMap<String, String> = @@ -312,15 +358,18 @@ impl RedisTokenManager { // Obtain network-specific limits and compute remaining monthly retries. let card_network_config = card_config.get_network_config(card_network); - let monthly_retry_remaining = card_network_config - .max_retry_count_for_thirty_day - .saturating_sub(retry_info.total_30_day_retries); + let monthly_retry_remaining = std::cmp::max( + 0, + card_network_config.max_retry_count_for_thirty_day + - retry_info.total_30_day_retries, + ); // Build the per-token result struct. let token_with_retry_info = PaymentProcessorTokenWithRetryInfo { token_status: payment_processor_token_status.clone(), retry_wait_time_hours, monthly_retry_remaining, + total_30_day_retries: retry_info.total_30_day_retries, }; result.insert(payment_processor_token_id.clone(), token_with_retry_info); @@ -367,6 +416,7 @@ impl RedisTokenManager { let monthly_wait_hours = if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day { (0..RETRY_WINDOW_DAYS) + .rev() .map(|i| today - Duration::days(i.into())) .find(|date| token.daily_retry_history.get(date).copied().unwrap_or(0) > 0) .map(|date| Self::calculate_wait_hours(date + Duration::days(31), now)) diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index d7ac92e131e..f0bd7e3619d 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "v2")] +use common_utils::ext_traits::AsyncExt; use common_utils::ext_traits::{OptionExt, StringExt, ValueExt}; use diesel_models::process_tracker::business_status; use error_stack::ResultExt; @@ -7,6 +9,8 @@ use scheduler::{ errors as sch_errors, utils as scheduler_utils, }; +#[cfg(feature = "v2")] +use crate::workflows::revenue_recovery::update_token_expiry_based_on_schedule_time; use crate::{ consts, core::{ @@ -304,6 +308,51 @@ pub async fn retry_sync_task( } } +/// Schedule the task for retry and update redis token expiry time +/// +/// Returns bool which indicates whether this was the last retry or not +#[cfg(feature = "v2")] +pub async fn recovery_retry_sync_task( + state: &SessionState, + connector_customer_id: Option<String>, + connector: String, + merchant_id: common_utils::id_type::MerchantId, + pt: storage::ProcessTracker, +) -> Result<bool, sch_errors::ProcessTrackerError> { + let db = &*state.store; + let schedule_time = + get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; + + match schedule_time { + Some(s_time) => { + db.as_scheduler().retry_process(pt, s_time).await?; + + connector_customer_id + .async_map(|id| async move { + let _ = update_token_expiry_based_on_schedule_time(state, &id, Some(s_time)) + .await + .map_err(|e| { + logger::error!( + error = ?e, + connector_customer_id = %id, + "Failed to update the token expiry time in redis" + ); + e + }); + }) + .await; + + Ok(false) + } + None => { + db.as_scheduler() + .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) + .await?; + Ok(true) + } + } +} + #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index b85ebd3ff11..6a6d9511062 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -371,10 +371,7 @@ pub(crate) async fn get_schedule_time_for_smart_retry( card_network: card_network_str, card_issuer: card_issuer_str, invoice_start_time: Some(start_time_proto), - retry_count: Some( - (total_retry_count_within_network.max_retry_count_for_thirty_day - retry_count_left) - .into(), - ), + retry_count: Some(token_with_retry_info.total_30_day_retries.into()), merchant_id, invoice_amount, invoice_currency, @@ -513,6 +510,47 @@ pub struct ScheduledToken { pub schedule_time: time::PrimitiveDateTime, } +#[cfg(feature = "v2")] +pub fn calculate_difference_in_seconds(scheduled_time: time::PrimitiveDateTime) -> i64 { + let now_utc = time::OffsetDateTime::now_utc(); + + let scheduled_offset_dt = scheduled_time.assume_utc(); + let difference = scheduled_offset_dt - now_utc; + + difference.whole_seconds() +} + +#[cfg(feature = "v2")] +pub async fn update_token_expiry_based_on_schedule_time( + state: &SessionState, + connector_customer_id: &str, + delayed_schedule_time: Option<time::PrimitiveDateTime>, +) -> CustomResult<(), errors::ProcessTrackerError> { + let expiry_buffer = state + .conf + .revenue_recovery + .recovery_timestamp + .redis_ttl_buffer_in_seconds; + + delayed_schedule_time + .async_map(|t| async move { + let expiry_time = calculate_difference_in_seconds(t) + expiry_buffer; + RedisTokenManager::update_connector_customer_lock_ttl( + state, + connector_customer_id, + expiry_time, + ) + .await + .change_context(errors::ProcessTrackerError::ERedisError( + errors::RedisError::RedisConnectionError.into(), + )) + }) + .await + .transpose()?; + + Ok(()) +} + #[cfg(feature = "v2")] pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type( state: &SessionState, @@ -553,6 +591,13 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type( let delayed_schedule_time = scheduled_time.map(|time| add_random_delay_to_schedule_time(state, time)); + let _ = update_token_expiry_based_on_schedule_time( + state, + connector_customer_id, + delayed_schedule_time, + ) + .await; + Ok(delayed_schedule_time) }
2025-09-04T11:57:18Z
## 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 implements an update mechanism for Redis Time-to-Live (TTL) for connector customer locks within the revenue recovery workflow. When the decider service provides token with scheduled time, the system now updates the TTL for the corresponding customer lock in Redis. The new TTL is calculated as the difference between the schedule_time_selected_token and the current time. The default TTL for these locks is set to 3888000 seconds (approximately 45 days). This update ensures that the lock's expiration aligns with the newly scheduled event, preventing premature lock release. A log entry is generated to track this change, with the message: Connector customer lock TTL update with new expiry time. Added revenue_recovery_retry_algorithm_type in business profile response. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- 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)? --> For testing refer to this : https://github.com/juspay/hyperswitch/pull/8848 System Update the Redis TTL for a connector customer lock after a best Payment Processor Token is selected. Logs - "Connector customer lock TTL update with new expiry time" <img width="356" height="57" alt="Screenshot 2025-09-08 at 11 15 41 AM" src="https://github.com/user-attachments/assets/13fe578a-1914-4823-b54e-94351c2b562d" /> ### Business profile #### curl ``` curl --location --request PUT 'http://localhost:8080/v2/profiles/pro_0GHXcjcAhvGPXGu0pitK' \ --header 'x-merchant-id: cloth_seller_yMwFFEtiXtszMGELTg2P' \ --header 'Authorization: admin-api-key={}' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "profile_name": "Update334", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "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 }, "metadata": null, "order_fulfillment_time": 900, "order_fulfillment_time_origin": "create", "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "collect_shipping_details_from_wallet_connector_if_required": false, "collect_billing_details_from_wallet_connector_if_required": 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, "revenue_recovery_retry_algorithm_type": "smart" }' ``` #### Response ``` { "merchant_id": "cloth_seller_yMwFFEtiXtszMGELTg2P", "id": "pro_0GHXcjcAhvGPXGu0pitK", "profile_name": "Update334", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "OxvXuBlTAtrqwP9VGJ9VIR1Zg7WDo1ZHEFDOxYMo4V2knbIWZA10OLE6ofW7kih8", "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, "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_if_required": false, "collect_billing_details_from_wallet_connector_if_required": 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, "order_fulfillment_time": 900, "order_fulfillment_time_origin": "create", "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "should_collect_cvv_during_payment": 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, "is_debit_routing_enabled": false, "merchant_business_country": null, "is_iframe_redirection_enabled": null, "is_external_vault_enabled": null, "external_vault_connector_details": null, "merchant_category_code": null, "merchant_country_code": null, "split_txns_enabled": "skip", "revenue_recovery_retry_algorithm_type": "smart" } ``` ## 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
v1.116.0
ea2fd1d4768f83d8564477ef82940a5f33b0e3a1
ea2fd1d4768f83d8564477ef82940a5f33b0e3a1
juspay/hyperswitch
juspay__hyperswitch-9295
Bug: feat(webhooks): Provide outgoing webhook support for revenue recovery Provide outgoing webhook support for revenue recovery. Based on the retry status send out outgoing webhooks to the url in business profile in v2.
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 100dc665e91..1fcc816ce88 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -20023,7 +20023,8 @@ "status", "amount", "customer_id", - "created" + "created", + "modified_at" ], "properties": { "id": { @@ -20058,6 +20059,12 @@ "description": "Time when the payment was created", "example": "2022-09-10T10:11:12Z" }, + "modified_at": { + "type": "string", + "format": "date-time", + "description": "Time when the payment was last modified", + "example": "2022-09-10T10:11:12Z" + }, "payment_method_data": { "allOf": [ { @@ -20208,6 +20215,11 @@ } ], "nullable": true + }, + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index bb53eb1b6ee..52f75bbe8be 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6170,6 +6170,11 @@ pub struct PaymentsResponse { #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, + /// Time when the payment was last modified + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, + /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] @@ -6252,6 +6257,10 @@ pub struct PaymentsResponse { /// Additional data that might be required by hyperswitch based on the additional features. pub feature_metadata: Option<FeatureMetadata>, + + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] @@ -9662,6 +9671,10 @@ pub struct RecoveryPaymentsCreate { /// Type of action that needs to be taken after consuming the recovery payload. For example: scheduling a failed payment or stopping the invoice. pub action: common_payments_types::RecoveryAction, + + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, } /// Error details for the payment diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 6d942980e2f..83e4795f3ef 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -612,6 +612,7 @@ impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceD retry_count, next_billing_at: invoice_next_billing_time, billing_started_at, + metadata: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs index a44a4d31a95..17b7fbd6ed6 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs @@ -422,6 +422,7 @@ impl TryFrom<StripebillingInvoiceBody> for revenue_recovery::RevenueRecoveryInvo retry_count: Some(item.data.object.attempt_count), next_billing_at, billing_started_at, + metadata: None, }) } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 6249053c36b..c8ac34f8613 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -964,7 +964,7 @@ impl<F: Clone> PaymentConfirmData<F> { } #[cfg(feature = "v2")] -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct PaymentStatusData<F> where F: Clone, diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 094905b1baf..8377fb06cba 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -1,6 +1,6 @@ use api_models::{payments as api_payments, webhooks}; use common_enums::enums as common_enums; -use common_utils::{id_type, types as util_types}; +use common_utils::{id_type, pii, types as util_types}; use time::PrimitiveDateTime; use crate::{ @@ -77,6 +77,8 @@ pub struct RevenueRecoveryInvoiceData { pub next_billing_at: Option<PrimitiveDateTime>, /// Invoice Starting Time pub billing_started_at: Option<PrimitiveDateTime>, + /// metadata of the merchant + pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Clone, Debug)] @@ -153,7 +155,7 @@ impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentReq statement_descriptor: None, order_details: None, allowed_payment_method_types: None, - metadata: None, + metadata: data.metadata.clone(), connector_metadata: None, feature_metadata: None, payment_link_enabled: None, @@ -178,6 +180,7 @@ impl From<&BillingConnectorInvoiceSyncResponse> for RevenueRecoveryInvoiceData { retry_count: data.retry_count, next_billing_at: data.ends_at, billing_started_at: data.created_at, + metadata: None, } } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 595b437675e..6c9a1babb7d 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2390,6 +2390,7 @@ where customer_id: payment_intent.customer_id.clone(), connector: Some(connector), created: payment_intent.created_at, + modified_at: payment_intent.modified_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), payment_method_subtype: Some(payment_attempt.payment_method_subtype), @@ -2410,7 +2411,10 @@ where is_iframe_redirection_enabled: None, merchant_reference_id: payment_intent.merchant_reference_id.clone(), raw_connector_response, - feature_metadata: None, + feature_metadata: payment_intent + .feature_metadata + .map(|feature_metadata| feature_metadata.convert_back()), + metadata: payment_intent.metadata, }; Ok(services::ApplicationResponse::JsonWithHeaders(( @@ -2501,6 +2505,7 @@ where .map(From::from), shipping: self.payment_address.get_shipping().cloned().map(From::from), created: payment_intent.created_at, + modified_at: payment_intent.modified_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), payment_method_subtype: Some(payment_attempt.payment_method_subtype), @@ -2519,7 +2524,10 @@ where is_iframe_redirection_enabled: payment_intent.is_iframe_redirection_enabled, merchant_reference_id: payment_intent.merchant_reference_id.clone(), raw_connector_response, - feature_metadata: None, + feature_metadata: payment_intent + .feature_metadata + .map(|feature_metadata| feature_metadata.convert_back()), + metadata: payment_intent.metadata, }; Ok(services::ApplicationResponse::JsonWithHeaders(( diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index f714564e1f3..f9662a745dd 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -1,29 +1,45 @@ pub mod api; pub mod transformers; pub mod types; -use api_models::{enums, process_tracker::revenue_recovery, webhooks}; +use std::marker::PhantomData; + +use api_models::{ + enums, + payments::{self as api_payments, PaymentsResponse}, + process_tracker::revenue_recovery, + webhooks, +}; use common_utils::{ self, errors::CustomResult, - ext_traits::{OptionExt, ValueExt}, + ext_traits::{AsyncExt, OptionExt, ValueExt}, id_type, }; use diesel_models::{enums as diesel_enum, process_tracker::business_status}; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ - payments::PaymentIntent, revenue_recovery as domain_revenue_recovery, - ApiModelToDieselModelConvertor, + merchant_context, + payments::{PaymentIntent, PaymentStatusData}, + revenue_recovery as domain_revenue_recovery, ApiModelToDieselModelConvertor, }; use scheduler::errors as sch_errors; use crate::{ - core::errors::{self, RouterResponse, RouterResult, StorageErrorExt}, + core::{ + errors::{self, RouterResponse, RouterResult, StorageErrorExt}, + payments::{ + self, + operations::{GetTrackerResponse, Operation}, + transformers::GenerateResponse, + }, + revenue_recovery::types::RevenueRecoveryOutgoingWebhook, + }, db::StorageInterface, logger, routes::{app::ReqState, metrics, SessionState}, services::ApplicationResponse, types::{ - domain, + api as router_api_types, domain, storage::{self, revenue_recovery as pcr}, transformers::{ForeignFrom, ForeignInto}, }, @@ -220,7 +236,7 @@ pub async fn perform_execute_payment( .await; match record_attempt { - Ok(_) => { + Ok(record_attempt_response) => { let action = Box::pin(types::Action::execute_payment( state, revenue_recovery_payment_data.merchant_account.get_id(), @@ -230,6 +246,7 @@ pub async fn perform_execute_payment( merchant_context, revenue_recovery_payment_data, &revenue_recovery_metadata, + &record_attempt_response.id, )) .await?; Box::pin(action.execute_payment_task_response_handler( @@ -414,10 +431,12 @@ pub async fn perform_payments_sync( state, &tracking_data.global_payment_id, revenue_recovery_payment_data, + true, + true, ) .await?; - let payment_attempt = psync_data.payment_attempt; + let payment_attempt = psync_data.payment_attempt.clone(); let mut revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() @@ -426,6 +445,12 @@ pub async fn perform_payments_sync( .convert_back(); let pcr_status: types::RevenueRecoveryPaymentsAttemptStatus = payment_attempt.status.foreign_into(); + + let new_revenue_recovery_payment_data = &pcr::RevenueRecoveryPaymentData { + psync_data: Some(psync_data), + ..revenue_recovery_payment_data.clone() + }; + Box::pin( pcr_status.update_pt_status_based_on_attempt_status_for_payments_sync( state, @@ -433,7 +458,7 @@ pub async fn perform_payments_sync( process.clone(), profile, merchant_context, - revenue_recovery_payment_data, + new_revenue_recovery_payment_data, payment_attempt, &mut revenue_recovery_metadata, ), @@ -457,6 +482,8 @@ pub async fn perform_calculate_workflow( let profile_id = revenue_recovery_payment_data.profile.get_id(); let billing_mca_id = revenue_recovery_payment_data.billing_mca.get_id(); + let mut event_type: Option<common_enums::EventType> = None; + logger::info!( process_id = %process.id, payment_id = %tracking_data.global_payment_id.get_string_repr(), @@ -488,6 +515,20 @@ pub async fn perform_calculate_workflow( } }; + // External Payments which enter the calculate workflow for the first time will have active attempt id as None + // Then we dont need to send an webhook to the merchant as its not a failure from our side. + // Thus we dont need to a payment get call for such payments. + let active_payment_attempt_id = payment_intent.active_attempt_id.as_ref(); + + let payments_response = get_payment_response_using_payment_get_operation( + state, + &tracking_data.global_payment_id, + revenue_recovery_payment_data, + &merchant_context_from_revenue_recovery_payment_data, + active_payment_attempt_id, + ) + .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, @@ -517,6 +558,14 @@ pub async fn perform_calculate_workflow( "Found best available token, creating EXECUTE_WORKFLOW task" ); + // reset active attmept id and payment connector transmission before going to execute workflow + let _ = Box::pin(reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow( + state, + payment_intent, + revenue_recovery_payment_data, + active_payment_attempt_id + )).await?; + // 3. If token found: create EXECUTE_WORKFLOW task and finish CALCULATE_WORKFLOW insert_execute_pcr_task_to_pt( &tracking_data.billing_mca_id, @@ -649,6 +698,8 @@ pub async fn perform_calculate_workflow( sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; + event_type = Some(common_enums::EventType::PaymentFailed); + logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, @@ -660,6 +711,34 @@ pub async fn perform_calculate_workflow( } } } + + let _outgoing_webhook = event_type.and_then(|event_kind| { + payments_response.map(|resp| Some((event_kind, resp))) + }) + .flatten() + .async_map(|(event_kind, response)| async move { + let _ = RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( + state, + common_enums::EventClass::Payments, + event_kind, + payment_intent, + &merchant_context, + profile, + tracking_data.payment_attempt_id.get_string_repr().to_string(), + response + ) + .await + .map_err(|e| { + logger::error!( + error = ?e, + "Failed to send outgoing webhook" + ); + e + }) + .ok(); + } + ).await; + Ok(()) } @@ -937,3 +1016,88 @@ pub async fn retrieve_revenue_recovery_process_tracker( }; Ok(ApplicationResponse::Json(response)) } + +pub async fn get_payment_response_using_payment_get_operation( + state: &SessionState, + payment_intent_id: &id_type::GlobalPaymentId, + revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, + merchant_context: &domain::MerchantContext, + active_payment_attempt_id: Option<&id_type::GlobalAttemptId>, +) -> Result<Option<ApplicationResponse<PaymentsResponse>>, sch_errors::ProcessTrackerError> { + match active_payment_attempt_id { + Some(_) => { + let payment_response = api::call_psync_api( + state, + payment_intent_id, + revenue_recovery_payment_data, + false, + false, + ) + .await?; + let payments_response = payment_response.generate_response( + state, + None, + None, + None, + merchant_context, + &revenue_recovery_payment_data.profile, + None, + )?; + + Ok(Some(payments_response)) + } + None => Ok(None), + } +} + +// This function can be implemented to reset the connector transmission and active attempt ID +// before pushing to the execute workflow. +pub async fn reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow( + state: &SessionState, + payment_intent: &PaymentIntent, + revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, + active_payment_attempt_id: Option<&id_type::GlobalAttemptId>, +) -> Result<Option<()>, sch_errors::ProcessTrackerError> { + let mut revenue_recovery_metadata = payment_intent + .feature_metadata + .as_ref() + .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()) + .get_required_value("Payment Revenue Recovery Metadata")? + .convert_back(); + match active_payment_attempt_id { + Some(_) => { + // update the connector payment transmission field to Unsuccessful and unset active attempt id + revenue_recovery_metadata.set_payment_transmission_field_for_api_request( + enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, + ); + + let payment_update_req = + api_payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( + payment_intent + .feature_metadata + .clone() + .unwrap_or_default() + .convert_back() + .set_payment_revenue_recovery_metadata_using_api( + revenue_recovery_metadata.clone(), + ), + enums::UpdateActiveAttempt::Unset, + ); + logger::info!( + "Call made to payments update intent api , with the request body {:?}", + payment_update_req + ); + api::update_payment_intent_api( + state, + payment_intent.id.clone(), + revenue_recovery_payment_data, + payment_update_req, + ) + .await + .change_context(errors::RecoveryError::PaymentCallFailed)?; + + Ok(Some(())) + } + None => Ok(None), + } +} diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rs index f7172e2369f..fe919979086 100644 --- a/crates/router/src/core/revenue_recovery/api.rs +++ b/crates/router/src/core/revenue_recovery/api.rs @@ -32,12 +32,14 @@ pub async fn call_psync_api( state: &SessionState, global_payment_id: &id_type::GlobalPaymentId, revenue_recovery_data: &revenue_recovery_types::RevenueRecoveryPaymentData, + force_sync_bool: bool, + expand_attempts_bool: bool, ) -> RouterResult<payments_domain::PaymentStatusData<api_types::PSync>> { let operation = payments::operations::PaymentGet; let req = payments_api::PaymentsRetrieveRequest { - force_sync: true, + force_sync: force_sync_bool, param: None, - expand_attempts: true, + expand_attempts: expand_attempts_bool, return_raw_connector_response: None, merchant_connector_details: None, }; diff --git a/crates/router/src/core/revenue_recovery/transformers.rs b/crates/router/src/core/revenue_recovery/transformers.rs index 9835999627f..df6e430a112 100644 --- a/crates/router/src/core/revenue_recovery/transformers.rs +++ b/crates/router/src/core/revenue_recovery/transformers.rs @@ -56,6 +56,7 @@ impl ForeignFrom<api_models::payments::RecoveryPaymentsCreate> retry_count: None, next_billing_at: None, billing_started_at: data.billing_started_at, + metadata: data.metadata, } } } diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 40532480d38..0b7fb4ad062 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -17,11 +17,12 @@ use diesel_models::{ }; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ + api::ApplicationResponse, business_profile, merchant_connector_account, merchant_context::{Context, MerchantContext}, payments::{ self as domain_payments, payment_attempt::PaymentAttempt, PaymentConfirmData, - PaymentIntent, PaymentIntentData, + PaymentIntent, PaymentIntentData, PaymentStatusData, }, router_data_v2::{self, flow_common_types}, router_flow_types, @@ -35,9 +36,11 @@ use super::errors::StorageErrorExt; use crate::{ core::{ errors::{self, RouterResult}, - payments::{self, helpers, operations::Operation}, + payments::{self, helpers, operations::Operation, transformers::GenerateResponse}, revenue_recovery::{self as revenue_recovery_core, pcr, perform_calculate_workflow}, - webhooks::recovery_incoming as recovery_incoming_flow, + webhooks::{ + create_event_and_trigger_outgoing_webhook, recovery_incoming as recovery_incoming_flow, + }, }, db::StorageInterface, logger, @@ -137,6 +140,12 @@ impl RevenueRecoveryPaymentsAttemptStatus { let retry_count = process_tracker.retry_count; + let psync_response = revenue_recovery_payment_data + .psync_data + .as_ref() + .ok_or(errors::RecoveryError::ValueNotFound) + .attach_printable("Psync data not found in revenue recovery payment data")?; + match self { Self::Succeeded => { // finish psync task as the payment was a success @@ -146,6 +155,9 @@ impl RevenueRecoveryPaymentsAttemptStatus { business_status::PSYNC_WORKFLOW_COMPLETE, ) .await?; + + let event_status = common_enums::EventType::PaymentSucceeded; + // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, @@ -177,6 +189,27 @@ impl RevenueRecoveryPaymentsAttemptStatus { ) .await; + let payments_response = psync_response + .clone() + .generate_response(state, None, None, None, &merchant_context, profile, None) + .change_context(errors::RecoveryError::PaymentsResponseGenerationFailed) + .attach_printable("Failed while generating response for payment")?; + + RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( + state, + common_enums::EventClass::Payments, + event_status, + payment_intent, + &merchant_context, + profile, + recovery_payment_attempt + .attempt_id + .get_string_repr() + .to_string(), + payments_response + ) + .await?; + // Record a successful transaction back to Billing Connector // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( @@ -233,14 +266,15 @@ impl RevenueRecoveryPaymentsAttemptStatus { .await; // Reopen calculate workflow on payment failure - reopen_calculate_workflow_on_payment_failure( + Box::pin(reopen_calculate_workflow_on_payment_failure( state, &process_tracker, profile, merchant_context, payment_intent, revenue_recovery_payment_data, - ) + psync_response.payment_attempt.get_id(), + )) .await?; } Self::Processing => { @@ -308,6 +342,8 @@ impl Decision { state, payment_id, revenue_recovery_data, + true, + true, ) .await .change_context(errors::RecoveryError::PaymentCallFailed) @@ -324,6 +360,8 @@ impl Decision { state, payment_id, revenue_recovery_data, + true, + true, ) .await .change_context(errors::RecoveryError::PaymentCallFailed) @@ -368,6 +406,7 @@ impl Action { merchant_context: domain::MerchantContext, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata, + latest_attempt_id: &id_type::GlobalAttemptId, ) -> RecoveryResult<Self> { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() @@ -426,7 +465,6 @@ impl Action { hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( payment_intent, ); - // handle proxy api's response match response { Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() { @@ -444,16 +482,16 @@ impl Action { // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( - state, - &recovery_payment_tuple, - Some(process.retry_count+1) - ) - .await{ - router_env::logger::error!( - "Failed to publish revenue recovery event to kafka: {:?}", - e - ); - }; + state, + &recovery_payment_tuple, + Some(process.retry_count+1) + ) + .await{ + router_env::logger::error!( + "Failed to publish revenue recovery event to kafka: {:?}", + e + ); + }; let is_hard_decline = revenue_recovery::check_hard_decline( state, @@ -474,10 +512,40 @@ impl Action { // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( - state, - &connector_customer_id, - ) - .await; + state, + &connector_customer_id, + ) + .await; + + let event_status = common_enums::EventType::PaymentSucceeded; + + let payments_response = payment_data + .clone() + .generate_response( + state, + None, + None, + None, + &merchant_context, + profile, + None, + ) + .change_context( + errors::RecoveryError::PaymentsResponseGenerationFailed, + ) + .attach_printable("Failed while generating response for payment")?; + + RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( + state, + common_enums::EventClass::Payments, + event_status, + payment_intent, + &merchant_context, + profile, + payment_data.payment_attempt.id.get_string_repr().to_string(), + payments_response + ) + .await?; Ok(Self::SuccessfulPayment( payment_data.payment_attempt.clone(), @@ -541,14 +609,15 @@ impl Action { .await; // Reopen calculate workflow on payment failure - reopen_calculate_workflow_on_payment_failure( + Box::pin(reopen_calculate_workflow_on_payment_failure( state, process, profile, merchant_context, payment_intent, revenue_recovery_payment_data, - ) + latest_attempt_id, + )) .await?; // Return terminal failure to finish the current execute workflow @@ -576,6 +645,8 @@ impl Action { state, payment_intent.get_id(), revenue_recovery_payment_data, + true, + true, ) .await; @@ -690,36 +761,6 @@ impl Action { Ok(()) } Self::TerminalFailure(payment_attempt) => { - // update the connector payment transmission field to Unsuccessful and unset active attempt id - revenue_recovery_metadata.set_payment_transmission_field_for_api_request( - enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, - ); - - let payment_update_req = - PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( - payment_intent - .feature_metadata - .clone() - .unwrap_or_default() - .convert_back() - .set_payment_revenue_recovery_metadata_using_api( - revenue_recovery_metadata.clone(), - ), - api_enums::UpdateActiveAttempt::Unset, - ); - logger::info!( - "Call made to payments update intent api , with the request body {:?}", - payment_update_req - ); - revenue_recovery_core::api::update_payment_intent_api( - state, - payment_intent.id.clone(), - revenue_recovery_payment_data, - payment_update_req, - ) - .await - .change_context(errors::RecoveryError::PaymentCallFailed)?; - db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), @@ -794,6 +835,8 @@ impl Action { state, payment_intent.get_id(), revenue_recovery_payment_data, + true, + true, ) .await; let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt); @@ -856,14 +899,15 @@ impl Action { .await; // Reopen calculate workflow on payment failure - reopen_calculate_workflow_on_payment_failure( + Box::pin(reopen_calculate_workflow_on_payment_failure( state, process, profile, merchant_context, payment_intent, revenue_recovery_payment_data, - ) + payment_attempt.get_id(), + )) .await?; Ok(Self::TerminalFailure(payment_attempt.clone())) @@ -937,37 +981,6 @@ impl Action { .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; - // update the connector payment transmission field to Unsuccessful and unset active attempt id - revenue_recovery_metadata.set_payment_transmission_field_for_api_request( - enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, - ); - - let payment_update_req = - PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( - payment_intent - .feature_metadata - .clone() - .unwrap_or_default() - .convert_back() - .set_payment_revenue_recovery_metadata_using_api( - revenue_recovery_metadata.clone(), - ), - api_enums::UpdateActiveAttempt::Unset, - ); - logger::info!( - "Call made to payments update intent api , with the request body {:?}", - payment_update_req - ); - - revenue_recovery_core::api::update_payment_intent_api( - state, - payment_intent.id.clone(), - revenue_recovery_payment_data, - payment_update_req, - ) - .await - .change_context(errors::RecoveryError::PaymentCallFailed)?; - // fetch the execute task let task = revenue_recovery_core::EXECUTE_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; @@ -990,37 +1003,6 @@ impl Action { } Self::TerminalFailure(payment_attempt) => { - // update the connector payment transmission field to Unsuccessful and unset active attempt id - revenue_recovery_metadata.set_payment_transmission_field_for_api_request( - enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, - ); - - let payment_update_req = - PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( - payment_intent - .feature_metadata - .clone() - .unwrap_or_default() - .convert_back() - .set_payment_revenue_recovery_metadata_using_api( - revenue_recovery_metadata.clone(), - ), - api_enums::UpdateActiveAttempt::Unset, - ); - logger::info!( - "Call made to payments update intent api , with the request body {:?}", - payment_update_req - ); - - revenue_recovery_core::api::update_payment_intent_api( - state, - payment_intent.id.clone(), - revenue_recovery_payment_data, - payment_update_req, - ) - .await - .change_context(errors::RecoveryError::PaymentCallFailed)?; - // TODO: Add support for retrying failed outgoing recordback webhooks // finish the current psync task db.as_scheduler() @@ -1150,12 +1132,27 @@ pub async fn reopen_calculate_workflow_on_payment_failure( merchant_context: domain::MerchantContext, payment_intent: &PaymentIntent, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, + latest_attempt_id: &id_type::GlobalAttemptId, ) -> RecoveryResult<()> { let db = &*state.store; let id = payment_intent.id.clone(); let task = revenue_recovery_core::CALCULATE_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; + let old_tracking_data: pcr::RevenueRecoveryWorkflowTrackingData = + serde_json::from_value(process.tracking_data.clone()) + .change_context(errors::RecoveryError::ValueNotFound) + .attach_printable("Failed to deserialize the tracking data from process tracker")?; + + let new_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { + payment_attempt_id: latest_attempt_id.clone(), + ..old_tracking_data + }; + + let tracking_data = serde_json::to_value(new_tracking_data) + .change_context(errors::RecoveryError::ValueNotFound) + .attach_printable("Failed to serialize the tracking data for process tracker")?; + // Construct the process tracker ID for CALCULATE_WORKFLOW let process_tracker_id = format!("{}_{}_{}", runner, task, id.get_string_repr()); @@ -1201,7 +1198,7 @@ pub async fn reopen_calculate_workflow_on_payment_failure( name: Some(task.to_string()), retry_count: Some(new_retry_count), schedule_time: Some(new_schedule_time), - tracking_data: Some(process.clone().tracking_data), + tracking_data: Some(tracking_data), business_status: Some(String::from(business_status::PENDING)), status: Some(common_enums::ProcessTrackerStatus::Pending), updated_at: Some(common_utils::date_time::now()), @@ -1301,7 +1298,7 @@ pub async fn reopen_calculate_workflow_on_payment_failure( .attach_printable("Failed to deserialize the tracking data from process tracker")?; // Call the existing perform_calculate_workflow function - perform_calculate_workflow( + Box::pin(perform_calculate_workflow( state, process, profile, @@ -1309,7 +1306,7 @@ pub async fn reopen_calculate_workflow_on_payment_failure( &tracking_data, revenue_recovery_payment_data, payment_intent, - ) + )) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to perform calculate workflow")?; @@ -1476,3 +1473,50 @@ pub fn get_payment_processor_token_id_from_payment_attempt( used_token } + +pub struct RevenueRecoveryOutgoingWebhook; + +impl RevenueRecoveryOutgoingWebhook { + #[allow(clippy::too_many_arguments)] + pub async fn send_outgoing_webhook_based_on_revenue_recovery_status( + state: &SessionState, + event_class: common_enums::EventClass, + event_status: common_enums::EventType, + payment_intent: &PaymentIntent, + merchant_context: &domain::MerchantContext, + profile: &domain::Profile, + payment_attempt_id: String, + payments_response: ApplicationResponse<api_models::payments::PaymentsResponse>, + ) -> RecoveryResult<()> { + match payments_response { + ApplicationResponse::JsonWithHeaders((response, _headers)) => { + let outgoing_webhook_content = + api_models::webhooks::OutgoingWebhookContent::PaymentDetails(Box::new( + response, + )); + create_event_and_trigger_outgoing_webhook( + state.clone(), + profile.clone(), + merchant_context.get_merchant_key_store(), + event_status, + event_class, + payment_attempt_id, + enums::EventObjectType::PaymentDetails, + outgoing_webhook_content, + payment_intent.created_at, + ) + .await + .change_context(errors::RecoveryError::InvalidTask) + .attach_printable("Failed to send out going webhook")?; + + Ok(()) + } + + _other_variant => { + // Handle other successful response types if needed + logger::warn!("Unexpected application response variant for outgoing webhook"); + Err(errors::RecoveryError::RevenueRecoveryOutgoingWebhookFailed.into()) + } + } + } +} diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index 48110eb92ed..4cde3bd99f8 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -7,7 +7,7 @@ use external_services::grpc_client::{self as external_grpc_client, GrpcHeaders}; use hyperswitch_domain_models::{ business_profile, merchant_account, merchant_connector_account, merchant_key_store, payment_method_data::{Card, PaymentMethodData}, - payments::{payment_attempt::PaymentAttempt, PaymentIntent}, + payments::{payment_attempt::PaymentAttempt, PaymentIntent, PaymentStatusData}, }; use masking::PeekInterface; use router_env::logger; @@ -32,6 +32,7 @@ pub struct RevenueRecoveryPaymentData { pub key_store: merchant_key_store::MerchantKeyStore, pub billing_mca: merchant_connector_account::MerchantConnectorAccount, pub retry_algorithm: enums::RevenueRecoveryAlgorithmType, + pub psync_data: Option<PaymentStatusData<types::api::PSync>>, } impl RevenueRecoveryPaymentData { pub async fn get_schedule_time_based_on_retry_type( diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index 6a6d9511062..e87b26e4c15 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -232,6 +232,7 @@ pub(crate) async fn extract_data_and_perform_action( retry_algorithm: profile .revenue_recovery_retry_algorithm_type .unwrap_or(tracking_data.revenue_recovery_retry), + psync_data: None, }; Ok(pcr_payment_data) } diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index a2b4dad779b..3aade73383c 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -288,6 +288,10 @@ pub enum RecoveryError { RecordBackToBillingConnectorFailed, #[error("Failed to fetch billing connector account id")] BillingMerchantConnectorAccountIdNotFound, + #[error("Failed to generate payment sync data")] + PaymentsResponseGenerationFailed, + #[error("Outgoing Webhook Failed")] + RevenueRecoveryOutgoingWebhookFailed, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckDecisionEngineError {
2025-09-07T20:28:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR enables outgoing webhook support for revenue recovery. When the retries get succeeded that are done using the revenue recovery system, an outgoing webhook needs to be triggered to the url in business profile. This pr adds that support. ### 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. PaymentResponse -> added modified at in api_models 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? 1. create a billing profile with webhook.site url to monitor the webhooks. 2. Create an payment mca using this ``` curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: {{merchant-id}}' --header 'x-profile-id: {{profile-id}}' \ --header 'Authorization: {{api-key}}' --header 'api-key:{{api-key}}' \ --data '{ "connector_type": "payment_processor", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "{{api_key}}" }, "payment_methods_enabled": [ { "payment_method_type": "card", "payment_method_subtypes": [ { "payment_method_subtype": "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_subtype": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_subtype": "card", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "frm_configs": null, "connector_webhook_details": { "merchant_secret": "" }, "metadata": { "report_group": "Hello", "merchant_config_currency": "USD" }, "profile_id": "{{profile_id}}" }' ``` 3. create an billing mca ``` curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: {{merchant-id}}' --header 'x-profile-id: {{profile-id}}' \ --header 'Authorization: {{api-key}}' --header 'api-key:{{api-key}}' \ --data '{ "connector_type": "billing_processor", "connector_name": "custombilling", "connector_account_details": { "auth_type": "NoKey" }, "feature_metadata" : { "revenue_recovery" : { "max_retry_count" : 9, "billing_connector_retry_threshold" : 0, "billing_account_reference" :{ "{{payment_mca}}" : "{{payment_mca}}" }, "switch_payment_method_config" : { "retry_threshold" : 0, "time_threshold_after_creation": 0 } } }, "profile_id": "{{profile_id}}" }' ``` 4. switch revenue recovery config to cascading ``` curl --location --request PUT 'http://localhost:8080/v2/profiles/pro_DD6ZRORqBtEwR3ITjseM' \ --header 'x-merchant-id: {{erchant-id}}' \ --header 'Authorization: {{api-key}}' \ --header 'Content-Type: application/json' \ --header 'api-key: {{api-key}}' \ --data '{ "revenue_recovery_retry_algorithm_type": "cascading" } ' ``` 5. Go to stripe dashboard and create a customer and attach a card for that customer 6. Hit this recovery api with that customer_id and payment_method_id ``` curl --location 'http://localhost:8080/v2/payments/recovery' \ --header 'Authorization: {{api-key}}' --header 'x-profile-id: {{profile-id}} --header 'x-merchant-id: {{merchant-id}}' --header 'Content-Type: application/json' \ --header 'api-key:{{api_key}}' \ --data '{ "amount_details": { "order_amount": 2250, "currency": "USD" }, "merchant_reference_id": "test_ffhgfewf3476f5", "connector_transaction_id": "1831984", "connector_customer_id": "{{customer_id_from_stripe}}", "error": { "code": "110", "message": "Insufficient Funds" }, "billing": { "address": { "state": "CA", "country": "US" } }, "payment_method_type": "card", "payment_method_sub_type": "credit", "payment_method_data": { "primary_processor_payment_method_token": "{{payment_method_id_from_stripe}}", "additional_payment_method_info": { "card_exp_month": "12", "card_exp_year": "25", "last_four_digits": 1997, "card_network": "Visa", "card_issuer": "Wells Fargo NA", "card_type": "credit" } }, "billing_started_at": "2024-05-29T08:10:58Z", "transaction_created_at": "2024-05-29T08:10:58Z", "attempt_status": "failure", "action": "schedule_failed_payment", "billing_merchant_connector_id": "{{billing_mca}} "payment_merchant_connector_id": "{{payment_mca}}" }' ``` 7. There will be a process tracker entry now and wait till it get triggered. Based on the test card if we mentioned a successful card's payment method id then we will get a webhook to webhook.site url. Sample screen shot and sample webhook body are mentioned below <img width="1727" height="951" alt="Screenshot 2025-09-08 at 1 55 58 AM" src="https://github.com/user-attachments/assets/77c67c1b-ba07-4d48-8109-be0de40837d6" /> Sample body of the webhook ``` { "merchant_id": "cloth_seller_I7nS4iwZnxRDJtGfiNTy", "event_id": "evt_019925c838c877c282d3eaf5b86e9036", "event_type": "payment_succeeded", "content": { "type": "payment_details", "object": { "id": "12345_pay_019925c5959a79418301a9460b92edb1", "status": "succeeded", "amount": { "order_amount": 2250, "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": 2250, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 2250 }, "customer_id": null, "connector": "stripe", "created": "2025-09-07T20:02:09.947Z", "modified_at": "2025-09-07T20:05:02.777Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "pi_3S4opd2KXBHSNjod0tD34Dmw", "connector_reference_id": "pi_3S4opd2KXBHSNjod0tD34Dmw", "merchant_connector_id": "mca_MbQwWzi4tFItmgYAmshC", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1S4olu2KXBHSNjodBbiedqY9", "connector_token_request_reference_id": 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": "test_ffhgfewf3476f5", "raw_connector_response": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "revenue_recovery": { "total_retry_count": 2, "payment_connector_transmission": "ConnectorCallSucceeded", "billing_connector_id": "mca_ppEVMjRWgTiGyCiwFtg9", "active_attempt_payment_connector_id": "mca_MbQwWzi4tFItmgYAmshC", "billing_connector_payment_details": { "payment_processor_token": "pm_1S4olu2KXBHSNjodBbiedqY9", "connector_customer_id": "cus_T0qSE723C5Xxic" }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector": "stripe", "billing_connector_payment_method_details": { "type": "card", "value": { "card_network": "Visa", "card_issuer": "Wells Fargo NA" } }, "invoice_next_billing_time": null, "invoice_billing_started_at_time": null, "first_payment_attempt_pg_error_code": "resource_missing", "first_payment_attempt_network_decline_code": null, "first_payment_attempt_network_advice_code": null } } } }, "timestamp": "2025-09-07T20:05:02.792Z" } ``` ## 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
v1.116.0
cadfcf7c22bfd1124f19e2f1cc1c98c3d152be99
cadfcf7c22bfd1124f19e2f1cc1c98c3d152be99
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
v1.116.0
641cd8d2a20c93e0ec7e20d362451c345fd6ad3e
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
v1.116.0
0eaea06a73d5209d8fa5688ec544af0883b787a2
0eaea06a73d5209d8fa5688ec544af0883b787a2
juspay/hyperswitch
juspay__hyperswitch-9288
Bug: Updated openapi spec to include labels to wallet data Updated openapi spec to include labels to wallet data
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 6c2fedbf684..b1004f4c933 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -32828,39 +32828,43 @@ "oneOf": [ { "type": "object", + "title": "AliPayHkRedirect", "required": [ - "ali_pay_qr" + "ali_pay_hk_redirect" ], "properties": { - "ali_pay_qr": { - "$ref": "#/components/schemas/AliPayQr" + "ali_pay_hk_redirect": { + "$ref": "#/components/schemas/AliPayHkRedirection" } } }, { "type": "object", + "title": "AliPayQr", "required": [ - "ali_pay_redirect" + "ali_pay_qr" ], "properties": { - "ali_pay_redirect": { - "$ref": "#/components/schemas/AliPayRedirection" + "ali_pay_qr": { + "$ref": "#/components/schemas/AliPayQr" } } }, { "type": "object", + "title": "AliPayRedirect", "required": [ - "ali_pay_hk_redirect" + "ali_pay_redirect" ], "properties": { - "ali_pay_hk_redirect": { - "$ref": "#/components/schemas/AliPayHkRedirection" + "ali_pay_redirect": { + "$ref": "#/components/schemas/AliPayRedirection" } } }, { "type": "object", + "title": "AmazonPay", "required": [ "amazon_pay" ], @@ -32872,6 +32876,7 @@ }, { "type": "object", + "title": "AmazonPayRedirect", "required": [ "amazon_pay_redirect" ], @@ -32883,73 +32888,81 @@ }, { "type": "object", + "title": "ApplePay", "required": [ - "bluecode_redirect" + "apple_pay" ], "properties": { - "bluecode_redirect": { - "type": "object", - "description": "The wallet data for Bluecode QR Code Redirect" + "apple_pay": { + "$ref": "#/components/schemas/ApplePayWalletData" } } }, { "type": "object", + "title": "ApplePayRedirect", "required": [ - "skrill" + "apple_pay_redirect" ], "properties": { - "skrill": { - "$ref": "#/components/schemas/SkrillData" + "apple_pay_redirect": { + "$ref": "#/components/schemas/ApplePayRedirectData" } } }, { "type": "object", + "title": "ApplePayThirdPartySdk", "required": [ - "paysera" + "apple_pay_third_party_sdk" ], "properties": { - "paysera": { - "$ref": "#/components/schemas/PayseraData" + "apple_pay_third_party_sdk": { + "$ref": "#/components/schemas/ApplePayThirdPartySdkData" } } }, { "type": "object", + "title": "BluecodeRedirect", "required": [ - "momo_redirect" + "bluecode_redirect" ], "properties": { - "momo_redirect": { - "$ref": "#/components/schemas/MomoRedirection" + "bluecode_redirect": { + "type": "object", + "description": "The wallet data for Bluecode QR Code Redirect" } } }, { "type": "object", + "title": "CashappQr", "required": [ - "kakao_pay_redirect" + "cashapp_qr" ], "properties": { - "kakao_pay_redirect": { - "$ref": "#/components/schemas/KakaoPayRedirection" + "cashapp_qr": { + "$ref": "#/components/schemas/CashappQr" } } }, { "type": "object", + "title": "DanaRedirect", "required": [ - "go_pay_redirect" + "dana_redirect" ], "properties": { - "go_pay_redirect": { - "$ref": "#/components/schemas/GoPayRedirection" + "dana_redirect": { + "type": "object", + "description": "Wallet data for DANA redirect flow" } } }, { "type": "object", + "title": "GcashRedirect", "required": [ "gcash_redirect" ], @@ -32961,106 +32974,115 @@ }, { "type": "object", + "title": "GoPayRedirect", "required": [ - "apple_pay" + "go_pay_redirect" ], "properties": { - "apple_pay": { - "$ref": "#/components/schemas/ApplePayWalletData" + "go_pay_redirect": { + "$ref": "#/components/schemas/GoPayRedirection" } } }, { "type": "object", + "title": "GooglePay", "required": [ - "apple_pay_redirect" + "google_pay" ], "properties": { - "apple_pay_redirect": { - "$ref": "#/components/schemas/ApplePayRedirectData" + "google_pay": { + "$ref": "#/components/schemas/GooglePayWalletData" } } }, { "type": "object", + "title": "GooglePayRedirect", "required": [ - "apple_pay_third_party_sdk" + "google_pay_redirect" ], "properties": { - "apple_pay_third_party_sdk": { - "$ref": "#/components/schemas/ApplePayThirdPartySdkData" + "google_pay_redirect": { + "$ref": "#/components/schemas/GooglePayRedirectData" } } }, { "type": "object", + "title": "GooglePayThirdPartySdk", "required": [ - "dana_redirect" + "google_pay_third_party_sdk" ], "properties": { - "dana_redirect": { - "type": "object", - "description": "Wallet data for DANA redirect flow" + "google_pay_third_party_sdk": { + "$ref": "#/components/schemas/GooglePayThirdPartySdkData" } } }, { "type": "object", + "title": "KakaoPayRedirect", "required": [ - "google_pay" + "kakao_pay_redirect" ], "properties": { - "google_pay": { - "$ref": "#/components/schemas/GooglePayWalletData" + "kakao_pay_redirect": { + "$ref": "#/components/schemas/KakaoPayRedirection" } } }, { "type": "object", + "title": "MbWayRedirect", "required": [ - "google_pay_redirect" + "mb_way_redirect" ], "properties": { - "google_pay_redirect": { - "$ref": "#/components/schemas/GooglePayRedirectData" + "mb_way_redirect": { + "$ref": "#/components/schemas/MbWayRedirection" } } }, { "type": "object", + "title": "Mifinity", "required": [ - "google_pay_third_party_sdk" + "mifinity" ], "properties": { - "google_pay_third_party_sdk": { - "$ref": "#/components/schemas/GooglePayThirdPartySdkData" + "mifinity": { + "$ref": "#/components/schemas/MifinityData" } } }, { "type": "object", + "title": "MobilePayRedirect", "required": [ - "mb_way_redirect" + "mobile_pay_redirect" ], "properties": { - "mb_way_redirect": { - "$ref": "#/components/schemas/MbWayRedirection" + "mobile_pay_redirect": { + "$ref": "#/components/schemas/MobilePayRedirection" } } }, { "type": "object", + "title": "MomoRedirect", "required": [ - "mobile_pay_redirect" + "momo_redirect" ], "properties": { - "mobile_pay_redirect": { - "$ref": "#/components/schemas/MobilePayRedirection" + "momo_redirect": { + "$ref": "#/components/schemas/MomoRedirection" } } }, { "type": "object", + "title": "PaypalRedirect", "required": [ "paypal_redirect" ], @@ -33072,6 +33094,7 @@ }, { "type": "object", + "title": "PaypalSdk", "required": [ "paypal_sdk" ], @@ -33083,124 +33106,135 @@ }, { "type": "object", + "title": "Paysera", "required": [ - "paze" + "paysera" ], "properties": { - "paze": { - "$ref": "#/components/schemas/PazeWalletData" + "paysera": { + "$ref": "#/components/schemas/PayseraData" } } }, { "type": "object", + "title": "Paze", "required": [ - "samsung_pay" + "paze" ], "properties": { - "samsung_pay": { - "$ref": "#/components/schemas/SamsungPayWalletData" + "paze": { + "$ref": "#/components/schemas/PazeWalletData" } } }, { "type": "object", + "title": "RevolutPay", "required": [ - "twint_redirect" + "revolut_pay" ], "properties": { - "twint_redirect": { - "type": "object", - "description": "Wallet data for Twint Redirection" + "revolut_pay": { + "$ref": "#/components/schemas/RevolutPayData" } } }, { "type": "object", + "title": "SamsungPay", "required": [ - "vipps_redirect" + "samsung_pay" ], "properties": { - "vipps_redirect": { - "type": "object", - "description": "Wallet data for Vipps Redirection" + "samsung_pay": { + "$ref": "#/components/schemas/SamsungPayWalletData" } } }, { "type": "object", + "title": "Skrill", "required": [ - "touch_n_go_redirect" + "skrill" ], "properties": { - "touch_n_go_redirect": { - "$ref": "#/components/schemas/TouchNGoRedirection" + "skrill": { + "$ref": "#/components/schemas/SkrillData" } } }, { "type": "object", + "title": "SwishQr", "required": [ - "we_chat_pay_redirect" + "swish_qr" ], "properties": { - "we_chat_pay_redirect": { - "$ref": "#/components/schemas/WeChatPayRedirection" + "swish_qr": { + "$ref": "#/components/schemas/SwishQrData" } } }, { "type": "object", + "title": "TouchNGoRedirect", "required": [ - "we_chat_pay_qr" + "touch_n_go_redirect" ], "properties": { - "we_chat_pay_qr": { - "$ref": "#/components/schemas/WeChatPayQr" + "touch_n_go_redirect": { + "$ref": "#/components/schemas/TouchNGoRedirection" } } }, { "type": "object", + "title": "TwintRedirect", "required": [ - "cashapp_qr" + "twint_redirect" ], "properties": { - "cashapp_qr": { - "$ref": "#/components/schemas/CashappQr" + "twint_redirect": { + "type": "object", + "description": "Wallet data for Twint Redirection" } } }, { "type": "object", + "title": "VippsRedirect", "required": [ - "swish_qr" + "vipps_redirect" ], "properties": { - "swish_qr": { - "$ref": "#/components/schemas/SwishQrData" + "vipps_redirect": { + "type": "object", + "description": "Wallet data for Vipps Redirection" } } }, { "type": "object", + "title": "WeChatPayQr", "required": [ - "mifinity" + "we_chat_pay_qr" ], "properties": { - "mifinity": { - "$ref": "#/components/schemas/MifinityData" + "we_chat_pay_qr": { + "$ref": "#/components/schemas/WeChatPayQr" } } }, { "type": "object", + "title": "WeChatPayRedirect", "required": [ - "revolut_pay" + "we_chat_pay_redirect" ], "properties": { - "revolut_pay": { - "$ref": "#/components/schemas/RevolutPayData" + "we_chat_pay_redirect": { + "$ref": "#/components/schemas/WeChatPayRedirection" } } } diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 8a103d92a82..e324240a1ad 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -26404,39 +26404,43 @@ "oneOf": [ { "type": "object", + "title": "AliPayHkRedirect", "required": [ - "ali_pay_qr" + "ali_pay_hk_redirect" ], "properties": { - "ali_pay_qr": { - "$ref": "#/components/schemas/AliPayQr" + "ali_pay_hk_redirect": { + "$ref": "#/components/schemas/AliPayHkRedirection" } } }, { "type": "object", + "title": "AliPayQr", "required": [ - "ali_pay_redirect" + "ali_pay_qr" ], "properties": { - "ali_pay_redirect": { - "$ref": "#/components/schemas/AliPayRedirection" + "ali_pay_qr": { + "$ref": "#/components/schemas/AliPayQr" } } }, { "type": "object", + "title": "AliPayRedirect", "required": [ - "ali_pay_hk_redirect" + "ali_pay_redirect" ], "properties": { - "ali_pay_hk_redirect": { - "$ref": "#/components/schemas/AliPayHkRedirection" + "ali_pay_redirect": { + "$ref": "#/components/schemas/AliPayRedirection" } } }, { "type": "object", + "title": "AmazonPay", "required": [ "amazon_pay" ], @@ -26448,6 +26452,7 @@ }, { "type": "object", + "title": "AmazonPayRedirect", "required": [ "amazon_pay_redirect" ], @@ -26459,73 +26464,81 @@ }, { "type": "object", + "title": "ApplePay", "required": [ - "bluecode_redirect" + "apple_pay" ], "properties": { - "bluecode_redirect": { - "type": "object", - "description": "The wallet data for Bluecode QR Code Redirect" + "apple_pay": { + "$ref": "#/components/schemas/ApplePayWalletData" } } }, { "type": "object", + "title": "ApplePayRedirect", "required": [ - "skrill" + "apple_pay_redirect" ], "properties": { - "skrill": { - "$ref": "#/components/schemas/SkrillData" + "apple_pay_redirect": { + "$ref": "#/components/schemas/ApplePayRedirectData" } } }, { "type": "object", + "title": "ApplePayThirdPartySdk", "required": [ - "paysera" + "apple_pay_third_party_sdk" ], "properties": { - "paysera": { - "$ref": "#/components/schemas/PayseraData" + "apple_pay_third_party_sdk": { + "$ref": "#/components/schemas/ApplePayThirdPartySdkData" } } }, { "type": "object", + "title": "BluecodeRedirect", "required": [ - "momo_redirect" + "bluecode_redirect" ], "properties": { - "momo_redirect": { - "$ref": "#/components/schemas/MomoRedirection" + "bluecode_redirect": { + "type": "object", + "description": "The wallet data for Bluecode QR Code Redirect" } } }, { "type": "object", + "title": "CashappQr", "required": [ - "kakao_pay_redirect" + "cashapp_qr" ], "properties": { - "kakao_pay_redirect": { - "$ref": "#/components/schemas/KakaoPayRedirection" + "cashapp_qr": { + "$ref": "#/components/schemas/CashappQr" } } }, { "type": "object", + "title": "DanaRedirect", "required": [ - "go_pay_redirect" + "dana_redirect" ], "properties": { - "go_pay_redirect": { - "$ref": "#/components/schemas/GoPayRedirection" + "dana_redirect": { + "type": "object", + "description": "Wallet data for DANA redirect flow" } } }, { "type": "object", + "title": "GcashRedirect", "required": [ "gcash_redirect" ], @@ -26537,106 +26550,115 @@ }, { "type": "object", + "title": "GoPayRedirect", "required": [ - "apple_pay" + "go_pay_redirect" ], "properties": { - "apple_pay": { - "$ref": "#/components/schemas/ApplePayWalletData" + "go_pay_redirect": { + "$ref": "#/components/schemas/GoPayRedirection" } } }, { "type": "object", + "title": "GooglePay", "required": [ - "apple_pay_redirect" + "google_pay" ], "properties": { - "apple_pay_redirect": { - "$ref": "#/components/schemas/ApplePayRedirectData" + "google_pay": { + "$ref": "#/components/schemas/GooglePayWalletData" } } }, { "type": "object", + "title": "GooglePayRedirect", "required": [ - "apple_pay_third_party_sdk" + "google_pay_redirect" ], "properties": { - "apple_pay_third_party_sdk": { - "$ref": "#/components/schemas/ApplePayThirdPartySdkData" + "google_pay_redirect": { + "$ref": "#/components/schemas/GooglePayRedirectData" } } }, { "type": "object", + "title": "GooglePayThirdPartySdk", "required": [ - "dana_redirect" + "google_pay_third_party_sdk" ], "properties": { - "dana_redirect": { - "type": "object", - "description": "Wallet data for DANA redirect flow" + "google_pay_third_party_sdk": { + "$ref": "#/components/schemas/GooglePayThirdPartySdkData" } } }, { "type": "object", + "title": "KakaoPayRedirect", "required": [ - "google_pay" + "kakao_pay_redirect" ], "properties": { - "google_pay": { - "$ref": "#/components/schemas/GooglePayWalletData" + "kakao_pay_redirect": { + "$ref": "#/components/schemas/KakaoPayRedirection" } } }, { "type": "object", + "title": "MbWayRedirect", "required": [ - "google_pay_redirect" + "mb_way_redirect" ], "properties": { - "google_pay_redirect": { - "$ref": "#/components/schemas/GooglePayRedirectData" + "mb_way_redirect": { + "$ref": "#/components/schemas/MbWayRedirection" } } }, { "type": "object", + "title": "Mifinity", "required": [ - "google_pay_third_party_sdk" + "mifinity" ], "properties": { - "google_pay_third_party_sdk": { - "$ref": "#/components/schemas/GooglePayThirdPartySdkData" + "mifinity": { + "$ref": "#/components/schemas/MifinityData" } } }, { "type": "object", + "title": "MobilePayRedirect", "required": [ - "mb_way_redirect" + "mobile_pay_redirect" ], "properties": { - "mb_way_redirect": { - "$ref": "#/components/schemas/MbWayRedirection" + "mobile_pay_redirect": { + "$ref": "#/components/schemas/MobilePayRedirection" } } }, { "type": "object", + "title": "MomoRedirect", "required": [ - "mobile_pay_redirect" + "momo_redirect" ], "properties": { - "mobile_pay_redirect": { - "$ref": "#/components/schemas/MobilePayRedirection" + "momo_redirect": { + "$ref": "#/components/schemas/MomoRedirection" } } }, { "type": "object", + "title": "PaypalRedirect", "required": [ "paypal_redirect" ], @@ -26648,6 +26670,7 @@ }, { "type": "object", + "title": "PaypalSdk", "required": [ "paypal_sdk" ], @@ -26659,124 +26682,135 @@ }, { "type": "object", + "title": "Paysera", "required": [ - "paze" + "paysera" ], "properties": { - "paze": { - "$ref": "#/components/schemas/PazeWalletData" + "paysera": { + "$ref": "#/components/schemas/PayseraData" } } }, { "type": "object", + "title": "Paze", "required": [ - "samsung_pay" + "paze" ], "properties": { - "samsung_pay": { - "$ref": "#/components/schemas/SamsungPayWalletData" + "paze": { + "$ref": "#/components/schemas/PazeWalletData" } } }, { "type": "object", + "title": "RevolutPay", "required": [ - "twint_redirect" + "revolut_pay" ], "properties": { - "twint_redirect": { - "type": "object", - "description": "Wallet data for Twint Redirection" + "revolut_pay": { + "$ref": "#/components/schemas/RevolutPayData" } } }, { "type": "object", + "title": "SamsungPay", "required": [ - "vipps_redirect" + "samsung_pay" ], "properties": { - "vipps_redirect": { - "type": "object", - "description": "Wallet data for Vipps Redirection" + "samsung_pay": { + "$ref": "#/components/schemas/SamsungPayWalletData" } } }, { "type": "object", + "title": "Skrill", "required": [ - "touch_n_go_redirect" + "skrill" ], "properties": { - "touch_n_go_redirect": { - "$ref": "#/components/schemas/TouchNGoRedirection" + "skrill": { + "$ref": "#/components/schemas/SkrillData" } } }, { "type": "object", + "title": "SwishQr", "required": [ - "we_chat_pay_redirect" + "swish_qr" ], "properties": { - "we_chat_pay_redirect": { - "$ref": "#/components/schemas/WeChatPayRedirection" + "swish_qr": { + "$ref": "#/components/schemas/SwishQrData" } } }, { "type": "object", + "title": "TouchNGoRedirect", "required": [ - "we_chat_pay_qr" + "touch_n_go_redirect" ], "properties": { - "we_chat_pay_qr": { - "$ref": "#/components/schemas/WeChatPayQr" + "touch_n_go_redirect": { + "$ref": "#/components/schemas/TouchNGoRedirection" } } }, { "type": "object", + "title": "TwintRedirect", "required": [ - "cashapp_qr" + "twint_redirect" ], "properties": { - "cashapp_qr": { - "$ref": "#/components/schemas/CashappQr" + "twint_redirect": { + "type": "object", + "description": "Wallet data for Twint Redirection" } } }, { "type": "object", + "title": "VippsRedirect", "required": [ - "swish_qr" + "vipps_redirect" ], "properties": { - "swish_qr": { - "$ref": "#/components/schemas/SwishQrData" + "vipps_redirect": { + "type": "object", + "description": "Wallet data for Vipps Redirection" } } }, { "type": "object", + "title": "WeChatPayQr", "required": [ - "mifinity" + "we_chat_pay_qr" ], "properties": { - "mifinity": { - "$ref": "#/components/schemas/MifinityData" + "we_chat_pay_qr": { + "$ref": "#/components/schemas/WeChatPayQr" } } }, { "type": "object", + "title": "WeChatPayRedirect", "required": [ - "revolut_pay" + "we_chat_pay_redirect" ], "properties": { - "revolut_pay": { - "$ref": "#/components/schemas/RevolutPayData" + "we_chat_pay_redirect": { + "$ref": "#/components/schemas/WeChatPayRedirection" } } } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 34a8beee16f..7f0c797a151 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3816,73 +3816,108 @@ impl GetAddressFromPaymentMethodData for BankDebitBilling { #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { + /// The wallet data for Ali Pay HK redirect + #[schema(title = "AliPayHkRedirect")] + AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Ali Pay QrCode + #[schema(title = "AliPayQr")] AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect + #[schema(title = "AliPayRedirect")] AliPayRedirect(AliPayRedirection), - /// The wallet data for Ali Pay HK redirect - AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay + #[schema(title = "AmazonPay")] AmazonPay(AmazonPayWalletData), /// The wallet data for Amazon Pay redirect + #[schema(title = "AmazonPayRedirect")] AmazonPayRedirect(AmazonPayRedirectData), - /// The wallet data for Bluecode QR Code Redirect - BluecodeRedirect {}, - /// The wallet data for Skrill - Skrill(SkrillData), - /// The wallet data for Paysera - Paysera(PayseraData), - /// The wallet data for Momo redirect - MomoRedirect(MomoRedirection), - /// The wallet data for KakaoPay redirect - KakaoPayRedirect(KakaoPayRedirection), - /// The wallet data for GoPay redirect - GoPayRedirect(GoPayRedirection), - /// The wallet data for Gcash redirect - GcashRedirect(GcashRedirection), /// The wallet data for Apple pay + #[schema(title = "ApplePay")] ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow + #[schema(title = "ApplePayRedirect")] ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow + #[schema(title = "ApplePayThirdPartySdk")] ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), + /// The wallet data for Bluecode QR Code Redirect + #[schema(title = "BluecodeRedirect")] + BluecodeRedirect {}, + /// The wallet data for Cashapp Qr + #[schema(title = "CashappQr")] + CashappQr(Box<CashappQr>), /// Wallet data for DANA redirect flow + #[schema(title = "DanaRedirect")] DanaRedirect {}, + /// The wallet data for Gcash redirect + #[schema(title = "GcashRedirect")] + GcashRedirect(GcashRedirection), + /// The wallet data for GoPay redirect + #[schema(title = "GoPayRedirect")] + GoPayRedirect(GoPayRedirection), /// The wallet data for Google pay + #[schema(title = "GooglePay")] GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow + #[schema(title = "GooglePayRedirect")] GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow + #[schema(title = "GooglePayThirdPartySdk")] GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), + /// The wallet data for KakaoPay redirect + #[schema(title = "KakaoPayRedirect")] + KakaoPayRedirect(KakaoPayRedirection), + /// Wallet data for MbWay redirect flow + #[schema(title = "MbWayRedirect")] MbWayRedirect(Box<MbWayRedirection>), + // The wallet data for Mifinity Ewallet + #[schema(title = "Mifinity")] + Mifinity(MifinityData), /// The wallet data for MobilePay redirect + #[schema(title = "MobilePayRedirect")] MobilePayRedirect(Box<MobilePayRedirection>), + /// The wallet data for Momo redirect + #[schema(title = "MomoRedirect")] + MomoRedirect(MomoRedirection), /// This is for paypal redirection + #[schema(title = "PaypalRedirect")] PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal + #[schema(title = "PaypalSdk")] PaypalSdk(PayPalWalletData), + /// The wallet data for Paysera + #[schema(title = "Paysera")] + Paysera(PayseraData), /// The wallet data for Paze + #[schema(title = "Paze")] Paze(PazeWalletData), + // The wallet data for RevolutPay + #[schema(title = "RevolutPay")] + RevolutPay(RevolutPayData), /// The wallet data for Samsung Pay + #[schema(title = "SamsungPay")] SamsungPay(Box<SamsungPayWalletData>), + /// The wallet data for Skrill + #[schema(title = "Skrill")] + Skrill(SkrillData), + // The wallet data for Swish + #[schema(title = "SwishQr")] + SwishQr(SwishQrData), + /// The wallet data for Touch n Go Redirection + #[schema(title = "TouchNGoRedirect")] + TouchNGoRedirect(Box<TouchNGoRedirection>), /// Wallet data for Twint Redirection + #[schema(title = "TwintRedirect")] TwintRedirect {}, /// Wallet data for Vipps Redirection + #[schema(title = "VippsRedirect")] VippsRedirect {}, - /// The wallet data for Touch n Go Redirection - TouchNGoRedirect(Box<TouchNGoRedirection>), - /// The wallet data for WeChat Pay Redirection - WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode + #[schema(title = "WeChatPayQr")] WeChatPayQr(Box<WeChatPayQr>), - /// The wallet data for Cashapp Qr - CashappQr(Box<CashappQr>), - // The wallet data for Swish - SwishQr(SwishQrData), - // The wallet data for Mifinity Ewallet - Mifinity(MifinityData), - // The wallet data for RevolutPay - RevolutPay(RevolutPayData), + /// The wallet data for WeChat Pay Redirection + #[schema(title = "WeChatPayRedirect")] + WeChatPayRedirect(Box<WeChatPayRedirection>), } impl GetAddressFromPaymentMethodData for WalletData {
2025-09-04T13:20:49Z
## 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 --> Updated openapi spec added labels to wallet 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)? --> <img width="641" height="637" alt="image" src="https://github.com/user-attachments/assets/c4d2f2a3-fb7c-46f7-98ed-01e8004d89d9" /> ## 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
v1.116.0
5e1fd0b187b99698936a8a0cb0d839a60b830de2
5e1fd0b187b99698936a8a0cb0d839a60b830de2
juspay/hyperswitch
juspay__hyperswitch-9278
Bug: [BUG] payout status is not updated in outgoing webhook ### Bug Description When an incoming webhook request triggers an outgoing webhooks request, it is triggered with a stale status. ### Expected Behavior Outgoing webhooks triggered during incoming webhooks flow must contain the latest status. ### Actual Behavior Outgoing webhooks triggered during incoming webhooks flow contains the stale status. ### Steps To Reproduce - ### Context For The Bug - ### Environment - ### 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/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 4d38ce2ed02..b248955de4d 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -1157,7 +1157,7 @@ async fn payouts_incoming_webhook_flow( payout_id: payouts.payout_id.clone(), }); - let payout_data = Box::pin(payouts::make_payout_data( + let mut payout_data = Box::pin(payouts::make_payout_data( &state, &merchant_context, None, @@ -1181,8 +1181,9 @@ async fn payouts_incoming_webhook_flow( payout_attempt.payout_attempt_id ) })?; + payout_data.payout_attempt = updated_payout_attempt; - let event_type: Option<enums::EventType> = updated_payout_attempt.status.into(); + let event_type: Option<enums::EventType> = payout_data.payout_attempt.status.into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { @@ -1195,20 +1196,21 @@ async fn payouts_incoming_webhook_flow( business_profile, outgoing_event_type, enums::EventClass::Payouts, - updated_payout_attempt + payout_data + .payout_attempt .payout_id .get_string_repr() .to_string(), enums::EventObjectType::PayoutDetails, api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)), - Some(updated_payout_attempt.created_at), + Some(payout_data.payout_attempt.created_at), )) .await?; } Ok(WebhookResponseTracker::Payout { - payout_id: updated_payout_attempt.payout_id, - status: updated_payout_attempt.status, + payout_id: payout_data.payout_attempt.payout_id, + status: payout_data.payout_attempt.status, }) } else { metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]);
2025-09-04T12:28:47Z
## 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 state update for `payout_attempt` where latest status resides. This fixes the bug mentioned in https://github.com/juspay/hyperswitch/issues/9278 ### 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 change will allow the outgoing webhooks for payouts to receive the right status. ## How did you test it? <details> <summary>1. Create a successful payout</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_o0Eo3tL2RDhcX3AzI9w5G5IguQslT7UDDYHne7W6QqjdBbQboNBTbHhW2ZuHFLIJ' \ --data-raw '{"amount":100,"currency":"EUR","profile_id":"pro_BAzWgR1xTKZGtzWKCUea","customer":{"id":"cus_yvCM0YPCw76nC5Dj2Kwm","email":"[email protected]","name":"John Doe","phone":"999999999","phone_country_code":"+65"},"connector":["adyen"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111 1111 1111 1111","expiry_month":"03","expiry_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_WIaDYW9nnqsiI50upbcg","merchant_id":"merchant_1756987500","merchant_order_reference_id":null,"amount":100,"currency":"EUR","connector":"adyen","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":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"auto_fulfill":true,"customer_id":"cus_yvCM0YPCw76nC5Dj2Kwm","customer":{"id":"cus_yvCM0YPCw76nC5Dj2Kwm","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_WIaDYW9nnqsiI50upbcg_secret_MBhR8Qp64emDZ3D0xsPq","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_B5g4wL5oJ6RGqSAdcsS5","status":"success","error_message":null,"error_code":null,"profile_id":"pro_BAzWgR1xTKZGtzWKCUea","created":"2025-09-04T12:22:28.359Z","connector_transaction_id":"TTGSSJV2MFZKTRV5","priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_8C3jiwCwp3fCfXMVcv6a"} </details> <details> <summary>2. Wait for incoming webhooks from Adyen and look at the status in outgoing webhook</summary> Expectation - for `Adyen` the incoming webhook received for payout will be mapped to `initiated` - updating the payout status to `initiated` - the latest status (`initiated` in this case) should be propagated in the outgoing webhook. HS outgoing webhook request {"merchant_id":"merchant_1756987500","event_id":"evt_019914af3ba678f1af65188c5722d96a","event_type":"payout_initiated","content":{"type":"payout_details","object":{"payout_id":"payout_WIaDYW9nnqsiI50upbcg","merchant_id":"merchant_1756987500","merchant_order_reference_id":null,"amount":100,"currency":"EUR","connector":"adyen","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":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"auto_fulfill":true,"customer_id":"cus_yvCM0YPCw76nC5Dj2Kwm","customer":{"id":"cus_yvCM0YPCw76nC5Dj2Kwm","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_WIaDYW9nnqsiI50upbcg_secret_MBhR8Qp64emDZ3D0xsPq","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_B5g4wL5oJ6RGqSAdcsS5","status":"initiated","error_message":null,"error_code":null,"profile_id":"pro_BAzWgR1xTKZGtzWKCUea","created":"2025-09-04T12:22:28.359Z","connector_transaction_id":"TTGSSJV2MFZKTRV5","priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_8C3jiwCwp3fCfXMVcv6a"}},"timestamp":"2025-09-04T12:24:12.454Z"} </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
v1.116.0
5e1fd0b187b99698936a8a0cb0d839a60b830de2
5e1fd0b187b99698936a8a0cb0d839a60b830de2
juspay/hyperswitch
juspay__hyperswitch-9284
Bug: [FEATURE] [ACI] Setup mandate and network token flow added and existing flows fixed Setup mandate and networkToken flow added for ACI connector. While doing payments, we were not validating the capture method in the request payload. Instead, we were directly treating it as automatic capture which was causing capture to fail. Made changes in API contracts in both request and response and status mapping for capture.
diff --git a/config/config.example.toml b/config/config.example.toml index d2bbb75a04e..b725be102c1 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -541,8 +541,8 @@ wallet.google_pay = { connector_list = "bankofamerica,authorizedotnet,cybersourc bank_redirect.giropay = { connector_list = "globalpay" } [mandates.supported_payment_methods] -card.credit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv" -card.debit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv" +card.credit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv" +card.debit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv" wallet.paypal = { connector_list = "adyen,novalnet" } # Mandate supported payment method type and connector for wallets pay_later.klarna = { connector_list = "adyen" } # Mandate supported payment method type and connector for pay_later bank_debit.ach = { connector_list = "gocardless,adyen" } # Mandate supported payment method type and connector for bank_debit diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 15665793cca..c756b0a9e9c 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -231,8 +231,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" -card.debit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" +card.credit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" +card.debit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,nuvei,authorizedotnet,wellsfargo" wallet.samsung_pay.connector_list = "cybersource" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 3843682e910..f685bbe2787 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -231,8 +231,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" -card.debit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" +card.credit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" +card.debit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,nuvei,authorizedotnet,wellsfargo" wallet.samsung_pay.connector_list = "cybersource" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 3fd60dfe8f9..9ed89a01c9b 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -238,8 +238,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" -card.debit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" +card.credit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" +card.debit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,nuvei,authorizedotnet,wellsfargo,worldpayvantiv" wallet.samsung_pay.connector_list = "cybersource" diff --git a/config/development.toml b/config/development.toml index 0454eb1931c..940e43b50ca 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1081,8 +1081,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" -card.debit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" +card.credit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" +card.debit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nuvei,nexinets,novalnet,authorizedotnet,wellsfargo,worldpayvantiv" wallet.samsung_pay.connector_list = "cybersource" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index b154cea783b..d299323f2c1 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1009,8 +1009,8 @@ wallet.google_pay = { connector_list = "stripe,cybersource,adyen,bankofamerica,a wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet,novalnet,multisafepay,wellsfargo,nuvei" } wallet.samsung_pay = { connector_list = "cybersource" } wallet.paypal = { connector_list = "adyen,novalnet,authorizedotnet" } -card.credit = { connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,elavon,xendit,novalnet,bamboraapac,archipel,wellsfargo,worldpayvantiv,payload" } -card.debit = { connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,elavon,xendit,novalnet,bamboraapac,archipel,wellsfargo,worldpayvantiv,payload" } +card.credit = { connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,elavon,xendit,novalnet,bamboraapac,archipel,wellsfargo,worldpayvantiv,payload" } +card.debit = { connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,elavon,xendit,novalnet,bamboraapac,archipel,wellsfargo,worldpayvantiv,payload" } bank_debit.ach = { connector_list = "gocardless,adyen" } bank_debit.becs = { connector_list = "gocardless" } bank_debit.bacs = { connector_list = "adyen" } diff --git a/crates/hyperswitch_connectors/src/connectors/aci.rs b/crates/hyperswitch_connectors/src/connectors/aci.rs index 59c89ae9771..96c3a059c22 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci.rs @@ -96,7 +96,7 @@ impl ConnectorCommon for Aci { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.into_masked(), + format!("Bearer {}", auth.api_key.peek()).into_masked(), )]) } @@ -161,31 +161,133 @@ impl api::PaymentToken for Aci {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Aci { - // Not Implemented (R) + fn build_request( + &self, + _req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::NotSupported { + message: "Payment method tokenization not supported".to_string(), + connector: "ACI", + } + .into()) + } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Aci { - // Not Implemented (R) + fn build_request( + &self, + _req: &RouterData<Session, PaymentsSessionData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::NotSupported { + message: "Payment sessions not supported".to_string(), + connector: "ACI", + } + .into()) + } } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Aci { - // Not Implemented (R) + fn build_request( + &self, + _req: &RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::NotSupported { + message: "Access token authentication not supported".to_string(), + connector: "ACI", + } + .into()) + } } impl api::MandateSetup for Aci {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Aci { - // Issue: #173 - fn build_request( + fn get_headers( + &self, + req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.common_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) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}v1/registrations", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = aci::AciMandateRequest::try_from(req)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("Setup Mandate flow for Aci".to_string()).into()) + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&self.get_url(req, connectors)?) + .attach_default_headers() + .headers(self.get_headers(req, connectors)?) + .set_body(self.get_request_body(req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult< + RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + errors::ConnectorError, + > { + let response: aci::AciMandateResponse = res + .response + .parse_struct("AciMandateResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) } } -// TODO: Investigate unexplained error in capture flow from connector. impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Aci { fn get_headers( &self, @@ -409,8 +511,6 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - // encode only for for urlencoded things. - let amount = convert_amount( self.amount_converter, req.request.minor_amount, @@ -724,14 +824,13 @@ fn decrypt_aci_webhook_payload( Ok(ciphertext_and_tag) } -// TODO: Test this webhook flow once dashboard access is available. #[async_trait::async_trait] impl IncomingWebhook for Aci { fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { - Ok(Box::new(crypto::NoAlgorithm)) + Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( @@ -899,15 +998,15 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::CaptureMethod::Manual, ]; - let supported_card_network = vec![ + let supported_card_networks = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::Discover, - common_enums::CardNetwork::JCB, - common_enums::CardNetwork::Maestro, - common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::UnionPay, - common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Maestro, ]; let mut aci_supported_payment_methods = SupportedPaymentMethods::new(); @@ -944,9 +1043,9 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { - three_ds: common_enums::FeatureStatus::NotSupported, + three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), + supported_card_networks: supported_card_networks.clone(), } }), ), @@ -963,14 +1062,15 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { - three_ds: common_enums::FeatureStatus::NotSupported, + three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), + supported_card_networks: supported_card_networks.clone(), } }), ), }, ); + aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Eps, @@ -1051,6 +1151,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo specific_features: None, }, ); + aci_supported_payment_methods.add( enums::PaymentMethod::PayLater, enums::PaymentMethodType::Klarna, @@ -1061,6 +1162,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo specific_features: None, }, ); + aci_supported_payment_methods }); diff --git a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs index 3edd04f8308..c3f5e53d9a4 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs @@ -4,10 +4,15 @@ use common_enums::enums; use common_utils::{id_type, pii::Email, request::Method, types::StringMajorUnit}; use error_stack::report; use hyperswitch_domain_models::{ - payment_method_data::{BankRedirectData, Card, PayLaterData, PaymentMethodData, WalletData}, + network_tokenization::NetworkTokenNumber, + payment_method_data::{ + BankRedirectData, Card, NetworkTokenData, PayLaterData, PaymentMethodData, WalletData, + }, router_data::{ConnectorAuthType, RouterData}, + router_flow_types::SetupMandate, router_request_types::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsSyncData, ResponseId, + SetupMandateRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, @@ -25,7 +30,10 @@ use url::Url; use super::aci_result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, - utils::{self, PhoneDetailsData, RouterData as _}, + utils::{ + self, CardData, NetworkTokenData as NetworkTokenDataTrait, PaymentsAuthorizeRequestData, + PhoneDetailsData, RouterData as _, + }, }; type Error = error_stack::Report<errors::ConnectorError>; @@ -54,8 +62,8 @@ impl GetCaptureMethod for PaymentsCancelData { #[derive(Debug, Serialize)] pub struct AciRouterData<T> { - amount: StringMajorUnit, - router_data: T, + pub amount: StringMajorUnit, + pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for AciRouterData<T> { @@ -114,6 +122,24 @@ pub struct AciCancelRequest { pub payment_type: AciPaymentType, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciMandateRequest { + pub entity_id: Secret<String>, + pub payment_brand: PaymentBrand, + #[serde(flatten)] + pub payment_details: PaymentDetails, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciMandateResponse { + pub id: String, + pub result: ResultCode, + pub build_number: String, + pub timestamp: String, +} + #[derive(Debug, Clone, Serialize)] #[serde(untagged)] pub enum PaymentDetails { @@ -123,6 +149,7 @@ pub enum PaymentDetails { Wallet(Box<WalletPMData>), Klarna, Mandate, + AciNetworkToken(Box<AciNetworkTokenData>), } impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for PaymentDetails { @@ -321,21 +348,117 @@ impl } } +fn get_aci_payment_brand( + card_network: Option<common_enums::CardNetwork>, + is_network_token_flow: bool, +) -> Result<PaymentBrand, Error> { + match card_network { + Some(common_enums::CardNetwork::Visa) => Ok(PaymentBrand::Visa), + Some(common_enums::CardNetwork::Mastercard) => Ok(PaymentBrand::Mastercard), + Some(common_enums::CardNetwork::AmericanExpress) => Ok(PaymentBrand::AmericanExpress), + Some(common_enums::CardNetwork::JCB) => Ok(PaymentBrand::Jcb), + Some(common_enums::CardNetwork::DinersClub) => Ok(PaymentBrand::DinersClub), + Some(common_enums::CardNetwork::Discover) => Ok(PaymentBrand::Discover), + Some(common_enums::CardNetwork::UnionPay) => Ok(PaymentBrand::UnionPay), + Some(common_enums::CardNetwork::Maestro) => Ok(PaymentBrand::Maestro), + Some(unsupported_network) => Err(errors::ConnectorError::NotSupported { + message: format!( + "Card network {:?} is not supported by ACI", + unsupported_network + ), + connector: "ACI", + })?, + None => { + if is_network_token_flow { + Ok(PaymentBrand::Visa) + } else { + Err(errors::ConnectorError::MissingRequiredField { + field_name: "card.card_network", + } + .into()) + } + } + } +} + impl TryFrom<(Card, Option<Secret<String>>)> for PaymentDetails { type Error = Error; fn try_from( (card_data, card_holder_name): (Card, Option<Secret<String>>), ) -> Result<Self, Self::Error> { + let card_expiry_year = card_data.get_expiry_year_4_digit(); + + let payment_brand = get_aci_payment_brand(card_data.card_network, false)?; + Ok(Self::AciCard(Box::new(CardDetails { card_number: card_data.card_number, - card_holder: card_holder_name.unwrap_or(Secret::new("".to_string())), - card_expiry_month: card_data.card_exp_month, - card_expiry_year: card_data.card_exp_year, + card_holder: card_holder_name.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "card_holder_name", + })?, + card_expiry_month: card_data.card_exp_month.clone(), + card_expiry_year, card_cvv: card_data.card_cvc, + payment_brand, }))) } } +impl + TryFrom<( + &AciRouterData<&PaymentsAuthorizeRouterData>, + &NetworkTokenData, + )> for PaymentDetails +{ + type Error = Error; + fn try_from( + value: ( + &AciRouterData<&PaymentsAuthorizeRouterData>, + &NetworkTokenData, + ), + ) -> Result<Self, Self::Error> { + let (_item, network_token_data) = value; + let token_number = network_token_data.get_network_token(); + let payment_brand = get_aci_payment_brand(network_token_data.card_network.clone(), true)?; + let aci_network_token_data = AciNetworkTokenData { + token_type: AciTokenAccountType::Network, + token_number, + token_expiry_month: network_token_data.get_network_token_expiry_month(), + token_expiry_year: network_token_data.get_expiry_year_4_digit(), + token_cryptogram: Some( + network_token_data + .get_cryptogram() + .clone() + .unwrap_or_default(), + ), + payment_brand, + }; + Ok(Self::AciNetworkToken(Box::new(aci_network_token_data))) + } +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum AciTokenAccountType { + Network, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciNetworkTokenData { + #[serde(rename = "tokenAccount.type")] + pub token_type: AciTokenAccountType, + #[serde(rename = "tokenAccount.number")] + pub token_number: NetworkTokenNumber, + #[serde(rename = "tokenAccount.expiryMonth")] + pub token_expiry_month: Secret<String>, + #[serde(rename = "tokenAccount.expiryYear")] + pub token_expiry_year: Secret<String>, + #[serde(rename = "tokenAccount.cryptogram")] + pub token_cryptogram: Option<Secret<String>>, + #[serde(rename = "paymentBrand")] + pub payment_brand: PaymentBrand, +} + #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankRedirectionPMData { @@ -365,7 +488,7 @@ pub struct WalletPMData { account_id: Option<Secret<String>>, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentBrand { Eps, @@ -379,6 +502,23 @@ pub enum PaymentBrand { Mbway, #[serde(rename = "ALIPAY")] AliPay, + // Card network brands + #[serde(rename = "VISA")] + Visa, + #[serde(rename = "MASTER")] + Mastercard, + #[serde(rename = "AMEX")] + AmericanExpress, + #[serde(rename = "JCB")] + Jcb, + #[serde(rename = "DINERS")] + DinersClub, + #[serde(rename = "DISCOVER")] + Discover, + #[serde(rename = "UNIONPAY")] + UnionPay, + #[serde(rename = "MAESTRO")] + Maestro, } #[derive(Debug, Clone, Eq, PartialEq, Serialize)] @@ -393,6 +533,8 @@ pub struct CardDetails { pub card_expiry_year: Secret<String>, #[serde(rename = "card.cvv")] pub card_cvv: Secret<String>, + #[serde(rename = "paymentBrand")] + pub payment_brand: PaymentBrand, } #[derive(Debug, Clone, Serialize)] @@ -460,6 +602,9 @@ impl TryFrom<&AciRouterData<&PaymentsAuthorizeRouterData>> for AciPaymentsReques fn try_from(item: &AciRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)), + PaymentMethodData::NetworkToken(ref network_token_data) => { + Self::try_from((item, network_token_data)) + } PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)), PaymentMethodData::PayLater(ref pay_later_data) => { Self::try_from((item, pay_later_data)) @@ -487,7 +632,6 @@ impl TryFrom<&AciRouterData<&PaymentsAuthorizeRouterData>> for AciPaymentsReques | PaymentMethodData::Voucher(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Aci"), @@ -574,7 +718,34 @@ impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AciPayme txn_details, payment_method, instruction, - shopper_result_url: None, + shopper_result_url: item.router_data.request.router_return_url.clone(), + }) + } +} + +impl + TryFrom<( + &AciRouterData<&PaymentsAuthorizeRouterData>, + &NetworkTokenData, + )> for AciPaymentsRequest +{ + type Error = Error; + fn try_from( + value: ( + &AciRouterData<&PaymentsAuthorizeRouterData>, + &NetworkTokenData, + ), + ) -> Result<Self, Self::Error> { + let (item, network_token_data) = value; + let txn_details = get_transaction_details(item)?; + let payment_method = PaymentDetails::try_from((item, network_token_data))?; + let instruction = get_instruction_details(item); + + Ok(Self { + txn_details, + payment_method, + instruction, + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } @@ -609,11 +780,16 @@ fn get_transaction_details( item: &AciRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> { let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?; + let payment_type = if item.router_data.request.is_auto_capture()? { + AciPaymentType::Debit + } else { + AciPaymentType::Preauthorization + }; Ok(TransactionDetails { entity_id: auth.entity_id, amount: item.amount.to_owned(), currency: item.router_data.request.currency.to_string(), - payment_type: AciPaymentType::Debit, + payment_type, }) } @@ -650,6 +826,61 @@ impl TryFrom<&PaymentsCancelRouterData> for AciCancelRequest { } } +impl TryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>> + for AciMandateRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + item: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let auth = AciAuthType::try_from(&item.connector_auth_type)?; + + let (payment_brand, payment_details) = match &item.request.payment_method_data { + PaymentMethodData::Card(card_data) => { + let brand = get_aci_payment_brand(card_data.card_network.clone(), false)?; + match brand { + PaymentBrand::Visa + | PaymentBrand::Mastercard + | PaymentBrand::AmericanExpress => {} + _ => Err(errors::ConnectorError::NotSupported { + message: "Payment method not supported for mandate setup".to_string(), + connector: "ACI", + })?, + } + + let details = PaymentDetails::AciCard(Box::new(CardDetails { + card_number: card_data.card_number.clone(), + card_expiry_month: card_data.card_exp_month.clone(), + card_expiry_year: card_data.get_expiry_year_4_digit(), + card_cvv: card_data.card_cvc.clone(), + card_holder: card_data.card_holder_name.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "card_holder_name", + }, + )?, + payment_brand: brand.clone(), + })); + + (brand, details) + } + _ => { + return Err(errors::ConnectorError::NotSupported { + message: "Payment method not supported for mandate setup".to_string(), + connector: "ACI", + } + .into()); + } + }; + + Ok(Self { + entity_id: auth.entity_id, + payment_brand, + payment_details, + }) + } +} + #[derive(Debug, Default, Clone, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AciPaymentStatus { @@ -674,6 +905,7 @@ fn map_aci_attempt_status(item: AciPaymentStatus, auto_capture: bool) -> enums:: AciPaymentStatus::RedirectShopper => enums::AttemptStatus::AuthenticationPending, } } + impl FromStr for AciPaymentStatus { type Err = error_stack::Report<errors::ConnectorError>; fn from_str(s: &str) -> Result<Self, Self::Err> { @@ -696,10 +928,8 @@ impl FromStr for AciPaymentStatus { pub struct AciPaymentsResponse { id: String, registration_id: Option<Secret<String>>, - // ndc is an internal unique identifier for the request. ndc: String, timestamp: String, - // Number useful for support purposes. build_number: String, pub(super) result: ResultCode, pub(super) redirect: Option<AciRedirectionData>, @@ -717,15 +947,24 @@ pub struct AciErrorResponse { #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciRedirectionData { - method: Option<Method>, - parameters: Vec<Parameters>, - url: Url, + pub method: Option<Method>, + pub parameters: Vec<Parameters>, + pub url: Url, + pub preconditions: Option<Vec<PreconditionData>>, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PreconditionData { + pub method: Option<Method>, + pub parameters: Vec<Parameters>, + pub url: Url, } #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] pub struct Parameters { - name: String, - value: String, + pub name: String, + pub value: String, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)] @@ -863,12 +1102,45 @@ pub struct AciCaptureResultDetails { extended_description: String, #[serde(rename = "clearingInstituteName")] clearing_institute_name: String, - connector_tx_id1: String, - connector_tx_id3: String, - connector_tx_id2: String, + connector_tx_i_d1: String, + connector_tx_i_d3: String, + connector_tx_i_d2: String, acquirer_response: String, } +#[derive(Debug, Default, Clone, Deserialize)] +pub enum AciCaptureStatus { + Succeeded, + Failed, + #[default] + Pending, +} + +impl FromStr for AciCaptureStatus { + type Err = error_stack::Report<errors::ConnectorError>; + fn from_str(s: &str) -> Result<Self, Self::Err> { + if FAILURE_CODES.contains(&s) { + Ok(Self::Failed) + } else if PENDING_CODES.contains(&s) { + Ok(Self::Pending) + } else if SUCCESSFUL_CODES.contains(&s) { + Ok(Self::Succeeded) + } else { + Err(report!(errors::ConnectorError::UnexpectedResponseError( + bytes::Bytes::from(s.to_owned()) + ))) + } + } +} + +fn map_aci_capture_status(item: AciCaptureStatus) -> enums::AttemptStatus { + match item { + AciCaptureStatus::Succeeded => enums::AttemptStatus::Charged, + AciCaptureStatus::Failed => enums::AttemptStatus::Failure, + AciCaptureStatus::Pending => enums::AttemptStatus::Pending, + } +} + impl<F, T> TryFrom<ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { @@ -877,10 +1149,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponse item: ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - status: map_aci_attempt_status( - AciPaymentStatus::from_str(&item.response.result.code)?, - false, - ), + status: map_aci_capture_status(AciCaptureStatus::from_str(&item.response.result.code)?), reference_id: Some(item.response.referenced_id.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), @@ -963,7 +1232,6 @@ impl From<AciRefundStatus> for enums::RefundStatus { #[serde(rename_all = "camelCase")] pub struct AciRefundResponse { id: String, - //ndc is an internal unique identifier for the request. ndc: String, timestamp: String, build_number: String, @@ -987,6 +1255,58 @@ impl<F> TryFrom<RefundsResponseRouterData<F, AciRefundResponse>> for RefundsRout } } +impl + TryFrom< + ResponseRouterData< + SetupMandate, + AciMandateResponse, + SetupMandateRequestData, + PaymentsResponseData, + >, + > for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + item: ResponseRouterData< + SetupMandate, + AciMandateResponse, + SetupMandateRequestData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let mandate_reference = Some(MandateReference { + connector_mandate_id: Some(item.response.id.clone()), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + }); + + let status = if SUCCESSFUL_CODES.contains(&item.response.result.code.as_str()) { + enums::AttemptStatus::Charged + } else if FAILURE_CODES.contains(&item.response.result.code.as_str()) { + enums::AttemptStatus::Failure + } else { + enums::AttemptStatus::Pending + }; + + Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.id), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] pub enum AciWebhookEventType { Payment, diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 9d3544d5cee..f50a7c16075 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -1,456 +1,559 @@ -#![allow(clippy::print_stdout)] +use std::str::FromStr; -use std::{borrow::Cow, marker::PhantomData, str::FromStr, sync::Arc}; - -use common_utils::id_type; -use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; +use hyperswitch_domain_models::{ + address::{Address, AddressDetails, PhoneDetails}, + payment_method_data::{Card, PaymentMethodData}, + router_request_types::AuthenticationData, +}; use masking::Secret; -use router::{ - configs::settings::Settings, - core::payments, - db::StorageImpl, - routes, services, - types::{self, storage::enums, PaymentAddress}, +use router::types::{self, storage::enums, PaymentAddress}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions, PaymentInfo}, }; -use tokio::sync::oneshot; - -use crate::{connector_auth::ConnectorAuthentication, utils}; - -fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { - let auth = ConnectorAuthentication::new() - .aci - .expect("Missing ACI connector authentication configuration"); - - let merchant_id = id_type::MerchantId::try_from(Cow::from("aci")).unwrap(); - - types::RouterData { - flow: PhantomData, - merchant_id, - customer_id: Some(id_type::CustomerId::try_from(Cow::from("aci")).unwrap()), - tenant_id: id_type::TenantId::try_from_string("public".to_string()).unwrap(), - connector: "aci".to_string(), - payment_id: uuid::Uuid::new_v4().to_string(), - attempt_id: uuid::Uuid::new_v4().to_string(), - status: enums::AttemptStatus::default(), - auth_type: enums::AuthenticationType::NoThreeDs, - payment_method: enums::PaymentMethod::Card, - connector_auth_type: utils::to_connector_auth_type(auth.into()), - description: Some("This is a test".to_string()), - payment_method_status: None, - request: types::PaymentsAuthorizeData { - amount: 1000, - currency: enums::Currency::USD, - payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { - card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), - card_exp_month: Secret::new("10".to_string()), - card_exp_year: Secret::new("2025".to_string()), - card_cvc: Secret::new("999".to_string()), - card_issuer: None, - card_network: None, - card_type: None, - card_issuing_country: None, - bank_code: None, - nick_name: Some(Secret::new("nick_name".into())), - card_holder_name: Some(Secret::new("card holder name".into())), - co_badged_card_data: None, - }), - confirm: true, - statement_descriptor_suffix: None, - statement_descriptor: None, - setup_future_usage: None, - mandate_id: None, - off_session: None, - setup_mandate_details: None, - capture_method: None, - browser_info: None, - order_details: None, - order_category: None, - email: None, - customer_name: None, - session_token: None, - enrolled_for_3ds: false, - related_transaction_id: None, - payment_experience: None, - payment_method_type: None, - router_return_url: None, - webhook_url: None, - complete_authorize_url: None, - customer_id: None, - surcharge_details: None, - request_incremental_authorization: false, - metadata: None, - authentication_data: None, - customer_acceptance: None, - locale: None, - enable_partial_authorization: None, - ..utils::PaymentAuthorizeType::default().0 - }, - response: Err(types::ErrorResponse::default()), - address: PaymentAddress::new( + +#[derive(Clone, Copy)] +struct AciTest; +impl ConnectorActions for AciTest {} +impl utils::Connector for AciTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Aci; + utils::construct_connector_data_old( + Box::new(Aci::new()), + types::Connector::Aci, + types::api::GetToken::Connector, None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .aci + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "aci".to_string() + } +} + +static CONNECTOR: AciTest = AciTest {}; + +fn get_default_payment_info() -> Option<PaymentInfo> { + Some(PaymentInfo { + address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), + line1: Some(Secret::new("123 Main St".to_string())), + city: Some("New York".to_string()), + state: Some(Secret::new("NY".to_string())), + zip: Some(Secret::new("10001".to_string())), + country: Some(enums::CountryAlpha2::US), ..Default::default() }), phone: Some(PhoneDetails { - number: Some(Secret::new("9123456789".to_string())), - country_code: Some("+351".to_string()), + number: Some(Secret::new("+1234567890".to_string())), + country_code: Some("+1".to_string()), }), email: None, }), None, - ), - connector_meta_data: None, - connector_wallets_details: None, - amount_captured: None, - minor_amount_captured: None, - access_token: None, - session_token: None, - reference_id: None, - payment_method_token: None, - connector_customer: None, - recurring_mandate_payment_data: None, - connector_response: None, - preprocessing_id: None, - connector_request_reference_id: uuid::Uuid::new_v4().to_string(), - #[cfg(feature = "payouts")] - payout_method_data: None, - #[cfg(feature = "payouts")] - quote_id: None, - test_mode: None, - payment_method_balance: None, - connector_api_version: None, - connector_http_status_code: None, - apple_pay_flow: None, - external_latency: None, - frm_metadata: None, - refund_id: None, - dispute_id: None, - integrity_check: Ok(()), - additional_merchant_data: None, - header_payload: None, - connector_mandate_request_reference_id: None, - authentication_id: None, - psd2_sca_exemption_type: None, - raw_connector_response: None, - is_payment_id_from_merchant: None, - l2_l3_data: None, - minor_amount_capturable: None, - } + None, + )), + ..Default::default() + }) } -fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { - let auth = ConnectorAuthentication::new() - .aci - .expect("Missing ACI connector authentication configuration"); - - let merchant_id = id_type::MerchantId::try_from(Cow::from("aci")).unwrap(); - - types::RouterData { - flow: PhantomData, - merchant_id, - customer_id: Some(id_type::CustomerId::try_from(Cow::from("aci")).unwrap()), - tenant_id: id_type::TenantId::try_from_string("public".to_string()).unwrap(), - connector: "aci".to_string(), - payment_id: uuid::Uuid::new_v4().to_string(), - attempt_id: uuid::Uuid::new_v4().to_string(), - payment_method_status: None, - status: enums::AttemptStatus::default(), - payment_method: enums::PaymentMethod::Card, - auth_type: enums::AuthenticationType::NoThreeDs, - connector_auth_type: utils::to_connector_auth_type(auth.into()), - description: Some("This is a test".to_string()), - request: types::RefundsData { - payment_amount: 1000, - currency: enums::Currency::USD, - - refund_id: uuid::Uuid::new_v4().to_string(), - connector_transaction_id: String::new(), - refund_amount: 100, - webhook_url: None, - connector_metadata: None, - reason: None, - connector_refund_id: None, - browser_info: None, - ..utils::PaymentRefundType::default().0 - }, - response: Err(types::ErrorResponse::default()), - address: PaymentAddress::default(), - connector_meta_data: None, - connector_wallets_details: None, - amount_captured: None, - minor_amount_captured: None, - access_token: None, - session_token: None, - reference_id: None, - payment_method_token: None, - connector_customer: None, - recurring_mandate_payment_data: None, - connector_response: None, - preprocessing_id: None, - connector_request_reference_id: uuid::Uuid::new_v4().to_string(), - #[cfg(feature = "payouts")] - payout_method_data: None, - #[cfg(feature = "payouts")] - quote_id: None, - test_mode: None, - payment_method_balance: None, - connector_api_version: None, - connector_http_status_code: None, - apple_pay_flow: None, - external_latency: None, - frm_metadata: None, - refund_id: None, - dispute_id: None, - integrity_check: Ok(()), - additional_merchant_data: None, - header_payload: None, - connector_mandate_request_reference_id: None, - authentication_id: None, - psd2_sca_exemption_type: None, - raw_connector_response: None, - is_payment_id_from_merchant: None, - l2_l3_data: None, - minor_amount_capturable: None, - } +fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), + card_exp_month: Secret::new("10".to_string()), + card_exp_year: Secret::new("2025".to_string()), + card_cvc: Secret::new("999".to_string()), + card_holder_name: Some(Secret::new("John Doe".to_string())), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }) +} + +fn get_threeds_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), + card_exp_month: Secret::new("10".to_string()), + card_exp_year: Secret::new("2025".to_string()), + card_cvc: Secret::new("999".to_string()), + card_holder_name: Some(Secret::new("John Doe".to_string())), + ..utils::CCardType::default().0 + }), + enrolled_for_3ds: true, + authentication_data: Some(AuthenticationData { + eci: Some("05".to_string()), + cavv: Secret::new("jJ81HADVRtXfCBATEp01CJUAAAA".to_string()), + threeds_server_transaction_id: Some("9458d8d4-f19f-4c28-b5c7-421b1dd2e1aa".to_string()), + message_version: Some(common_utils::types::SemanticVersion::new(2, 1, 0)), + ds_trans_id: Some("97267598FAE648F28083B2D2AF7B1234".to_string()), + created_at: common_utils::date_time::now(), + challenge_code: Some("01".to_string()), + challenge_cancel: None, + challenge_code_reason: Some("01".to_string()), + message_extension: None, + acs_trans_id: None, + authentication_type: None, + }), + ..utils::PaymentAuthorizeType::default().0 + }) } #[actix_web::test] -async fn payments_create_success() { - let conf = Settings::new().unwrap(); - let tx: oneshot::Sender<()> = oneshot::channel().0; - - let app_state = Box::pin(routes::AppState::with_storage( - conf, - StorageImpl::PostgresqlTest, - tx, - Box::new(services::MockApiClient), - )) - .await; - let state = Arc::new(app_state) - .get_session_state( - &id_type::TenantId::try_from_string("public".to_string()).unwrap(), +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(get_payment_authorize_data(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + get_payment_authorize_data(), None, - || {}, + get_default_payment_info(), ) - .unwrap(); + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} - use router::connector::Aci; - let connector = utils::construct_connector_data_old( - Box::new(Aci::new()), - types::Connector::Aci, - types::api::GetToken::Connector, - None, +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + get_payment_authorize_data(), + 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); +} + +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(get_payment_authorize_data(), 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,); +} + +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + get_payment_authorize_data(), + 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); +} + +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + get_payment_authorize_data(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, ); - let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let request = construct_payment_router_data(); - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - None, - None, - ) - .await - .unwrap(); - assert!( - response.status == enums::AttemptStatus::Charged, - "The payment failed" +} + +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + get_payment_authorize_data(), + 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, ); } #[actix_web::test] -#[ignore] -async fn payments_create_failure() { - { - let conf = Settings::new().unwrap(); - use router::connector::Aci; - let tx: oneshot::Sender<()> = oneshot::channel().0; - - let app_state = Box::pin(routes::AppState::with_storage( - conf, - StorageImpl::PostgresqlTest, - tx, - Box::new(services::MockApiClient), - )) - .await; - let state = Arc::new(app_state) - .get_session_state( - &id_type::TenantId::try_from_string("public".to_string()).unwrap(), - None, - || {}, - ) - .unwrap(); - let connector = utils::construct_connector_data_old( - Box::new(Aci::new()), - types::Connector::Aci, - types::api::GetToken::Connector, +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + get_payment_authorize_data(), None, - ); - let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let mut request = construct_payment_router_data(); - request.request.payment_method_data = - types::domain::PaymentMethodData::Card(types::domain::Card { - card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), - card_exp_month: Secret::new("10".to_string()), - card_exp_year: Secret::new("2025".to_string()), - card_cvc: Secret::new("99".to_string()), - card_issuer: None, - card_network: None, - card_type: None, - card_issuing_country: None, - bank_code: None, - nick_name: Some(Secret::new("nick_name".into())), - card_holder_name: Some(Secret::new("card holder name".into())), - co_badged_card_data: None, - }); - - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, 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 - .is_err(); - println!("{response:?}"); - assert!(response, "The payment was intended to fail but it passed"); - } + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(get_payment_authorize_data(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } #[actix_web::test] -async fn refund_for_successful_payments() { - let conf = Settings::new().unwrap(); - use router::connector::Aci; - let connector = utils::construct_connector_data_old( - Box::new(Aci::new()), - types::Connector::Aci, - types::api::GetToken::Connector, - None, +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(get_payment_authorize_data(), 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,); +} + +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund( + get_payment_authorize_data(), + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, ); - let tx: oneshot::Sender<()> = oneshot::channel().0; - - let app_state = Box::pin(routes::AppState::with_storage( - conf, - StorageImpl::PostgresqlTest, - tx, - Box::new(services::MockApiClient), - )) - .await; - let state = Arc::new(app_state) - .get_session_state( - &id_type::TenantId::try_from_string("public".to_string()).unwrap(), +} + +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + get_payment_authorize_data(), + 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, + ); +} + +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + get_payment_authorize_data(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund( + get_payment_authorize_data(), 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, + ); +} + +#[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(); - let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< - types::api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > = connector.connector.get_connector_integration(); - let request = construct_payment_router_data(); - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - None, - None, - ) - .await - .unwrap(); assert!( - response.status == enums::AttemptStatus::Charged, - "The payment failed" + response.response.is_err(), + "Payment should fail with incorrect CVC" ); - let connector_integration: services::BoxedRefundConnectorIntegrationInterface< - types::api::Execute, - types::RefundsData, - types::RefundsResponseData, - > = connector.connector.get_connector_integration(); - let mut refund_request = construct_refund_router_data(); - refund_request.request.connector_transaction_id = match response.response.unwrap() { - types::PaymentsResponseData::TransactionResponse { resource_id, .. } => { - resource_id.get_connector_transaction_id().unwrap() - } - _ => panic!("Connector transaction id not found"), - }; - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &refund_request, - payments::CallConnectorAction::Trigger, - None, - None, - ) - .await - .unwrap(); - println!("{response:?}"); +} + +#[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!( - response.response.unwrap().refund_status == enums::RefundStatus::Success, - "The refund transaction failed" + response.response.is_err(), + "Payment should fail with invalid expiry month" ); } #[actix_web::test] -#[ignore] -async fn refunds_create_failure() { - let conf = Settings::new().unwrap(); - use router::connector::Aci; - let connector = utils::construct_connector_data_old( - Box::new(Aci::new()), - types::Connector::Aci, - types::api::GetToken::Connector, - None, +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!( + response.response.is_err(), + "Payment should fail with incorrect expiry year" ); - let tx: oneshot::Sender<()> = oneshot::channel().0; - - let app_state = Box::pin(routes::AppState::with_storage( - conf, - StorageImpl::PostgresqlTest, - tx, - Box::new(services::MockApiClient), - )) - .await; - let state = Arc::new(app_state) - .get_session_state( - &id_type::TenantId::try_from_string("public".to_string()).unwrap(), - None, - || {}, +} + +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(get_payment_authorize_data(), 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!( + void_response.response.is_err(), + "Void should fail for already captured payment" + ); +} + +#[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!( + capture_response.response.is_err(), + "Capture should fail for invalid payment ID" + ); +} + +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + get_payment_authorize_data(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), ) + .await + .unwrap(); + assert!( + response.response.is_err(), + "Refund should fail when amount exceeds payment amount" + ); +} + +#[actix_web::test] +#[ignore] +async fn should_make_threeds_payment() { + let authorize_response = CONNECTOR + .make_payment( + get_threeds_payment_authorize_data(), + get_default_payment_info(), + ) + .await .unwrap(); - let connector_integration: services::BoxedRefundConnectorIntegrationInterface< - types::api::Execute, - types::RefundsData, - types::RefundsResponseData, - > = connector.connector.get_connector_integration(); - let mut request = construct_refund_router_data(); - request.request.connector_transaction_id = "1234".to_string(); - let response = services::api::execute_connector_processing_step( - &state, - connector_integration, - &request, - payments::CallConnectorAction::Trigger, - None, - None, - ) - .await - .is_err(); - println!("{response:?}"); - assert!(response, "The refund was intended to fail but it passed"); + + assert!( + authorize_response.status == enums::AttemptStatus::AuthenticationPending + || authorize_response.status == enums::AttemptStatus::Charged, + "3DS payment should result in AuthenticationPending or Charged status, got: {:?}", + authorize_response.status + ); + + if let Ok(types::PaymentsResponseData::TransactionResponse { + redirection_data, .. + }) = &authorize_response.response + { + if authorize_response.status == enums::AttemptStatus::AuthenticationPending { + assert!( + redirection_data.is_some(), + "3DS flow should include redirection data for authentication" + ); + } + } +} + +#[actix_web::test] +#[ignore] +async fn should_authorize_threeds_payment() { + let response = CONNECTOR + .authorize_payment( + get_threeds_payment_authorize_data(), + get_default_payment_info(), + ) + .await + .expect("Authorize 3DS payment response"); + + assert!( + response.status == enums::AttemptStatus::AuthenticationPending + || response.status == enums::AttemptStatus::Authorized, + "3DS authorization should result in AuthenticationPending or Authorized status, got: {:?}", + response.status + ); +} + +#[actix_web::test] +#[ignore] +async fn should_sync_threeds_payment() { + let authorize_response = CONNECTOR + .authorize_payment( + get_threeds_payment_authorize_data(), + get_default_payment_info(), + ) + .await + .expect("Authorize 3DS payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::AuthenticationPending, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync 3DS response"); + assert!( + response.status == enums::AttemptStatus::AuthenticationPending + || response.status == enums::AttemptStatus::Authorized, + "3DS sync should maintain AuthenticationPending or Authorized status" + ); } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 65fd42accf2..7508208069d 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -721,8 +721,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,worldpayvantiv,payload" -card.debit.connector_list = "checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,worldpayvantiv,payload" +card.credit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,worldpayvantiv,payload" +card.debit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource"
2025-08-19T07:22:43Z
## Type of Change - [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Summary This PR enhances the ACI connector with comprehensive 3D Secure (3DS) authentication support and modernizes the test suite, porting behavioral improvements from the `ORCH-2/aci-fixes` branch to be compatible with the current upstream codebase structure. ### Key Changes - **Standalone 3DS Implementation**: Added complete 3DS authentication flow using proper `/v1/threeDSecure` endpoints (PreAuthentication and Authentication) - **Framework Integration**: Implemented `AciThreeDSFlow` redirect form variant with dual iframe support for precondition and authentication steps - **Enhanced Request Structures**: Updated request models to include all required fields matching the reference script at `@hyperswitch/tmp/poc-exipay-cnp/scripts/aci/3ds` - **Payment Processing Improvements**: Added network token support, payment brand mapping, and proper mandate setup functionality - **Security Enhancement**: Updated webhook verification from NoAlgorithm to HMAC-SHA256 - **Modernized Test Suite**: Refactored tests to use `ConnectorActions` pattern with comprehensive coverage including positive, negative, and 3DS scenarios ### Technical Details #### Files Modified - `crates/hyperswitch_connectors/src/connectors/aci.rs` - Main connector implementation - `crates/hyperswitch_connectors/src/connectors/aci/transformers.rs` - Request/response transformers - `crates/hyperswitch_domain_models/src/router_response_types.rs` - RedirectForm enum extension - `crates/diesel_models/src/payment_attempt.rs` - Database model updates - `crates/router/src/services/api.rs` - Framework-level redirect handling - `crates/router/tests/connectors/aci.rs` - Complete test suite modernization #### Key Implementations - **3DS Request Structure**: Complete `AciStandalone3DSRequest` with all required fields including challenge indicators, enrollment flags, and proper card data handling - **Dual Iframe Support**: Framework-level HTML generation for both precondition and authentication iframes - **Payment Brand Mapping**: Support for Visa, Mastercard, American Express, JCB, and other major card networks - **Authentication**: Fixed authentication to use Bearer format - **Modern Test Architecture**: Implemented `ConnectorActions` trait pattern following project standards ### Test Coverage Enhancements #### Positive Test Scenarios - Manual capture flow: authorize, capture, partial capture, sync, void, refund - Automatic capture flow: payment, sync, refund, partial refund, multiple refunds - 3DS authentication flows with proper status validation #### Negative Test Scenarios - Invalid card details (CVC, expiry month, expiry year) - Invalid payment operations (void auto-captured, invalid payment ID) - Refund validation (amount exceeding payment amount) #### 3DS-Specific Tests - 3DS payment creation with authentication data - 3DS authorization with redirect data validation - 3DS payment synchronization - Authentication flow status verification ### Validation - ✅ All modified files pass `cargo +nightly fmt` formatting checks - ✅ Code follows project conventions and patterns - ✅ Implementation matches reference script behavior - ✅ Comprehensive test coverage (18+ test scenarios) - ✅ Modern `ConnectorActions` pattern implementation - ✅ Backward compatibility maintained for existing functionality ### Test Plan - [x] Manual capture flow tests (authorize, capture, void, refund, sync) - [x] Automatic capture flow tests (payment, refund, sync) - [x] Negative scenario tests (invalid inputs, edge cases) - [x] 3DS authentication flow tests with redirect validation - [x] Framework-level redirect form handling validation - [x] Error handling and status code validation ### Additional Changes - [x] This PR modifies the API contract - [x] 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)? --> <details> <summary>1. Cards payment </summary> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Tz5ePEgSZ0NRdEOsdx3cloAjMSV3KkPbsWubLbAlSsv0ndwsblQKTkZZMu3332yC' \ --data-raw '{ "amount": 6540, "currency": "EUR", "amount_to_capture": 6540, "confirm": true, "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": "5454545454545454", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "737", "card_network": "Mastercard" } }, "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" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal" }' ``` Response ``` ``` </details> 2. Redirection <img width="1721" height="1082" alt="Screenshot 2025-09-03 at 10 17 24 AM" src="https://github.com/user-attachments/assets/4e4c7059-1353-4160-b02e-bfa24fe7aa00" /> <details> <summary>3. CIT </summary> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_jBGr5aVyHqi26wIUT0l6VoyH0lGLSC5AcUoyoSv4MOaZDVulNKHuceiO87kr1UDn' \ --data-raw '{ "amount": 6540, "currency": "EUR", "amount_to_capture": 6540, "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "routing": { "type": "single", "data": "stripe" }, "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5454545454545454", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "737", "card_network": "Mastercard" } }, "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" } }, "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, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } } }' ```` Response: ``` {"payment_id":"pay_nJrHQrInwO77Uvsjrp1h","merchant_id":"merchant_1756939264","status":"requires_customer_action","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":6540,"amount_received":null,"connector":"aci","client_secret":"pay_nJrHQrInwO77Uvsjrp1h_secret_klCqSLL4Va5yqCqoS7iU","created":"2025-09-03T22:48:45.789Z","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":"man_JblRgVnFHqYNKvQIONrg","mandate_data":{"update_mandate_id":null,"customer_acceptance":{"acceptance_type":"offline","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"125.0.0.1","user_agent":"amet irure esse"}},"mandate_type":{"multi_use":{"amount":1000,"currency":"USD","start_date":"2023-04-21T00:00:00.000Z","end_date":"2023-05-21T00:00:00.000Z","metadata":{"frequency":"13"}}}},"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"5454","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"545454","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":[{"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":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_nJrHQrInwO77Uvsjrp1h/merchant_1756939264/pay_nJrHQrInwO77Uvsjrp1h_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":1756939725,"expires":1756943325,"secret":"epk_a1f0c3c09a644947b2fbad66699edd4d"},"manual_retry_allowed":null,"connector_transaction_id":"8ac7a4a19911957d019911c4b0db7792","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":"8ac7a4a19911957d019911c4b0db7792","payment_link":null,"profile_id":"pro_HoadX959YnH9wsndpUrq","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_PZ6v2D98umb2BxIN28tM","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-03T23:03:45.788Z","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_Nm9GUukfMLZhXdHJSEy0","network_transaction_id":null,"payment_method_status":null,"updated":"2025-09-03T22:48:47.635Z","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} ``` </details> <details> <summary>4. Corresponding MIT </summary> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jBGr5aVyHqi26wIUT0l6VoyH0lGLSC5AcUoyoSv4MOaZDVulNKHuceiO87kr1UDn' \ --data '{ "amount": 1000, "currency": "EUR", "customer_id": "customer123", "description": "Subsequent Mandate Test Payment (MIT from New CIT Demo)", "confirm": true, "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "pm_Nm9GUukfMLZhXdHJSEy0" } } ' ``` Response ``` {"payment_id":"pay_tzYpHGeuRYHdPGK5M89d","merchant_id":"merchant_1756939264","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":1000,"connector":"aci","client_secret":"pay_tzYpHGeuRYHdPGK5M89d_secret_AErv7wAoaKE3LP4CWUR1","created":"2025-09-03T22:49:39.145Z","currency":"EUR","customer_id":"customer123","customer":{"id":"customer123","name":"John Doe","email":"[email protected]","phone":"9999999999","phone_country_code":"+1"},"description":"Subsequent Mandate Test Payment (MIT from New CIT Demo)","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":"5454","card_type":null,"card_network":"Mastercard","card_issuer":null,"card_issuing_country":null,"card_isin":"545454","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":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":"customer123","created_at":1756939779,"expires":1756943379,"secret":"epk_63a75cd297424ac8b2af9abbd2e7396b"},"manual_retry_allowed":false,"connector_transaction_id":"8ac7a49f99119578019911c57d647953","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":"8ac7a49f99119578019911c57d647953","payment_link":null,"profile_id":"pro_HoadX959YnH9wsndpUrq","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_PZ6v2D98umb2BxIN28tM","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-03T23:04:39.145Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_Nm9GUukfMLZhXdHJSEy0","network_transaction_id":null,"payment_method_status":"active","updated":"2025-09-03T22:49:40.001Z","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":"8ac7a4a299119a87019911c4af57529a","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> <details> <summary>5. setup mandate </summary> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_dVV9Je3mjaAV1ryc2n6xxIBOOiA5O7RoCqSRMpVpb9Gj9AV6dS5g3hEbMQp3K5rG' \ --data-raw ' { "amount": 0, "currency": "USD", "confirm": true, "customer_id": "tester123C", "email": "[email protected]", "setup_future_usage": "off_session", "payment_type": "setup_mandate", "off_session": true, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5454545454545454", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "737", "card_network": "Mastercard" } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } }, "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" }, "email":"[email protected]" } }' ``` Response ``` {"payment_id":"pay_4fB1VOfBvH94w8ubEwIR","merchant_id":"merchant_1756917466","status":"succeeded","amount":0,"net_amount":0,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"aci","client_secret":"pay_4fB1VOfBvH94w8ubEwIR_secret_CGiYMO43dEvBza21wCNY","created":"2025-09-03T21:43:07.598Z","currency":"USD","customer_id":"tester123C","customer":{"id":"tester123C","name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":"man_D0PDZ3sITaf5hRKWOv9w","mandate_data":{"update_mandate_id":null,"customer_acceptance":{"acceptance_type":"offline","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"125.0.0.1","user_agent":"amet irure esse"}},"mandate_type":{"multi_use":{"amount":1000,"currency":"USD","start_date":"2023-04-21T00:00:00.000Z","end_date":"2023-05-21T00:00:00.000Z","metadata":{"frequency":"13"}}}},"setup_future_usage":"off_session","off_session":true,"capture_on":null,"capture_method":null,"payment_method":"card","payment_method_data":{"card":{"last4":"5454","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"545454","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":"John","last_name":"Doe","origin_zip":null},"phone":null,"email":"[email protected]"},"billing":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":"tester123C","created_at":1756935787,"expires":1756939387,"secret":"epk_297846ba6efb4bc1a00da345f2d56273"},"manual_retry_allowed":false,"connector_transaction_id":"8ac7a4a1990ec863019911889b7c095d","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":"8ac7a4a1990ec863019911889b7c095d","payment_link":null,"profile_id":"pro_xtK5YkotshPxwjOySVEi","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_gnftzAdh1YZJvZj3U2nU","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-03T21:58:07.597Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_lM41ZHCkvobdOiYZwhPr","network_transaction_id":null,"payment_method_status":"active","updated":"2025-09-03T21:43:10.100Z","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":"8ac7a4a1990ec863019911889b7c095d","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> <details> <summary>6. MIT corresponding to setup mandate</summary> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_T42KWe2OWnUIg0vvhyYcFu7R1lLBKCRrpLWyPb4hWHNFyyC34aN9NQjpUdLsd9t9' \ --data '{ "amount": 1000, "currency": "USD", "customer_id": "tester123C", "description": "Subsequent Mandate Test Payment (MIT from New CIT Demo)", "confirm": true, "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "pm_lM41ZHCkvobdOiYZwhPr" } } ' ``` Response ``` {"payment_id":"pay_TzRnmR2Nthv3WQbjCToR","merchant_id":"merchant_1756917466","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":1000,"connector":"aci","client_secret":"pay_TzRnmR2Nthv3WQbjCToR_secret_dOfVMRSVNv25sfAoN6nO","created":"2025-09-03T21:44:32.257Z","currency":"USD","customer_id":"tester123C","customer":{"id":"tester123C","name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"description":"Subsequent Mandate Test Payment (MIT from New CIT Demo)","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":"5454","card_type":null,"card_network":"Mastercard","card_issuer":null,"card_issuing_country":null,"card_isin":"545454","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":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":"tester123C","created_at":1756935872,"expires":1756939472,"secret":"epk_a4ec4eaa5b374dc682e3fac2ad45b421"},"manual_retry_allowed":false,"connector_transaction_id":"8ac7a4a0990ed03f01991189e2d474be","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":"8ac7a4a0990ed03f01991189e2d474be","payment_link":null,"profile_id":"pro_xtK5YkotshPxwjOySVEi","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_gnftzAdh1YZJvZj3U2nU","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-03T21:59:32.256Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_lM41ZHCkvobdOiYZwhPr","network_transaction_id":null,"payment_method_status":"active","updated":"2025-09-03T21:44:33.883Z","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":"8ac7a4a1990ec863019911889b7c095d","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> <details> <summary>7. Network Token flow</summary> I. Create ACI connector ``` curl --location 'http://localhost:8080/account/merchant_1756935953/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_HlwN4Co1MokPmoPglbMtwu0HJ25IBH6oRMWOUJuubIG71NvbeULTgz9TNjjGzlsz' \ --data '{ "connector_type": "payment_processor", "connector_name": "aci", "connector_account_details": { "auth_type": "BodyKey", "api_key": API_KEY, "key1": ENTITY_ID }, "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, "accepted_countries":null, "accepted_currencies": null }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_countries": null, "accepted_currencies": null } ] }, ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_label": "default" }' ``` II. Enable UAS for profile ``` curl --location 'http://localhost:8080/configs/merchants_eligible_for_authentication_service' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "key": "merchants_eligible_for_authentication_service", "value": VALUE_HERE }' ``` III. create ctp_mastercard ``` curl --location 'http://localhost:8080/account/merchant_1756935953/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_HlwN4Co1MokPmoPglbMtwu0HJ25IBH6oRMWOUJuubIG71NvbeULTgz9TNjjGzlsz' \ --data '{ "connector_type": "authentication_processor", "connector_name": "ctp_mastercard", "connector_account_details": { "auth_type": "HeaderKey", "api_key": API_KEY }, "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 } ] } ], "business_country": "US", "business_label": "default", "metadata": { "dpa_id": "DPA ID", "dpa_name": "TestMerchant", "locale": "en_AU", "card_brands": [ "mastercard", "visa" ], "acquirer_bin": "ACQUIRER BIN", "acquirer_merchant_id": "ACQUIRER MERCHANT ID", "merchant_category_code": "0001", "merchant_country_code": "US" } }' ``` IV. CTP profile update ``` curl --location 'http://localhost:8080/account/merchant_1756935953/business_profile/pro_kkwmU6LfcSIte3TlcHMh' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_HlwN4Co1MokPmoPglbMtwu0HJ25IBH6oRMWOUJuubIG71NvbeULTgz9TNjjGzlsz' \ --data '{ "is_click_to_pay_enabled": true, "authentication_product_ids": {"click_to_pay": "mca_foGzOn6nPM6TFvwh6fhj"} }' ``` V. create payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_HlwN4Co1MokPmoPglbMtwu0HJ25IBH6oRMWOUJuubIG71NvbeULTgz9TNjjGzlsz' \ --data-raw ' { "amount": 1130, "currency": "EUR", "confirm": false, "return_url": "https://hyperswitch.io", "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]" } }' ``` Response ``` {"payment_id":"pay_CHQQv8xweeAmih5MdFXd","merchant_id":"merchant_1756935953","status":"requires_payment_method","amount":1130,"net_amount":1130,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":null,"client_secret":"pay_CHQQv8xweeAmih5MdFXd_secret_zoplDPH6fk9Qm6Recdqn","created":"2025-09-03T21:48:11.651Z","currency":"EUR","customer_id":null,"customer":null,"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":null,"payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://hyperswitch.io/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":null,"profile_id":"pro_kkwmU6LfcSIte3TlcHMh","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-03T22:03:11.651Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":null,"payment_method_status":null,"updated":"2025-09-03T21:48:11.673Z","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} ``` VI. confirm payment ``` curl --location 'http://localhost:8080/payments/pay_CHQQv8xweeAmih5MdFXd/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_4c7f1ffc1dfc4e889e867ac60505d178' \ --data '{ "payment_method": "card", "payment_method_type": "debit", "client_secret": "pay_CHQQv8xweeAmih5MdFXd_secret_zoplDPH6fk9Qm6Recdqn", "all_keys_required":true, "ctp_service_details": { "merchant_transaction_id": VALUE_HERE, "correlation_id": VALUE_HERE, "x_src_flow_id": VALUE_HERE }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-GB", "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "user_agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36" } }' ``` Response ``` {"payment_id":"pay_CHQQv8xweeAmih5MdFXd","merchant_id":"merchant_1756935953","status":"requires_customer_action","amount":1130,"net_amount":1130,"shipping_cost":null,"amount_capturable":1130,"amount_received":null,"connector":"aci","client_secret":"pay_CHQQv8xweeAmih5MdFXd_secret_zoplDPH6fk9Qm6Recdqn","created":"2025-09-03T21:48:11.651Z","currency":"EUR","customer_id":null,"customer":null,"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":null,"payment_method":"card","payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"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":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_CHQQv8xweeAmih5MdFXd/merchant_1756935953/pay_CHQQv8xweeAmih5MdFXd_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":null,"connector_transaction_id":"8ac7a4a1990ec8630199118d5b0d11ed","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":"8ac7a4a1990ec8630199118d5b0d11ed","payment_link":null,"profile_id":"pro_kkwmU6LfcSIte3TlcHMh","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_bQFt1dkbAjSp6Gv6pbJR","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":{"authentication_flow":null,"electronic_commerce_indicator":"06","status":"success","ds_transaction_id":null,"version":null,"error_code":null,"error_message":null},"external_3ds_authentication_attempted":false,"expires_on":"2025-09-03T22:03:11.651Z","fingerprint":null,"browser_info":{"os_type":null,"language":"en-GB","time_zone":-330,"ip_address":"::1","os_version":null,"user_agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36","color_depth":24,"device_model":null,"java_enabled":true,"screen_width":2560,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1440,"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-03T21:48:20.951Z","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":"click_to_pay","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":"{\"id\":\"8ac7a4a1990ec8630199118d5b0d11ed\",\"paymentType\":\"DB\",\"paymentBrand\":\"VISA\",\"amount\":\"11.30\",\"currency\":\"EUR\",\"descriptor\":\"3484.7818.5182 NetworkTokenChannel \",\"result\":{\"code\":\"000.200.000\",\"description\":\"transaction pending\"},\"tokenAccount\":{\"number\":\"2222030199301958\",\"type\":\"NETWORK\",\"expiryMonth\":\"10\",\"expiryYear\":\"2027\"},\"redirect\":{\"url\":\"https://eu-test.oppwa.com/connectors/demo/cybersourcerest/simulator/payment.ftl?ndcid=8a8294175d602369015d73bf009f1808_efdb58167aad468a928b44dde03c2115\",\"parameters\":[{\"name\":\"TransactionId\",\"value\":\"0000000070575071\"},{\"name\":\"uuid\",\"value\":\"8ac7a4a1990ec8630199118d5b0d11ed\"}]},\"buildNumber\":\"e05bc10dcc6acc6bd4abda346f4af077dcd905d7@2025-09-02 06:02:21 +0000\",\"timestamp\":\"2025-09-03 21:48:20+0000\",\"ndc\":\"8a8294175d602369015d73bf009f1808_efdb58167aad468a928b44dde03c2115\",\"source\":\"OPP\",\"paymentMethod\":\"NT\",\"shortId\":\"3484.7818.5182\"}","enable_partial_authorization":null} ``` </details> <details> <summary>7. Manual capture </summary> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jBGr5aVyHqi26wIUT0l6VoyH0lGLSC5AcUoyoSv4MOaZDVulNKHuceiO87kr1UDn' \ --data-raw '{ "amount": 6540, "currency": "EUR", "amount_to_capture": 6540, "confirm": true, "capture_method": "manual", "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", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5386024192625914", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "737", "card_network": "Mastercard" } }, "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" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal" } ' ``` Response: ``` {"payment_id":"pay_dTlUOqtFsHTk2pYjcNDt","merchant_id":"merchant_1756939264","status":"requires_customer_action","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":6540,"amount_received":null,"connector":"aci","client_secret":"pay_dTlUOqtFsHTk2pYjcNDt_secret_quBPvBLmgEoMeGq30q8W","created":"2025-09-04T12:25:30.223Z","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":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"5914","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"538602","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":[{"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":"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_dTlUOqtFsHTk2pYjcNDt/merchant_1756939264/pay_dTlUOqtFsHTk2pYjcNDt_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":1756988730,"expires":1756992330,"secret":"epk_fbfca29dcba44555b3c4abb3e7ce9b67"},"manual_retry_allowed":null,"connector_transaction_id":"8ac7a49f9912a69e019914b074cd08f8","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":"8ac7a49f9912a69e019914b074cd08f8","payment_link":null,"profile_id":"pro_HoadX959YnH9wsndpUrq","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_PZ6v2D98umb2BxIN28tM","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-04T12:40:30.223Z","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-04T12:25:33.311Z","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} ```` capture after redirection: ``` curl --location 'http://localhost:8080/payments/pay_dTlUOqtFsHTk2pYjcNDt/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jBGr5aVyHqi26wIUT0l6VoyH0lGLSC5AcUoyoSv4MOaZDVulNKHuceiO87kr1UDn' \ --data '{ "amount_to_capture": 6540, "statement_descriptor_name": "Joseph", "statement_descriptor_prefix" :"joseph", "statement_descriptor_suffix": "JS" }' ``` Response ``` {"payment_id":"pay_dTlUOqtFsHTk2pYjcNDt","merchant_id":"merchant_1756939264","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"aci","client_secret":"pay_dTlUOqtFsHTk2pYjcNDt_secret_quBPvBLmgEoMeGq30q8W","created":"2025-09-04T12:25:30.223Z","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":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"5914","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"538602","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":[{"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":"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":"8ac7a4a29912ae61019914b0fd8866f5","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":"8ac7a49f9912a69e019914b074cd08f8","payment_link":null,"profile_id":"pro_HoadX959YnH9wsndpUrq","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_PZ6v2D98umb2BxIN28tM","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-04T12:40:30.223Z","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_dgRVnCJRHsU6c2LmY34G","network_transaction_id":null,"payment_method_status":null,"updated":"2025-09-04T12:26:08.107Z","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} ``` </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 - [x] I added unit tests for my changes where possible
v1.116.0
7355a83ef9316a6cc7f9fa0c9c9aec7397e9fc4b
7355a83ef9316a6cc7f9fa0c9c9aec7397e9fc4b
juspay/hyperswitch
juspay__hyperswitch-9270
Bug: [FEATURE] Map NTID for nuvei Map NTID for Nuvei connector
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 791261d9ee0..b5bf5236330 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -2113,6 +2113,7 @@ pub struct NuveiPaymentsResponse { pub auth_code: Option<String>, pub custom_data: Option<String>, pub fraud_details: Option<FraudDetails>, + // NTID pub external_scheme_transaction_id: Option<Secret<String>>, pub session_token: Option<Secret<String>>, pub partial_approval: Option<NuveiPartialApproval>, @@ -2420,7 +2421,10 @@ fn create_transaction_response( } else { None }, - network_txn_id: None, + network_txn_id: response + .external_scheme_transaction_id + .as_ref() + .map(|ntid| ntid.clone().expose()), connector_response_reference_id: response.order_id.clone(), incremental_authorization_allowed: None, charges: None,
2025-09-03T11:36:44Z
## 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 --> Return Network transaction if from connector Response - NOTE: we need to ask nuvei to return `external_scheme_transaction_id` during integration. <details> <summary> See returned NTID in the connector payment response</summary> ### Request ```json { "amount": 4324, "currency": "EUR", "confirm": true, "capture_method":"automatic", "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": "on_session", "payment_type":"setup_mandate", "connector":["nuvei"], "customer_id": "nidthhxxinn", "return_url": "https://www.google.com", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", "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" } }, "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_132ox19xtSuuI0v9ys8n", "merchant_id": "merchant_1756789409", "status": "succeeded", "amount": 4324, "net_amount": 4324, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_132ox19xtSuuI0v9ys8n_secret_zh69zcTMS8m8Gu3Qbxqj", "created": "2025-09-03T11:35:15.849Z", "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": "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_G1CCSamx2eABoRZkUVdu", "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": 1756899315, "expires": 1756902915, "secret": "epk_47477b29a38249f98abba6493c539f4b" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016989638", "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": "8460393111", "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-03T11:50:15.849Z", "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_bdgYAugJg43wY2L78Vkb", "network_transaction_id": "483299310332879", // NETWORK TRANSACTION ID "payment_method_status": "active", "updated": "2025-09-03T11:35:18.030Z", "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": "2313100111", "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> <details> <summary> make a payment using NTID and card details</summary> ### 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" } }, // "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", "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": "4000000000009995", "card_exp_month": "01", "card_exp_year": "2026", "card_network":"VISA", "network_transaction_id": "483299310332879" } } } ``` ### Response ```json { "payment_id": "pay_PP3muTBqIZL7tmrcOUgt", "merchant_id": "merchant_1756789409", "status": "succeeded", "amount": 10023, "net_amount": 10023, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10023, "connector": "nuvei", "client_secret": "pay_PP3muTBqIZL7tmrcOUgt_secret_nv6ljhZsvECDd4g7p3V2", "created": "2025-09-03T11:48:42.127Z", "currency": "EUR", "customer_id": null, "customer": 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": "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": 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": 1756900122, "expires": 1756903722, "secret": "epk_803cf15eb02a4cd29894d6eb117b464e" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016990565", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "8460887111", "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-03T12:03:42.127Z", "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": "483299310332879", "payment_method_status": null, "updated": "2025-09-03T11:48:43.810Z", "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 } ``` </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` --> ## 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
v1.116.0
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
juspay/hyperswitch
juspay__hyperswitch-9258
Bug: [BUG] secure payment links don't render ### Bug Description Secure payment links are not instantiating and rendering the checkout widget. ### Expected Behavior Secure payment links should render the checkout widget. ### Actual Behavior Secure payment links are breaking the functionality. ### Steps To Reproduce - Whitelist `allowed_domains` in `payment_link_config` - Create a payment link - Open secure links ### Context For The Bug - ### 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/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index c539363c102..3a9e7f60336 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -30,7 +30,8 @@ if (!isFramed) { **/ function initializeSDK() { // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; + var encodedPaymentDetails = window.__PAYMENT_DETAILS; + var paymentDetails = decodeUri(encodedPaymentDetails); var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; var labelType = paymentDetails.payment_form_label_type;
2025-09-03T10:49:24Z
## 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 bug where the encoded payment link details were being read without decoding them first. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Fixes usage of secure payment links. ## How did you test it? Locally by creating secure payment links. <details> <summary>1. Update allowed domains in payment link config</summary> cURL curl --location --request POST 'https://sandbox.hyperswitch.io/account/merchant_1681193734270/business_profile/pro_E7pM8kGERopEKEhqwfWQ' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_001otYWH3kG1v2SYexBXbt7AwbGQx8lK18wdsAmDvxtKVVLbBupRICLt6Styqadq' \ --data '{ "payment_link_config": { "theme": "#003264", "allowed_domains": [ "localhost:5000", "http://localhost:5500", "localhost:5500", "http://localhost:5000", "http://localhost:5501", "localhost:5501", "http://127.0.0.1:5501", "127.0.0.1:5501" ], "branding_visibility": false } }' </details> <details> <summary>2. Create a payment link</summary> cURL curl --location --request POST 'https://sandbox.hyperswitch.io/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: de' \ --header 'api-key: dev_001otYWH3kG1v2SYexBXbt7AwbGQx8lK18wdsAmDvxtKVVLbBupRICLt6Styqadq' \ --data-raw '{ "customer_id": "cus_CDei4NEhboFFubgAxsy8", "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" } }, "setup_future_usage": "off_session", "amount": 100, "currency": "EUR", "confirm": false, "payment_link": true, "session_expiry": 7890000, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "country": "IT", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "return_url": "https://www.example.com" }' Response {"payment_id":"pay_6tphveQF5TmCQO90G05r","merchant_id":"merchant_1756818611","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":null,"client_secret":"pay_6tphveQF5TmCQO90G05r_secret_VUlaPQSpKYZWGwCpGBI4","created":"2025-09-03T10:38:39.889Z","currency":"EUR","customer_id":"cus_Ey5nUuS0S4R2xds9t51K","customer":{"id":"cus_Ey5nUuS0S4R2xds9t51K","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":null,"payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":null,"country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":null,"first_name":"John","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":"999999999","return_url":"https://www.example.com/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_Ey5nUuS0S4R2xds9t51K","created_at":1756895919,"expires":1756899519,"secret":"epk_a9551c5842a04d8cbd9eb0213ea5790d"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1756818611/pay_6tphveQF5TmCQO90G05r?locale=de","secure_link":"http://localhost:8080/payment_link/s/merchant_1756818611/pay_6tphveQF5TmCQO90G05r?locale=de","payment_link_id":"plink_KZjExI8gP8BP0pRGVaI9"},"profile_id":"pro_GlXrXUKHbckWzGnidhzV","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-12-03T18:18:39.883Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"network_transaction_id":null,"payment_method_status":null,"updated":"2025-09-03T10:38:39.911Z","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} </details> <details> <summary>3. Open in an iframe</summary> HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> html, body { margin: 0; display: flex; align-items: center; justify-content: center; background-color: black; height: 100vh; width: 100vw; } iframe { border-radius: 4px; height: 90vh; width: 90vw; background-color: white; } </style> </head> <body> <iframe allow="payment" src="http://localhost:8080/payment_link/s/merchant_1756818611/pay_5NZOVfi2G1Xg856uyTCZ?locale=de" frameborder="0"></iframe> </body> </html> <img width="860" height="840" alt="Screenshot 2025-09-03 at 4 18 58 PM" src="https://github.com/user-attachments/assets/990d25a1-cb4c-4049-bc60-78f9a2232047" /> </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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
juspay/hyperswitch
juspay__hyperswitch-9264
Bug: [BUG] Add extra field for Cybersource MIT payment for acquirer CMCIC ### Bug Description For acquirer CMCIC, Cybersource MIT payments needs the following field `paymentInformation.card.typeSelectionIndicator` ### Expected Behavior the said field should be present in MIT payments ### Actual Behavior the said field is currently not present in MIT payments ### 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/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index e39bc64c3f6..c877832521f 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -562,11 +562,17 @@ pub struct MandatePaymentTokenizedCard { transaction_type: TransactionType, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MandateCard { + type_selection_indicator: Option<String>, +} #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MandatePaymentInformation { payment_instrument: CybersoucrePaymentInstrument, tokenized_card: MandatePaymentTokenizedCard, + card: Option<MandateCard>, } #[derive(Debug, Serialize)] @@ -2555,6 +2561,15 @@ impl TryFrom<(&CybersourceRouterData<&PaymentsAuthorizeRouterData>, String)> let payment_instrument = CybersoucrePaymentInstrument { id: connector_mandate_id.into(), }; + let mandate_card_information = match item.router_data.request.payment_method_type { + Some(enums::PaymentMethodType::Credit) | Some(enums::PaymentMethodType::Debit) => { + Some(MandateCard { + type_selection_indicator: Some("1".to_owned()), + }) + } + _ => None, + }; + let bill_to = item .router_data .get_optional_billing_email() @@ -2567,6 +2582,7 @@ impl TryFrom<(&CybersourceRouterData<&PaymentsAuthorizeRouterData>, String)> tokenized_card: MandatePaymentTokenizedCard { transaction_type: TransactionType::StoredCredentials, }, + card: mandate_card_information, })); let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item
2025-09-03T13:09:14Z
…IT payments ## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description For acquirer CMCIC, Cybersource MIT payments needs the following field `paymentInformation.card.typeSelectionIndicator` This PR addresses the same ### 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)? --> <details> <summary>Create MIT for cards via cybersource</summary> **MIT curl** ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jEdNDCtQGso72keWEtypBWmXAKaYNLmAcTTsutLbPwa8CY4p2I36w4wVkZziDTuK' \ --data-raw '{ "recurring_details": { "type": "payment_method_id", "data": "pm_TjN8SPmxPhH9HMUG1QRT" }, "authentication_type": "no_three_ds", "customer": { "id": "StripeCustomer", "email": "[email protected]" }, "description": "This is the test payment made through Mule API", "currency": "USD", "amount": 126, "confirm": true, "capture_method": "automatic", "off_session": true, "metadata": { "businessUnit": "ZG_GL_Group", "country": "US", "clientId": "N/A", "productName": "Travel insurance", "orderReference": "order-040724-001" } }' ``` **Response** ``` {"payment_id":"pay_IwxJCwYyfgVs2dmuJEGV","merchant_id":"merchant_1756212829","status":"succeeded","amount":126,"net_amount":126,"shipping_cost":null,"amount_capturable":0,"amount_received":126,"connector":"cybersource","client_secret":"pay_IwxJCwYyfgVs2dmuJEGV_secret_vrVfkIHFXMHTjV15kPvX","created":"2025-09-03T13:03:09.431Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+1"},"description":"This is the test payment made through Mule API","refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1091","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2025","card_holder_name":"Max Mustermann","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":null,"authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"StripeCustomer","created_at":1756904589,"expires":1756908189,"secret":"epk_98623acc878f40c58dec97f2ccd8b2c9"},"manual_retry_allowed":false,"connector_transaction_id":"7569045896736796904805","frm_message":null,"metadata":{"country":"US","clientId":"N/A","productName":"Travel insurance","businessUnit":"ZG_GL_Group","orderReference":"order-040724-001"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_IwxJCwYyfgVs2dmuJEGV_1","payment_link":null,"profile_id":"pro_LDyaQED9dZ5fgu7cmTQ0","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_xal1vas6DVUdGb6LDbro","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-03T13:18:09.431Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_TjN8SPmxPhH9HMUG1QRT","network_transaction_id":"123456789619999","payment_method_status":"active","updated":"2025-09-03T13:03:09.995Z","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":"3DE62376C727E833E063AF598E0A2728","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} ``` Screenshot of logs: `type_selection_indicator` is passed as 1 <img width="1721" height="252" alt="Screenshot 2025-09-03 at 6 32 25 PM" src="https://github.com/user-attachments/assets/8b2f4abb-80dd-415f-960e-413b0ecc7ebc" /> </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
v1.116.0
04578801b62245144c029accb6de5c23042480cb
04578801b62245144c029accb6de5c23042480cb
juspay/hyperswitch
juspay__hyperswitch-9268
Bug: Fix UCS address precedence order for payment method billing addresses ## Problem The current implementation in the UCS (Unified Connector Service) transformers has incorrect precedence order when handling addresses. The unified payment method billing address should take priority over the shipping/billing addresses from the payment request. ## Current Behavior - Shipping address: `shipping.or(unified_payment_method_billing.clone())` - Billing address: `billing.or(unified_payment_method_billing)` This means the payment request addresses take precedence over the unified payment method billing address. ## Expected Behavior The unified payment method billing address should take precedence: - Shipping address: `unified_payment_method_billing.clone().or(shipping)` - Billing address: `unified_payment_method_billing.or(billing)` ## Impact This affects address data consistency in UCS transformations and could lead to incorrect address information being sent to connectors. ## Files Affected - `crates/router/src/core/unified_connector_service/transformers.rs`
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index dec4281e7a9..9cc94c4a866 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -967,8 +967,8 @@ impl ForeignTryFrom<hyperswitch_domain_models::payment_address::PaymentAddress> } }); Ok(Self { - shipping_address: shipping.or(unified_payment_method_billing.clone()), - billing_address: billing.or(unified_payment_method_billing), + shipping_address: shipping, + billing_address: unified_payment_method_billing.or(billing), }) } }
2025-09-03T14:53:29Z
## Summary This PR fixes the billing address precedence order in the UCS (Unified Connector Service) transformers to ensure that unified payment method billing addresses take priority over billing addresses from payment requests. ## Changes - Changed billing address precedence: `unified_payment_method_billing.or(billing)` instead of `billing.or(unified_payment_method_billing)` - Shipping address logic remains unchanged: `shipping` ## Related Issues - Closes #9268: Fix UCS address precedence order for payment method billing addresses ## Type of Change - [x] Bug fix - [ ] New feature - [ ] Breaking change - [ ] Documentation update - [ ] Refactoring ## Testing - [x] Code follows project style guidelines - [x] Self-review completed - [ ] Tests pass locally - [ ] Documentation updated if needed ## Impact This change ensures that unified payment method billing addresses take priority over payment request billing addresses in UCS transformations, providing more consistent address data handling. ## Files Modified - `crates/router/src/core/unified_connector_service/transformers.rs` (line 971) ## Technical Details The fix changes the precedence logic for billing addresses in the `ForeignTryFrom` implementation for `payments_grpc::PaymentAddress`. Previously, billing addresses from the payment request took precedence over unified payment method billing addresses. Now, if a unified payment method billing address exists, it will be used; otherwise, it falls back to the payment request billing address. ### Testing ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-request-id: adsfadfads' \ --header 'api-key: dev_iTbySOVTqap2S4d7lr80lizI9gP4Ud3cji91v7AV1xk1elLdWNNq6dDVnSoAbpI6' \ --data-raw '{ "amount": 6540, "currency": "INR", "amount_to_capture": 6540, "confirm": true, "profile_id": "pro_RkdjC1k2ZDLH1wvhSc76", "email": "[email protected]", "capture_method": "automatic", "authentication_type": "no_three_ds", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+91" }, "customer_id": "customer123", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "success@razorpay" } }, "billing": { "email": "[email protected]", "phone": { "country_code": "+91", "number": "6502530000" } } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "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" }, "request_incremental_authorization": false, "merchant_order_reference_id": "testing_the_integ03454", "all_keys_required": true, "session_expiry": 900 }' ``` ```json { "payment_id": "pay_d4tMeFMxF4EmZZ4w18Ym", "merchant_id": "merchant_1756906013", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 6540, "amount_received": null, "connector": "razorpay", "client_secret": "pay_d4tMeFMxF4EmZZ4w18Ym_secret_Bj4JWSrDkGDGK3TfKBt1", "created": "2025-09-03T15:36:23.275Z", "currency": "INR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+91" }, "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": "upi", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "su*****@razorpay" } }, "billing": { "address": null, "phone": { "number": "6502530000", "country_code": "+91" }, "email": null } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "IN", "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": "IN", "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": "upi_collect", "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": 1756913783, "expires": 1756917383, "secret": "epk_53d393130e224556b2105520350533ae" }, "manual_retry_allowed": null, "connector_transaction_id": "pay_RDBFdT6qU2bwzC", "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": "order_RDBFcufill32B5", "payment_link": null, "profile_id": "pro_RkdjC1k2ZDLH1wvhSc76", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1cYyVsBadn8UVLK5vI24", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-03T15:51:23.275Z", "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-03T15:36:26.339Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "testing_the_integ03454", "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": "{\"razorpay_payment_id\":\"pay_RDBFdT6qU2bwzC\"}", "enable_partial_authorization": null } ``` **Important Note**: before fix the status was failed as it wasn't able to consume email but now it is correct
v1.116.0
4ab54f3c835de59cc098c8518938c746f4895bd1
4ab54f3c835de59cc098c8518938c746f4895bd1
juspay/hyperswitch
juspay__hyperswitch-9255
Bug: [FEATURE] [SHIFT4] Pass metadata to connector ### Feature Description Pass metadata to connector Shift4 ### Possible Implementation Pass metadata to connector Shift4 ### 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/shift4/transformers.rs b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs index eeaf340e103..98793e691ff 100644 --- a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs @@ -43,6 +43,7 @@ trait Shift4AuthorizePreprocessingCommon { fn get_email_optional(&self) -> Option<pii::Email>; fn get_complete_authorize_url(&self) -> Option<String>; fn get_currency_required(&self) -> Result<enums::Currency, Error>; + fn get_metadata(&self) -> Result<Option<serde_json::Value>, Error>; fn get_payment_method_data_required(&self) -> Result<PaymentMethodData, Error>; } @@ -88,6 +89,12 @@ impl Shift4AuthorizePreprocessingCommon for PaymentsAuthorizeData { fn get_router_return_url(&self) -> Option<String> { self.router_return_url.clone() } + + fn get_metadata( + &self, + ) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> { + Ok(self.metadata.clone()) + } } impl Shift4AuthorizePreprocessingCommon for PaymentsPreProcessingData { @@ -117,12 +124,18 @@ impl Shift4AuthorizePreprocessingCommon for PaymentsPreProcessingData { fn get_router_return_url(&self) -> Option<String> { self.router_return_url.clone() } + fn get_metadata( + &self, + ) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> { + Ok(None) + } } #[derive(Debug, Serialize)] pub struct Shift4PaymentsRequest { amount: MinorUnit, currency: enums::Currency, captured: bool, + metadata: Option<serde_json::Value>, #[serde(flatten)] payment_method: Shift4PaymentMethod, } @@ -275,11 +288,13 @@ where let submit_for_settlement = item.router_data.request.is_automatic_capture()?; let amount = item.amount.to_owned(); let currency = item.router_data.request.get_currency_required()?; + let metadata = item.router_data.request.get_metadata()?; let payment_method = Shift4PaymentMethod::try_from(item.router_data)?; Ok(Self { amount, currency, captured: submit_for_settlement, + metadata, payment_method, }) } @@ -641,9 +656,11 @@ impl<T> TryFrom<&Shift4RouterData<&RouterData<T, CompleteAuthorizeData, Payments Some(PaymentMethodData::Card(_)) => { let card_token: Shift4CardToken = to_connector_meta(item.router_data.request.connector_meta.clone())?; + let metadata = item.router_data.request.metadata.clone(); Ok(Self { amount: item.amount.to_owned(), currency: item.router_data.request.currency, + metadata, payment_method: Shift4PaymentMethod::CardsNon3DSRequest(Box::new( CardsNon3DSRequest { card: CardPayment::CardToken(card_token.id),
2025-09-03T09:33: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 --> Pass metadata to connector Shift4. ### 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/9255 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Payment Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_eJHaeshBvRK6V5mOAoloL5aRczu82zuQt41YvafbbOxn5nDxMNIHOWsJ5TDCT8dJ' \ --data-raw '{ "amount": 5556, "currency": "USD", "confirm": true, "profile_id": "pro_mId6vzqmEh4dUmJyLRSI", "authentication_type": "no_three_ds", "customer": { "id": "deepanshu", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "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": "4012001800000016", "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]" }, "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" }, "metadata": { "order_id": "ORD-12345", "customer_segment": "premium", "purchase_platform": "web_store" } }' ``` Payment Response: ``` { "payment_id": "pay_Xb9hjoMzOeSqH14S1HXy", "merchant_id": "merchant_1756889332", "status": "succeeded", "amount": 5556, "net_amount": 5556, "shipping_cost": null, "amount_capturable": 0, "amount_received": 5556, "connector": "shift4", "client_secret": "pay_Xb9hjoMzOeSqH14S1HXy_secret_EYxCuRxvHkZu7WyJW1Hh", "created": "2025-09-03T09:34:00.407Z", "currency": "USD", "customer_id": "deepanshu", "customer": { "id": "deepanshu", "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": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "0016", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "401200", "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": "token_whphrdy66T0EROtSP61h", "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": "[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": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "deepanshu", "created_at": 1756892040, "expires": 1756895640, "secret": "epk_00a0b91c83104def83f9758c18ee9034" }, "manual_retry_allowed": false, "connector_transaction_id": "char_pBsemSHNsodexllVdUWYvyUi", "frm_message": null, "metadata": { "order_id": "ORD-12345", "customer_segment": "premium", "purchase_platform": "web_store" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "char_pBsemSHNsodexllVdUWYvyUi", "payment_link": null, "profile_id": "pro_mId6vzqmEh4dUmJyLRSI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_lLEdkj8jX102T4hpRpLE", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-03T09:49:00.407Z", "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-03T09:34:01.500Z", "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 } ``` Shift4 Dashboard: <img width="1955" height="217" alt="image" src="https://github.com/user-attachments/assets/47fb3ce8-0687-41f1-990b-2d8c30e8b65f" /> Cypress: <img width="822" height="1071" alt="image" src="https://github.com/user-attachments/assets/af192e95-66a5-49d6-a0f7-7960b8e1e76a" /> ## 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
v1.116.0
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
juspay/hyperswitch
juspay__hyperswitch-9257
Bug: [BUG] Enable nuvei applepay googlepay mandate features in sbx , prod and integ Update .toml files for sbx, prod and integ to enable mandates for applae pay and google_pay
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 0867ca7014a..15f3233e175 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -233,9 +233,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,nuvei,authorizedotnet,wellsfargo" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,nuvei,authorizedotnet,wellsfargo" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 20040502e11..124a31113df 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -233,9 +233,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,nuvei,authorizedotnet,wellsfargo" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,nuvei,authorizedotnet,wellsfargo" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 23a362581e9..4fe6332572b 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -240,9 +240,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,archipel,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo,worldpayvantiv" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,nuvei,authorizedotnet,wellsfargo,worldpayvantiv" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo,worldpayvantiv" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,nuvei,authorizedotnet,wellsfargo,worldpayvantiv" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index fbe2be161fa..8dbbd2aadaa 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1003,8 +1003,8 @@ bank_redirect.open_banking_uk.connector_list = "adyen" [mandates.supported_payment_methods] pay_later.klarna = { connector_list = "adyen,aci" } -wallet.google_pay = { connector_list = "stripe,cybersource,adyen,bankofamerica,authorizedotnet,noon,novalnet,multisafepay,wellsfargo" } -wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet,novalnet,multisafepay,wellsfargo" } +wallet.google_pay = { connector_list = "stripe,cybersource,adyen,bankofamerica,authorizedotnet,noon,novalnet,multisafepay,wellsfargo,nuvei" } +wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet,novalnet,multisafepay,wellsfargo,nuvei" } wallet.samsung_pay = { connector_list = "cybersource" } wallet.paypal = { connector_list = "adyen,novalnet,authorizedotnet" } card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,elavon,xendit,novalnet,bamboraapac,archipel,wellsfargo,worldpayvantiv,payload" }
2025-09-03T09:38:46Z
## 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 apple_pay and google_pay mandate support for nuvei in integ,sbx and prod ( updation of config files) Parent pr : https://github.com/juspay/hyperswitch/pull/9081 Refer test cases with above pr ### 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
v1.116.0
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
juspay/hyperswitch
juspay__hyperswitch-9250
Bug: fix(users): Add Bad request response in openidconnect Currently, when users provide an invalid or expired code during SSO login, the system returns a 500 response. This is misleading, as the issue is with the client input rather than a server error. This change introduces a proper 400 BadRequest response to better reflect the actual problem and improve error handling.
diff --git a/crates/router/src/services/openidconnect.rs b/crates/router/src/services/openidconnect.rs index ca20b021a56..69b890d657e 100644 --- a/crates/router/src/services/openidconnect.rs +++ b/crates/router/src/services/openidconnect.rs @@ -76,7 +76,14 @@ pub async fn get_user_email_from_oidc_provider( .exchange_code(oidc::AuthorizationCode::new(authorization_code.expose())) .request_async(|req| get_oidc_reqwest_client(state, req)) .await - .change_context(UserErrors::InternalServerError) + .map_err(|e| match e { + oidc::RequestTokenError::ServerResponse(resp) + if resp.error() == &oidc_core::CoreErrorResponseType::InvalidGrant => + { + UserErrors::SSOFailed + } + _ => UserErrors::InternalServerError, + }) .attach_printable("Failed to exchange code and fetch oidc token")?; // Fetch id token from response
2025-09-02T13:29:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added a BadRequest response for SSO login when an invalid authorization code is provided. <!-- Describe your changes in detail --> ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Currently, when users provide an invalid or expired code during SSO login, the system returns a 500 response. This is misleading, as the issue is with the client input rather than a server error. This change introduces a proper 400 BadRequest response to better reflect the actual problem and improve error handling. <!-- 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? ```sh curl --location '<BASE URL>/user/oidc' \ --header 'Content-Type: application/json' \ --data '{ "state": "<correct state>", "code": "<wrong code>" }' ``` This should give `400` instead of 500. <!-- 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
v1.116.0
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
juspay/hyperswitch
juspay__hyperswitch-9247
Bug: [FEATURE]:[PAYSAFE] Integrate no 3ds card Integrate Paysafe connector - No 3ds Cards Flows - Payment - Psync - Capture - Void - Refund - Refund Sync
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 3a94e620897..906859f016b 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -12059,6 +12059,7 @@ "payme", "payone", "paypal", + "paysafe", "paystack", "paytm", "payu", @@ -30074,6 +30075,7 @@ "payload", "payone", "paypal", + "paysafe", "paystack", "paytm", "payu", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 4cf8b42437e..7158928d3ad 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8603,6 +8603,7 @@ "payme", "payone", "paypal", + "paysafe", "paystack", "paytm", "payu", @@ -23759,6 +23760,7 @@ "payload", "payone", "paypal", + "paysafe", "paystack", "paytm", "payu", diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 20040502e11..da17d2d3ff0 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -117,7 +117,7 @@ payload.base_url = "https://api.payload.com" payme.base_url = "https://live.payme.io/" payone.base_url = "https://payment.payone.com/" paypal.base_url = "https://api-m.paypal.com/" -paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" +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/" diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 8b1c9e2f9eb..b040182ac7e 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -132,6 +132,7 @@ pub enum RoutableConnectors { Payload, Payone, Paypal, + Paysafe, Paystack, Paytm, Payu, @@ -308,6 +309,7 @@ pub enum Connector { Payme, Payone, Paypal, + Paysafe, Paystack, Paytm, Payu, @@ -496,6 +498,7 @@ impl Connector { | Self::Payme | Self::Payone | Self::Paypal + | Self::Paysafe | Self::Paystack | Self::Payu | Self::Placetopay @@ -670,6 +673,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Payme => Self::Payme, RoutableConnectors::Payone => Self::Payone, RoutableConnectors::Paypal => Self::Paypal, + RoutableConnectors::Paysafe => Self::Paysafe, RoutableConnectors::Paystack => Self::Paystack, RoutableConnectors::Payu => Self::Payu, RoutableConnectors::Placetopay => Self::Placetopay, @@ -803,6 +807,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Payme => Ok(Self::Payme), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), + Connector::Paysafe => Ok(Self::Paysafe), Connector::Paystack => Ok(Self::Paystack), Connector::Payu => Ok(Self::Payu), Connector::Placetopay => Ok(Self::Placetopay), diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index 78f85c82577..b54d9e86da8 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -110,6 +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>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index e67a8136684..18da6b52498 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -149,6 +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>, } #[serde_with::skip_serializing_none] @@ -481,6 +482,7 @@ impl ConnectorConfig { Connector::Payme => Ok(connector_data.payme), Connector::Payone => Err("Use get_payout_connector_config".to_string()), Connector::Paypal => Ok(connector_data.paypal), + Connector::Paysafe => Ok(connector_data.paysafe), Connector::Paystack => Ok(connector_data.paystack), Connector::Payu => Ok(connector_data.payu), Connector::Placetopay => Ok(connector_data.placetopay), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index ded3ee24bfd..864b220688f 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6718,5 +6718,50 @@ api_key = "Password" key1 = "Username" [paysafe] -[paysafe.connector_auth.HeaderKey] -api_key = "API Key" +[[paysafe.credit]] +payment_method_type = "Mastercard" +[[paysafe.credit]] +payment_method_type = "Visa" +[[paysafe.credit]] +payment_method_type = "Interac" +[[paysafe.credit]] +payment_method_type = "AmericanExpress" +[[paysafe.credit]] +payment_method_type = "JCB" +[[paysafe.credit]] +payment_method_type = "DinersClub" +[[paysafe.credit]] +payment_method_type = "Discover" +[[paysafe.credit]] +payment_method_type = "CartesBancaires" +[[paysafe.credit]] +payment_method_type = "UnionPay" +[[paysafe.debit]] +payment_method_type = "Mastercard" +[[paysafe.debit]] +payment_method_type = "Visa" +[[paysafe.debit]] +payment_method_type = "Interac" +[[paysafe.debit]] +payment_method_type = "AmericanExpress" +[[paysafe.debit]] +payment_method_type = "JCB" +[[paysafe.debit]] +payment_method_type = "DinersClub" +[[paysafe.debit]] +payment_method_type = "Discover" +[[paysafe.debit]] +payment_method_type = "CartesBancaires" +[[paysafe.debit]] +payment_method_type = "UnionPay" +[paysafe.connector_auth.BodyKey] +api_key = "Username" +key1 = "Password" +[paysafe.connector_webhook_details] +merchant_secret = "Source verification key" +[paysafe.metadata.account_id] +name="account_id" +label="Payment Method Account ID" +placeholder="Enter Account ID" +required=true +type="Text" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index c0332a75daa..2f9ef9019de 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5387,5 +5387,50 @@ api_key = "Password" key1 = "Username" [paysafe] -[paysafe.connector_auth.HeaderKey] -api_key = "API Key" +[[paysafe.credit]] +payment_method_type = "Mastercard" +[[paysafe.credit]] +payment_method_type = "Visa" +[[paysafe.credit]] +payment_method_type = "Interac" +[[paysafe.credit]] +payment_method_type = "AmericanExpress" +[[paysafe.credit]] +payment_method_type = "JCB" +[[paysafe.credit]] +payment_method_type = "DinersClub" +[[paysafe.credit]] +payment_method_type = "Discover" +[[paysafe.credit]] +payment_method_type = "CartesBancaires" +[[paysafe.credit]] +payment_method_type = "UnionPay" +[[paysafe.debit]] +payment_method_type = "Mastercard" +[[paysafe.debit]] +payment_method_type = "Visa" +[[paysafe.debit]] +payment_method_type = "Interac" +[[paysafe.debit]] +payment_method_type = "AmericanExpress" +[[paysafe.debit]] +payment_method_type = "JCB" +[[paysafe.debit]] +payment_method_type = "DinersClub" +[[paysafe.debit]] +payment_method_type = "Discover" +[[paysafe.debit]] +payment_method_type = "CartesBancaires" +[[paysafe.debit]] +payment_method_type = "UnionPay" +[paysafe.connector_auth.BodyKey] +api_key = "Username" +key1 = "Password" +[paysafe.connector_webhook_details] +merchant_secret = "Source verification key" +[paysafe.metadata.account_id] +name="account_id" +label="Payment Method Account ID" +placeholder="Enter Account ID" +required=true +type="Text" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 7f95cd02c50..89d5f539e73 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6701,5 +6701,50 @@ api_key = "Password" key1 = "Username" [paysafe] -[paysafe.connector_auth.HeaderKey] -api_key = "API Key" +[[paysafe.credit]] +payment_method_type = "Mastercard" +[[paysafe.credit]] +payment_method_type = "Visa" +[[paysafe.credit]] +payment_method_type = "Interac" +[[paysafe.credit]] +payment_method_type = "AmericanExpress" +[[paysafe.credit]] +payment_method_type = "JCB" +[[paysafe.credit]] +payment_method_type = "DinersClub" +[[paysafe.credit]] +payment_method_type = "Discover" +[[paysafe.credit]] +payment_method_type = "CartesBancaires" +[[paysafe.credit]] +payment_method_type = "UnionPay" +[[paysafe.debit]] +payment_method_type = "Mastercard" +[[paysafe.debit]] +payment_method_type = "Visa" +[[paysafe.debit]] +payment_method_type = "Interac" +[[paysafe.debit]] +payment_method_type = "AmericanExpress" +[[paysafe.debit]] +payment_method_type = "JCB" +[[paysafe.debit]] +payment_method_type = "DinersClub" +[[paysafe.debit]] +payment_method_type = "Discover" +[[paysafe.debit]] +payment_method_type = "CartesBancaires" +[[paysafe.debit]] +payment_method_type = "UnionPay" +[paysafe.connector_auth.BodyKey] +api_key = "Username" +key1 = "Password" +[paysafe.connector_webhook_details] +merchant_secret = "Source verification key" +[paysafe.metadata.account_id] +name="account_id" +label="Payment Method Account ID" +placeholder="Enter 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 fc76cece514..64296c2ebe6 100644 --- a/crates/hyperswitch_connectors/src/connectors/paysafe.rs +++ b/crates/hyperswitch_connectors/src/connectors/paysafe.rs @@ -2,33 +2,39 @@ 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, 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}, + payments::{ + Authorize, Capture, PSync, PaymentMethodToken, PreProcessing, Session, SetupMandate, + Void, + }, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, 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, + PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData, + RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -42,20 +48,24 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; +use masking::{Mask, PeekInterface}; use transformers as paysafe; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{self, RefundsRequestData as OtherRefundsRequestData}, +}; #[derive(Clone)] pub struct Paysafe { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Paysafe { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &MinorUnitForConnector, } } } @@ -76,7 +86,6 @@ impl api::PaymentToken for Paysafe {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Paysafe { - // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paysafe @@ -121,9 +130,11 @@ impl ConnectorCommon for Paysafe { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = paysafe::PaysafeAuthType::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(), )]) } @@ -140,11 +151,29 @@ impl ConnectorCommon for Paysafe { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let detail_message = response + .error + .details + .as_ref() + .and_then(|d| d.first().cloned()); + let field_error_message = response + .error + .field_errors + .as_ref() + .and_then(|f| f.first().map(|fe| fe.error.clone())); + + let reason = match (detail_message, field_error_message) { + (Some(detail), Some(field)) => Some(format!("{detail}, {field}")), + (Some(detail), None) => Some(detail), + (None, Some(field)) => Some(field), + (None, None) => Some(response.error.message.clone()), + }; + Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response.error.code, + message: response.error.message, + reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, @@ -156,20 +185,6 @@ impl ConnectorCommon for Paysafe { } impl ConnectorValidation for Paysafe { - 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, @@ -187,7 +202,121 @@ impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> fo impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paysafe {} -impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paysafe {} +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paysafe { + // Not Implemented (R) + fn build_request( + &self, + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err( + errors::ConnectorError::NotImplemented("Setup Mandate flow for Paysafe".to_string()) + .into(), + ) + } +} + +impl api::PaymentsPreProcessing for Paysafe {} + +impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> + for Paysafe +{ + fn get_headers( + &self, + req: &PaymentsPreProcessingRouterData, + 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: &PaymentsPreProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}v1/paymenthandles", self.base_url(connectors),)) + } + + fn get_request_body( + &self, + req: &PaymentsPreProcessingRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let minor_amount = + req.request + .minor_amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "minor_amount", + })?; + let currency = + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?; + let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?; + + let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); + let connector_req = paysafe::PaysafePaymentHandleRequest::try_from(&connector_router_data)?; + + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsPreProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPreProcessingType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPreProcessingType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsPreProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: paysafe::PaysafePaymentHandleResponse = res + .response + .parse_struct("PaysafePaymentHandleResponse") + .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<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paysafe { fn get_headers( @@ -205,9 +334,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!("{}v1/payments", self.base_url(connectors),)) } fn get_request_body( @@ -291,10 +420,15 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pay 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_payment_id = req.connector_request_reference_id.clone(); + Ok(format!( + "{}v1/payments?merchantRefNum={}", + self.base_url(connectors), + connector_payment_id + )) } fn build_request( @@ -318,9 +452,9 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pay event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: paysafe::PaysafePaymentsResponse = res + let response: paysafe::PaysafePaymentsSyncResponse = res .response - .parse_struct("paysafe PaymentsSyncResponse") + .parse_struct("paysafe PaysafePaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -355,18 +489,31 @@ 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_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}v1/payments/{}/settlements", + self.base_url(connectors), + connector_payment_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 = paysafe::PaysafeRouterData::from((amount, req)); + let connector_req = paysafe::PaysafeCaptureRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -395,9 +542,9 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: paysafe::PaysafePaymentsResponse = res + let response: paysafe::PaysafeSettlementResponse = res .response - .parse_struct("Paysafe PaymentsCaptureResponse") + .parse_struct("PaysafeSettlementResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -417,7 +564,97 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paysafe {} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paysafe { + fn get_headers( + &self, + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}v1/payments/{}/voidauths", + self.base_url(connectors), + connector_payment_id + )) + } + + fn get_request_body( + &self, + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let minor_amount = + req.request + .minor_amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "minor_amount", + })?; + let currency = + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?; + let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?; + + let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); + let connector_req = paysafe::PaysafeCaptureRequest::try_from(&connector_router_data)?; + 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::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: &PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + let response: paysafe::VoidResponse = res + .response + .parse_struct("PaysafeVoidResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paysafe { fn get_headers( @@ -434,10 +671,15 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paysafe 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()) + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}v1/settlements/{}/refunds", + self.base_url(connectors), + connector_payment_id + )) } fn get_request_body( @@ -518,10 +760,15 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paysafe { 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 connector_refund_id = req.request.get_connector_refund_id()?; + Ok(format!( + "{}v1/refunds/{}", + self.base_url(connectors), + connector_refund_id + )) } fn build_request( @@ -594,12 +841,70 @@ impl webhooks::IncomingWebhook for Paysafe { } } -static PAYSAFE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = - LazyLock::new(SupportedPaymentMethods::new); +static PAYSAFE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut paysafe_supported_payment_methods = SupportedPaymentMethods::new(); + + paysafe_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + paysafe_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + paysafe_supported_payment_methods +}); static PAYSAFE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Paysafe", - description: "Paysafe connector", + description: "Paysafe gives ambitious businesses a launchpad with safe, secure online payment solutions, and gives consumers the ability to turn their transactions into meaningful experiences.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs index f1a7dbdc237..50c665a65bd 100644 --- a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs @@ -1,28 +1,43 @@ +use cards::CardNumber; use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_utils::{ + pii::{IpAddress, SecretSerdeValue}, + request::Method, + 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_request_types::ResponseId, + router_request_types::{ + PaymentsAuthorizeData, PaymentsPreProcessingData, PaymentsSyncData, ResponseId, + }, router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsPreProcessingRouterData, RefundsRouterData, + }, }; use hyperswitch_interfaces::errors; -use masking::Secret; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; -use crate::types::{RefundsResponseRouterData, ResponseRouterData}; +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{ + self, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, + PaymentsPreProcessingRequestData, RouterData as _, + }, +}; -//TODO: Fill the struct with respective fields pub struct PaysafeRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } -impl<T> From<(StringMinorUnit, T)> for PaysafeRouterData<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<(MinorUnit, T)> for PaysafeRouterData<T> { + fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, @@ -30,20 +45,273 @@ impl<T> From<(StringMinorUnit, T)> for PaysafeRouterData<T> { } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct PaysafeConnectorMetadataObject { + pub account_id: 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> { + 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) + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafePaymentHandleRequest { + pub merchant_ref_num: String, + pub amount: MinorUnit, + pub settle_with_auth: bool, + pub card: PaysafeCard, + pub currency_code: enums::Currency, + pub payment_type: PaysafePaymentType, + pub transaction_type: TransactionType, + pub return_links: Vec<ReturnLink>, + pub account_id: Secret<String>, +} + +#[derive(Debug, Serialize)] +pub struct ReturnLink { + pub rel: LinkType, + pub href: String, + pub method: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinkType { + OnCompleted, + OnFailed, + OnCancelled, + Default, +} + +#[derive(Debug, Serialize)] +pub enum PaysafePaymentType { + #[serde(rename = "CARD")] + Card, +} + +#[derive(Debug, Serialize)] +pub enum TransactionType { + #[serde(rename = "PAYMENT")] + Payment, +} + +impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePaymentHandleRequest { + type Error = error_stack::Report<errors::ConnectorError>; + 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", + })?; + 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 account_id = metadata.account_id; + + 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 + ), + card, + currency_code: item.router_data.request.get_currency()?, + payment_type, + transaction_type, + return_links, + account_id, + }) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + ))?, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafePaymentHandleResponse { + pub id: String, + pub merchant_ref_num: String, + pub payment_handle_token: Secret<String>, + pub status: PaysafePaymentHandleStatus, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum PaysafePaymentHandleStatus { + Initiated, + Payable, + #[default] + Processing, + Failed, + Expired, + Completed, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PaysafeMeta { + pub payment_handle_token: Secret<String>, +} + +impl<F> + TryFrom< + ResponseRouterData< + F, + PaysafePaymentHandleResponse, + PaymentsPreProcessingData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + PaysafePaymentHandleResponse, + PaymentsPreProcessingData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + preprocessing_id: Some( + item.response + .payment_handle_token + .to_owned() + .peek() + .to_string(), + ), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + 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 + }) + } +} + +impl<F> + TryFrom< + ResponseRouterData<F, PaysafePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>, + > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + PaysafePaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: get_paysafe_payment_status( + item.response.status, + item.data.request.capture_method, + ), + 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 + }) + } +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct PaysafePaymentsRequest { - amount: StringMinorUnit, - card: PaysafeCard, + pub merchant_ref_num: String, + pub amount: MinorUnit, + pub settle_with_auth: bool, + pub payment_handle_token: Secret<String>, + pub currency_code: enums::Currency, + pub customer_ip: Option<Secret<String, IpAddress>>, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct PaysafeCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, + pub card_num: CardNumber, + pub card_expiry: PaysafeCardExpiry, + #[serde(skip_serializing_if = "Option::is_none")] + pub cvv: Option<Secret<String>>, + pub holder_name: Option<Secret<String>>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaysafeCardExpiry { + pub month: Secret<String>, + pub year: Secret<String>, } impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentsRequest { @@ -51,72 +319,278 @@ impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymen fn try_from( item: &PaysafeRouterData<&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()), - } + if item.router_data.is_three_ds() { + Err(errors::ConnectorError::NotSupported { + message: "Card 3DS".to_string(), + connector: "Paysafe", + })? + }; + let payment_handle_token = Secret::new(item.router_data.get_preprocessing_id()?); + let amount = item.amount; + let customer_ip = Some( + item.router_data + .request + .get_browser_info()? + .get_ip_address()?, + ); + + Ok(Self { + merchant_ref_num: item.router_data.connector_request_reference_id.clone(), + payment_handle_token, + amount, + settle_with_auth: item.router_data.request.is_auto_capture()?, + currency_code: item.router_data.request.currency, + customer_ip, + }) } } -//TODO: Fill the struct with respective fields -// Auth Struct pub struct PaysafeAuthType { - pub(super) api_key: Secret<String>, + pub(super) username: Secret<String>, + pub(super) password: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PaysafeAuthType { 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 { + username: api_key.to_owned(), + password: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags + +// Paysafe Payment Status #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] +#[serde(rename_all = "UPPERCASE")] pub enum PaysafePaymentStatus { - Succeeded, + Received, + Completed, + Held, Failed, #[default] + Pending, + Cancelled, Processing, } -impl From<PaysafePaymentStatus> for common_enums::AttemptStatus { - fn from(item: PaysafePaymentStatus) -> Self { +pub fn get_paysafe_payment_status( + status: PaysafePaymentStatus, + capture_method: Option<common_enums::CaptureMethod>, +) -> common_enums::AttemptStatus { + match status { + PaysafePaymentStatus::Completed => match capture_method { + Some(common_enums::CaptureMethod::Manual) => common_enums::AttemptStatus::Authorized, + Some(common_enums::CaptureMethod::Automatic) | None => { + common_enums::AttemptStatus::Charged + } + Some(common_enums::CaptureMethod::SequentialAutomatic) + | Some(common_enums::CaptureMethod::ManualMultiple) + | Some(common_enums::CaptureMethod::Scheduled) => { + common_enums::AttemptStatus::Unresolved + } + }, + PaysafePaymentStatus::Failed => common_enums::AttemptStatus::Failure, + PaysafePaymentStatus::Pending + | PaysafePaymentStatus::Processing + | PaysafePaymentStatus::Received + | PaysafePaymentStatus::Held => common_enums::AttemptStatus::Pending, + PaysafePaymentStatus::Cancelled => common_enums::AttemptStatus::Voided, + } +} + +// Paysafe Payments Response Structure +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafePaymentsSyncResponse { + pub payments: Vec<PaysafePaymentsResponse>, +} + +// Paysafe Payments Response Structure +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +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)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeSettlementResponse { + pub merchant_ref_num: Option<String>, + pub id: String, + pub status: PaysafeSettlementStatus, +} + +impl<F> + TryFrom< + ResponseRouterData<F, PaysafePaymentsSyncResponse, PaymentsSyncData, PaymentsResponseData>, + > for RouterData<F, PaymentsSyncData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + PaysafePaymentsSyncResponse, + PaymentsSyncData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let payment_handle = item + .response + .payments + .first() + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(Self { + status: get_paysafe_payment_status( + payment_handle.status, + item.data.request.capture_method, + ), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + 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 + }) + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaysafeCaptureRequest { + pub merchant_ref_num: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option<MinorUnit>, +} + +impl TryFrom<&PaysafeRouterData<&PaymentsCaptureRouterData>> for PaysafeCaptureRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaysafeRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { + let amount = Some(item.amount); + + Ok(Self { + merchant_ref_num: item.router_data.connector_request_reference_id.clone(), + amount, + }) + } +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum PaysafeSettlementStatus { + Received, + Initiated, + Completed, + Expired, + Failed, + #[default] + Pending, + Cancelled, +} + +impl From<PaysafeSettlementStatus> for common_enums::AttemptStatus { + fn from(item: PaysafeSettlementStatus) -> Self { match item { - PaysafePaymentStatus::Succeeded => Self::Charged, - PaysafePaymentStatus::Failed => Self::Failure, - PaysafePaymentStatus::Processing => Self::Authorizing, + PaysafeSettlementStatus::Completed + | PaysafeSettlementStatus::Pending + | PaysafeSettlementStatus::Received => Self::Charged, + PaysafeSettlementStatus::Failed | PaysafeSettlementStatus::Expired => Self::Failure, + PaysafeSettlementStatus::Cancelled => Self::Voided, + PaysafeSettlementStatus::Initiated => Self::Pending, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct PaysafePaymentsResponse { - status: PaysafePaymentStatus, - id: String, +impl<F, T> TryFrom<ResponseRouterData<F, PaysafeSettlementResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, PaysafeSettlementResponse, 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.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 + }) + } +} + +impl TryFrom<&PaysafeRouterData<&PaymentsCancelRouterData>> for PaysafeCaptureRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaysafeRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> { + let amount = Some(item.amount); + + Ok(Self { + merchant_ref_num: item.router_data.connector_request_reference_id.clone(), + amount, + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct VoidResponse { + pub merchant_ref_num: Option<String>, + pub id: String, + pub status: PaysafeVoidStatus, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum PaysafeVoidStatus { + Received, + Completed, + Held, + Failed, + #[default] + Pending, + Cancelled, +} + +impl From<PaysafeVoidStatus> for common_enums::AttemptStatus { + fn from(item: PaysafeVoidStatus) -> Self { + match item { + PaysafeVoidStatus::Completed + | PaysafeVoidStatus::Pending + | PaysafeVoidStatus::Received => Self::Voided, + PaysafeVoidStatus::Failed | PaysafeVoidStatus::Held => Self::Failure, + PaysafeVoidStatus::Cancelled => Self::Voided, + } + } } -impl<F, T> TryFrom<ResponseRouterData<F, PaysafePaymentsResponse, T, PaymentsResponseData>> +impl<F, T> TryFrom<ResponseRouterData<F, VoidResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, PaysafePaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, VoidResponse, 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), + resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, @@ -130,46 +604,50 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaysafePaymentsResponse, T, PaymentsRes } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct PaysafeRefundRequest { - pub amount: StringMinorUnit, + pub merchant_ref_num: String, + pub amount: MinorUnit, } impl<F> TryFrom<&PaysafeRouterData<&RefundsRouterData<F>>> for PaysafeRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaysafeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + let amount = item.amount; + Ok(Self { - amount: item.amount.to_owned(), + merchant_ref_num: item.router_data.request.refund_id.clone(), + amount, }) } } // Type definition for Refund Response -#[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] +#[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { - Succeeded, + Received, + Initiated, + Completed, + Expired, Failed, #[default] - Processing, + Pending, + Cancelled, } 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 + RefundStatus::Received | RefundStatus::Completed => Self::Success, + RefundStatus::Failed | RefundStatus::Cancelled | RefundStatus::Expired => Self::Failure, + RefundStatus::Pending | RefundStatus::Initiated => Self::Pending, } } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, @@ -206,14 +684,22 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouter } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Serialize, Deserialize)] pub struct PaysafeErrorResponse { - pub status_code: u16, + pub error: Error, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Error { 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>, + pub details: Option<Vec<String>>, + #[serde(rename = "fieldErrors")] + pub field_errors: Option<Vec<FieldError>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FieldError { + pub field: String, + pub error: String, } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 8b87e0c098a..0535088c884 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -1664,7 +1664,6 @@ macro_rules! default_imp_for_pre_processing_steps{ } default_imp_for_pre_processing_steps!( - connectors::Paysafe, connectors::Trustpayments, connectors::Silverflow, connectors::Vgs, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index d34cb480800..edc6e5a42bb 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -2411,6 +2411,7 @@ pub trait PaymentsPreProcessingRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn connector_mandate_id(&self) -> Option<String>; + fn get_payment_method_data(&self) -> Result<PaymentMethodData, Error>; } impl PaymentsPreProcessingRequestData for PaymentsPreProcessingData { @@ -2422,6 +2423,11 @@ impl PaymentsPreProcessingRequestData for PaymentsPreProcessingData { .to_owned() .ok_or_else(missing_field_err("payment_method_type")) } + fn get_payment_method_data(&self) -> Result<PaymentMethodData, Error> { + self.payment_method_data + .to_owned() + .ok_or_else(missing_field_err("payment_method_data")) + } fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index 69e8cf96218..77e51e63f38 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -396,6 +396,13 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { paypal::transformers::PaypalAuthType::try_from(self.auth_type)?; Ok(()) } + api_enums::Connector::Paysafe => { + paysafe::transformers::PaysafeAuthType::try_from(self.auth_type)?; + paysafe::transformers::PaysafeConnectorMetadataObject::try_from( + self.connector_meta_data, + )?; + Ok(()) + } api_enums::Connector::Payone => { payone::transformers::PayoneAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a87d22191b6..7db83c383d8 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -6593,6 +6593,14 @@ where router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) + } else if connector.connector_name == router_types::Connector::Paysafe + && router_data.auth_type == storage_enums::AuthenticationType::NoThreeDs + { + 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 if (connector.connector_name == router_types::Connector::Cybersource || connector.connector_name == router_types::Connector::Barclaycard) && is_operation_complete_authorize(&operation) diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index 2f93feba334..0e809c628f1 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -424,6 +424,9 @@ impl ConnectorData { enums::Connector::Paypal => { Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new()))) } + enums::Connector::Paysafe => { + Ok(ConnectorEnum::Old(Box::new(connector::Paysafe::new()))) + } enums::Connector::Paystack => { Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new()))) } diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index 77286011ad0..98e00bc893d 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -343,6 +343,9 @@ impl FeatureMatrixConnectorData { enums::Connector::Paypal => { Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new()))) } + enums::Connector::Paysafe => { + Ok(ConnectorEnum::Old(Box::new(connector::Paysafe::new()))) + } enums::Connector::Paystack => { Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new()))) } diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index 0688b466558..fb43e8b1360 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -110,6 +110,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Payme => Self::Payme, api_enums::Connector::Payone => Self::Payone, api_enums::Connector::Paypal => Self::Paypal, + api_enums::Connector::Paysafe => Self::Paysafe, api_enums::Connector::Paystack => Self::Paystack, api_enums::Connector::Payu => Self::Payu, api_models::enums::Connector::Placetopay => Self::Placetopay, diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 1bf84848e47..f6deae24e20 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -94,7 +94,7 @@ pub struct ConnectorAuthentication { pub payme: Option<BodyKey>, pub payone: Option<HeaderKey>, pub paypal: Option<BodyKey>, - pub paysafe: Option<HeaderKey>, + pub paysafe: Option<BodyKey>, pub paystack: Option<HeaderKey>, pub paytm: Option<HeaderKey>, pub payu: Option<BodyKey>,
2025-09-01T09:55:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Integrate Paysafe connector - No 3ds Cards Flows - Payment - Psync - Capture - Void - Refund - Refund Sync ### 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 Paysafe connector ``` curl --location 'http://localhost:8080/account/merchant_1756845023/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: _' \ --data '{ "connector_type": "payment_processor", "connector_name": "paysafe", "business_country": "US", "business_label": "food", "connector_account_details": { "auth_type": "BodyKey", "api_key": "**", "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 } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, ], "metadata": { "report_group" : "Hello", "merchant_config_currency":"USD", "account_id": "_____" } }' ``` Create a Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: _' \ --data '{ "amount": 1500, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "payment_method": "card", "payment_method_type": "credit", "profile_id": "pro_Dpwkpk5tMI4H6ZdYjpEW", "payment_method_data": { "card": { "card_number": "4530910000012345", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph", "card_cvc": "111" } }, "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" } }, "shipping": { "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" } }, "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_PGOFJN06yH9nEglswyFF", "merchant_id": "merchant_1756845023", "status": "succeeded", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1500, "connector": "paysafe", "client_secret": "pay_PGOFJN06yH9nEglswyFF_secret_UdTEHyTjQIGYtgESFnqe", "created": "2025-09-02T20:31:17.873Z", "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": "card", "payment_method_data": { "card": { "last4": "2345", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453091", "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": "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": "aaaa", "created_at": 1756845077, "expires": 1756848677, "secret": "epk_6ed44431aa3048fc87756aba02f4deb7" }, "manual_retry_allowed": false, "connector_transaction_id": "09ef3d4c-ef25-4234-b6a7-f0e074b16fa0", "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_Dpwkpk5tMI4H6ZdYjpEW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_pliYtewxLmWuyNqYCjxg", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-02T20:46:17.873Z", "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-02T20:31:19.281Z", "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 } ``` Create a Payment with capture_method as manual - Response ``` { "payment_id": "pay_NtJnAOrMkNpnmUFaSP3P", "merchant_id": "merchant_1756845023", "status": "requires_capture", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 1500, "amount_received": null, "connector": "paysafe", "client_secret": "pay_NtJnAOrMkNpnmUFaSP3P_secret_ScE2jv35Tp7z2ors0vSN", "created": "2025-09-02T20:59:00.726Z", "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": "2345", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453091", "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": "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": "aaaa", "created_at": 1756846740, "expires": 1756850340, "secret": "epk_725012e7f4524681a43c922269d96501" }, "manual_retry_allowed": false, "connector_transaction_id": "7b6151d0-a81c-4dea-8c65-72053993f1a0", "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_Dpwkpk5tMI4H6ZdYjpEW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_pliYtewxLmWuyNqYCjxg", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-02T21:14:00.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-02T20:59:02.385Z", "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 } ``` Capture the payment Response ``` { "payment_id": "pay_NtJnAOrMkNpnmUFaSP3P", "merchant_id": "merchant_1756845023", "status": "succeeded", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1500, "connector": "paysafe", "client_secret": "pay_NtJnAOrMkNpnmUFaSP3P_secret_ScE2jv35Tp7z2ors0vSN", "created": "2025-09-02T20:59:00.726Z", "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": "2345", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453091", "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": "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": "f1063df1-4f29-433c-a97f-f9b3d32dac5d", "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_Dpwkpk5tMI4H6ZdYjpEW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_pliYtewxLmWuyNqYCjxg", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-02T21:14:00.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-02T20:59:27.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 } ``` Make one more payment with capture method manual - Then void it Response ``` { "payment_id": "pay_TaErSsfUWajhzursc4jS", "merchant_id": "merchant_1756845023", "status": "cancelled", "amount": 1500, "net_amount": 1500, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "paysafe", "client_secret": "pay_TaErSsfUWajhzursc4jS_secret_l7P3CWNj0vzLmXG6TNiT", "created": "2025-09-02T21:00:32.402Z", "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": "2345", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453091", "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": "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": "2951a54a-c923-48d4-9738-5e16bb440b3e", "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_Dpwkpk5tMI4H6ZdYjpEW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_pliYtewxLmWuyNqYCjxg", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-02T21:15:32.402Z", "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-02T21:00:35.862Z", "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 } ``` Refunds Refunds can only be triggered after sometime, as the payment take some time to settle. according to doc - This process is typically handled in an overnight batch. Cypress <img width="740" height="826" alt="Screenshot 2025-09-04 at 4 45 29 PM" src="https://github.com/user-attachments/assets/1ffe7b71-bc3d-4350-8af9-b7b3cd879b2b" /> <img width="957" height="852" alt="Screenshot 2025-09-08 at 3 57 46 PM" src="https://github.com/user-attachments/assets/e7f144c2-8c20-44b0-84a5-e2b531ec59a4" /> ## 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
v1.116.0
7ad5cd5531eee612d72c938f324c08682359a313
7ad5cd5531eee612d72c938f324c08682359a313
juspay/hyperswitch
juspay__hyperswitch-9128
Bug: [FEATURE] allow wallet data migration ### Feature Description Currently, migration API is card-centric and performs validation assuming all the entries are for migrating cards. These validations make the wallet migration fail. ### Possible Implementation Make card expiry validation optional per payment method type. For now it should be optional for - `PayPal` and `SamsungPay`. ### 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/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs index 5c30698f615..494e1987e21 100644 --- a/crates/payment_methods/src/core/migration/payment_methods.rs +++ b/crates/payment_methods/src/core/migration/payment_methods.rs @@ -51,8 +51,12 @@ pub async fn migrate_payment_method( let card_number_validation_result = cards::CardNumber::from_str(card_details.card_number.peek()); - let card_bin_details = - populate_bin_details_for_masked_card(card_details, &*state.store).await?; + let card_bin_details = populate_bin_details_for_masked_card( + card_details, + &*state.store, + req.payment_method_type.as_ref(), + ) + .await?; req.card = Some(api_models::payment_methods::MigrateCardDetail { card_issuing_country: card_bin_details.issuer_country.clone(), @@ -176,8 +180,23 @@ pub async fn migrate_payment_method( pub async fn populate_bin_details_for_masked_card( card_details: &api_models::payment_methods::MigrateCardDetail, db: &dyn state::PaymentMethodsStorageInterface, + payment_method_type: Option<&enums::PaymentMethodType>, ) -> CustomResult<pm_api::CardDetailFromLocker, errors::ApiErrorResponse> { - migration::validate_card_expiry(&card_details.card_exp_month, &card_details.card_exp_year)?; + if let Some( + // Cards + enums::PaymentMethodType::Credit + | enums::PaymentMethodType::Debit + + // Wallets + | enums::PaymentMethodType::ApplePay + | enums::PaymentMethodType::GooglePay, + ) = payment_method_type { + migration::validate_card_expiry( + &card_details.card_exp_month, + &card_details.card_exp_year, + )?; + } + let card_number = card_details.card_number.clone(); let (card_isin, _last4_digits) = get_card_bin_and_last4_digits_for_masked_card(
2025-09-01T11: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 This PR updates the migration flow around card validation to skip card expiry validation for `PayPal` and `SamsungPay` - these payment methods do not have the linked card's expiry 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 Allows migration of `PayPal` and `SamsungPay` PSP tokens. ## How did you test it? Performing PayPal migration without specifying card details. <details> <summary>Run migration</summary> cURL curl --location --request POST 'http://localhost:8080/payment_methods/migrate-batch' \ --header 'api-key: test_admin' \ --form 'merchant_id="merchant_1756723897"' \ --form 'merchant_connector_ids="mca_0HKNtxio5DvoSuELXkRm"' \ --form 'file=@"sample.csv"' Response [ { "line_number": 40, "payment_method_id": "pm_cy7Xo2En9vh9vqZydXO2", "payment_method": "wallet", "payment_method_type": "paypal", "customer_id": "ef57377bf54cd4ff3bfc26e1e60dbebf", "migration_status": "Success", "card_number_masked": "", "card_migrated": null, "network_token_migrated": true, "connector_mandate_details_migrated": true, "network_transaction_id_migrated": null }, { "line_number": 41, "payment_method_id": "pm_GPmSXeoPxhEtAxSC4uDD", "payment_method": "wallet", "payment_method_type": "paypal", "customer_id": "pet-5cda4ebb25e102e30043f14425915b58", "migration_status": "Success", "card_number_masked": "", "card_migrated": null, "network_token_migrated": true, "connector_mandate_details_migrated": true, "network_transaction_id_migrated": null }, { "line_number": 42, "payment_method_id": "pm_gB4DmNbBNqWsfKru9ZkE", "payment_method": "wallet", "payment_method_type": "paypal", "customer_id": "088e36d3b9ef09533b77d086497a8dc4", "migration_status": "Success", "card_number_masked": "", "card_migrated": null, "network_token_migrated": true, "connector_mandate_details_migrated": true, "network_transaction_id_migrated": 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
v1.116.0
c02d8b9ba9e204fa163b61c419811eaa65fdbcb4
c02d8b9ba9e204fa163b61c419811eaa65fdbcb4
juspay/hyperswitch
juspay__hyperswitch-9139
Bug: feat(revenue_recovery): add support for data migration from merchant csv to Redis
diff --git a/Cargo.lock b/Cargo.lock index 196c7b9820b..82373eafbee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -459,6 +459,7 @@ dependencies = [ "common_enums", "common_types", "common_utils", + "csv", "deserialize_form_style_query_parameter", "error-stack 0.4.1", "euclid", @@ -470,6 +471,7 @@ dependencies = [ "serde", "serde_json", "strum 0.26.3", + "tempfile", "time", "url", "utoipa", diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index cac70d26649..16403f0e25e 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -17,21 +17,23 @@ olap = [] openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"] recon = [] v1 = ["common_utils/v1"] -v2 = ["common_types/v2", "common_utils/v2", "tokenization_v2", "dep:reqwest"] +v2 = ["common_types/v2", "common_utils/v2", "tokenization_v2", "dep:reqwest", "revenue_recovery"] dynamic_routing = [] control_center_theme = ["dep:actix-web", "dep:actix-multipart"] -revenue_recovery = [] +revenue_recovery = ["dep:actix-multipart"] tokenization_v2 = ["common_utils/tokenization_v2"] [dependencies] actix-multipart = { version = "0.6.2", optional = true } actix-web = { version = "4.11.0", optional = true } +csv = "1.3" error-stack = "0.4.1" mime = "0.3.17" reqwest = { version = "0.11.27", optional = true } serde = { version = "1.0.219", features = ["derive"] } serde_json = "1.0.140" strum = { version = "0.26", features = ["derive"] } +tempfile = "3.8" time = { version = "0.3.41", features = ["serde", "serde-well-known", "std"] } url = { version = "2.5.4", features = ["serde"] } utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_order"] } diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 3b343459e9e..16ad859f69a 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -41,6 +41,8 @@ pub mod proxy; pub mod recon; pub mod refunds; pub mod relay; +#[cfg(feature = "v2")] +pub mod revenue_recovery_data_backfill; pub mod routing; pub mod surcharge_decision_configs; pub mod three_ds_decision_rule; diff --git a/crates/api_models/src/revenue_recovery_data_backfill.rs b/crates/api_models/src/revenue_recovery_data_backfill.rs new file mode 100644 index 00000000000..d73ae8a33c3 --- /dev/null +++ b/crates/api_models/src/revenue_recovery_data_backfill.rs @@ -0,0 +1,150 @@ +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 csv::Reader; +use masking::Secret; +use serde::{Deserialize, Serialize}; +use time::Date; + +#[derive(Debug, Deserialize, Serialize)] +pub struct RevenueRecoveryBackfillRequest { + pub bin_number: Option<Secret<String>>, + pub customer_id_resp: String, + pub connector_payment_id: Option<String>, + pub token: Option<Secret<String>>, + pub exp_date: Option<Secret<String>>, + pub card_network: Option<CardNetwork>, + pub payment_method_sub_type: Option<PaymentMethodType>, + pub clean_bank_name: Option<String>, + pub country_name: Option<String>, + pub daily_retry_history: Option<String>, +} + +#[derive(Debug, Serialize)] +pub struct RevenueRecoveryDataBackfillResponse { + pub processed_records: usize, + pub failed_records: usize, +} + +#[derive(Debug, Serialize)] +pub struct CsvParsingResult { + pub records: Vec<RevenueRecoveryBackfillRequest>, + pub failed_records: Vec<CsvParsingError>, +} + +#[derive(Debug, Serialize)] +pub struct CsvParsingError { + pub row_number: usize, + pub error: String, +} + +/// Comprehensive card +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ComprehensiveCardData { + pub card_type: Option<String>, + pub card_exp_month: Option<Secret<String>>, + pub card_exp_year: Option<Secret<String>>, + pub card_network: Option<CardNetwork>, + pub card_issuer: Option<String>, + pub card_issuing_country: Option<String>, + pub daily_retry_history: Option<HashMap<Date, i32>>, +} + +impl ApiEventMetric for RevenueRecoveryDataBackfillResponse { + 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) + } +} + +impl ApiEventMetric for CsvParsingError { + 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), + DatabaseError(String), + RedisError(String), + CsvParsingError(String), + FileProcessingError(String), +} + +#[derive(serde::Deserialize)] +pub struct BackfillQuery { + pub cutoff_time: Option<String>, +} + +impl std::fmt::Display for BackfillError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidCardType(msg) => write!(f, "Invalid card type: {}", msg), + Self::DatabaseError(msg) => write!(f, "Database error: {}", msg), + Self::RedisError(msg) => write!(f, "Redis error: {}", msg), + Self::CsvParsingError(msg) => write!(f, "CSV parsing error: {}", msg), + Self::FileProcessingError(msg) => write!(f, "File processing error: {}", msg), + } + } +} + +impl std::error::Error for BackfillError {} + +impl ResponseError for BackfillError { + fn error_response(&self) -> HttpResponse { + HttpResponse::BadRequest().json(serde_json::json!({ + "error": self.to_string() + })) + } +} + +#[derive(Debug, MultipartForm)] +pub struct RevenueRecoveryDataBackfillForm { + #[multipart(rename = "file")] + pub file: TempFile, +} + +impl RevenueRecoveryDataBackfillForm { + pub fn validate_and_get_records_with_errors(&self) -> Result<CsvParsingResult, BackfillError> { + // Step 1: Open the file + let file = File::open(self.file.file.path()) + .map_err(|error| BackfillError::FileProcessingError(error.to_string()))?; + + let mut csv_reader = Reader::from_reader(BufReader::new(file)); + + // Step 2: Parse CSV into typed records + let mut records = Vec::new(); + let mut failed_records = Vec::new(); + + for (row_index, record_result) in csv_reader + .deserialize::<RevenueRecoveryBackfillRequest>() + .enumerate() + { + match record_result { + Ok(record) => { + records.push(record); + } + Err(err) => { + failed_records.push(CsvParsingError { + row_number: row_index + 2, // +2 because enumerate starts at 0 and CSV has header row + error: err.to_string(), + }); + } + } + } + + Ok(CsvParsingResult { + records, + failed_records, + }) + } +} diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index f7cb256f587..6a7e77f6beb 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -75,4 +75,6 @@ pub mod relay; pub mod revenue_recovery; pub mod chat; +#[cfg(feature = "v2")] +pub mod revenue_recovery_data_backfill; pub mod tokenization; diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 0b7fb4ad062..3bdc822859f 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -1231,8 +1231,17 @@ pub async fn reopen_calculate_workflow_on_payment_failure( // Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id} let process_tracker_id = format!("{runner}_{task}_{}", id.get_string_repr()); - // Set scheduled time to 1 hour from now - let schedule_time = common_utils::date_time::now() + time::Duration::hours(1); + // Set scheduled time to current time + buffer time set in configuration + let schedule_time = common_utils::date_time::now() + + time::Duration::seconds( + state + .conf + .revenue_recovery + .recovery_timestamp + .reopen_workflow_buffer_time_in_seconds, + ); + + let new_retry_count = process.retry_count + 1; // Check if a process tracker entry already exists for this payment intent let existing_entry = db @@ -1244,72 +1253,41 @@ pub async fn reopen_calculate_workflow_on_payment_failure( "Failed to check for existing calculate workflow process tracker entry", )?; - match existing_entry { - Some(existing_process) => { - router_env::logger::error!( - "Found existing CALCULATE_WORKFLOW task with id: {}", - existing_process.id - ); - } - None => { - // No entry exists - create a new one - router_env::logger::info!( - "No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry scheduled for 1 hour from now", + // No entry exists - create a new one + router_env::logger::info!( + "No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry... ", id.get_string_repr() ); - let tag = ["PCR"]; - let task = "CALCULATE_WORKFLOW"; - let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; - - let process_tracker_entry = storage::ProcessTrackerNew::new( - &process_tracker_id, - task, - runner, - tag, - process.tracking_data.clone(), - Some(process.retry_count), - schedule_time, - common_types::consts::API_VERSION, - ) - .change_context(errors::RecoveryError::ProcessTrackerFailure) - .attach_printable( - "Failed to construct calculate workflow process tracker entry", - )?; - - // Insert into process tracker with status New - db.as_scheduler() - .insert_process(process_tracker_entry) - .await - .change_context(errors::RecoveryError::ProcessTrackerFailure) - .attach_printable( - "Failed to enter calculate workflow process_tracker_entry in DB", - )?; - - router_env::logger::info!( - "Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}", - id.get_string_repr() - ); - } - } + let tag = ["PCR"]; + let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; + + let process_tracker_entry = storage::ProcessTrackerNew::new( + &process_tracker_id, + task, + runner, + tag, + process.tracking_data.clone(), + Some(new_retry_count), + schedule_time, + common_types::consts::API_VERSION, + ) + .change_context(errors::RecoveryError::ProcessTrackerFailure) + .attach_printable("Failed to construct calculate workflow process tracker entry")?; - let tracking_data = serde_json::from_value(process.tracking_data.clone()) - .change_context(errors::RecoveryError::ValueNotFound) - .attach_printable("Failed to deserialize the tracking data from process tracker")?; + // Insert into process tracker with status New + db.as_scheduler() + .insert_process(process_tracker_entry) + .await + .change_context(errors::RecoveryError::ProcessTrackerFailure) + .attach_printable( + "Failed to enter calculate workflow process_tracker_entry in DB", + )?; - // Call the existing perform_calculate_workflow function - Box::pin(perform_calculate_workflow( - state, - process, - profile, - merchant_context, - &tracking_data, - revenue_recovery_payment_data, - payment_intent, - )) - .await - .change_context(errors::RecoveryError::ProcessTrackerFailure) - .attach_printable("Failed to perform calculate workflow")?; + router_env::logger::info!( + "Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}", + id.get_string_repr() + ); logger::info!( payment_id = %id.get_string_repr(), @@ -1322,30 +1300,6 @@ pub async fn reopen_calculate_workflow_on_payment_failure( Ok(()) } -/// Create tracking data for the CALCULATE_WORKFLOW -fn create_calculate_workflow_tracking_data( - payment_intent: &PaymentIntent, - revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, -) -> RecoveryResult<storage::revenue_recovery::RevenueRecoveryWorkflowTrackingData> { - let tracking_data = storage::revenue_recovery::RevenueRecoveryWorkflowTrackingData { - merchant_id: revenue_recovery_payment_data - .merchant_account - .get_id() - .clone(), - profile_id: revenue_recovery_payment_data.profile.get_id().clone(), - global_payment_id: payment_intent.id.clone(), - payment_attempt_id: payment_intent - .active_attempt_id - .clone() - .ok_or(storage_impl::errors::RecoveryError::ValueNotFound)?, - billing_mca_id: revenue_recovery_payment_data.billing_mca.get_id().clone(), - revenue_recovery_retry: revenue_recovery_payment_data.retry_algorithm, - invoice_scheduled_time: None, // Will be set by perform_calculate_workflow - }; - - Ok(tracking_data) -} - // TODO: Move these to impl based functions async fn record_back_to_billing_connector( state: &SessionState, diff --git a/crates/router/src/core/revenue_recovery_data_backfill.rs b/crates/router/src/core/revenue_recovery_data_backfill.rs new file mode 100644 index 00000000000..4f32a914849 --- /dev/null +++ b/crates/router/src/core/revenue_recovery_data_backfill.rs @@ -0,0 +1,316 @@ +use std::collections::HashMap; + +use api_models::revenue_recovery_data_backfill::{ + BackfillError, ComprehensiveCardData, RevenueRecoveryBackfillRequest, + RevenueRecoveryDataBackfillResponse, +}; +use common_enums::{CardNetwork, PaymentMethodType}; +use hyperswitch_domain_models::api::ApplicationResponse; +use masking::ExposeInterface; +use router_env::{instrument, logger}; +use time::{format_description, Date}; + +use crate::{ + connection, + core::errors::{self, RouterResult}, + routes::SessionState, + types::{domain, storage}, +}; + +pub async fn revenue_recovery_data_backfill( + state: SessionState, + records: Vec<RevenueRecoveryBackfillRequest>, + cutoff_datetime: Option<time::PrimitiveDateTime>, +) -> RouterResult<ApplicationResponse<RevenueRecoveryDataBackfillResponse>> { + let mut processed_records = 0; + let mut failed_records = 0; + + // Process each record + for record in records { + match process_payment_method_record(&state, &record, cutoff_datetime).await { + Ok(_) => { + processed_records += 1; + logger::info!( + "Successfully processed record with connector customer id: {}", + record.customer_id_resp + ); + } + Err(e) => { + failed_records += 1; + logger::error!( + "Payment method backfill failed: customer_id={}, error={}", + record.customer_id_resp, + e + ); + } + } + } + + let response = RevenueRecoveryDataBackfillResponse { + processed_records, + failed_records, + }; + + logger::info!( + "Revenue recovery data backfill completed - Processed: {}, Failed: {}", + processed_records, + failed_records + ); + + Ok(ApplicationResponse::Json(response)) +} + +async fn process_payment_method_record( + state: &SessionState, + record: &RevenueRecoveryBackfillRequest, + cutoff_datetime: Option<time::PrimitiveDateTime>, +) -> Result<(), BackfillError> { + // Build comprehensive card data from CSV record + let card_data = match build_comprehensive_card_data(record) { + Ok(data) => data, + Err(e) => { + logger::warn!( + "Failed to build card data for connector customer id: {}, error: {}.", + record.customer_id_resp, + e + ); + ComprehensiveCardData { + card_type: Some("card".to_string()), + card_exp_month: None, + card_exp_year: None, + card_network: None, + card_issuer: None, + card_issuing_country: None, + daily_retry_history: None, + } + } + }; + logger::info!( + "Built comprehensive card data - card_type: {:?}, exp_month: {}, exp_year: {}, network: {:?}, issuer: {:?}, country: {:?}, daily_retry_history: {:?}", + card_data.card_type, + card_data.card_exp_month.as_ref().map(|_| "**").unwrap_or("None"), + card_data.card_exp_year.as_ref().map(|_| "**").unwrap_or("None"), + card_data.card_network, + card_data.card_issuer, + card_data.card_issuing_country, + card_data.daily_retry_history + ); + + // Update Redis if token exists and is valid + match record.token.as_ref().map(|token| token.clone().expose()) { + Some(token) if !token.is_empty() => { + logger::info!("Updating Redis for customer: {}", record.customer_id_resp,); + + storage::revenue_recovery_redis_operation:: + RedisTokenManager::update_redis_token_with_comprehensive_card_data( + state, + &record.customer_id_resp, + &token, + &card_data, + cutoff_datetime, + ) + .await + .map_err(|e| { + logger::error!("Redis update failed: {}", e); + BackfillError::RedisError(format!("Token not found in Redis: {}", e)) + })?; + } + _ => { + logger::info!( + "Skipping Redis update - token is missing, empty or 'nan': {:?}", + record.token + ); + } + } + + logger::info!( + "Successfully completed processing for connector customer id: {}", + record.customer_id_resp + ); + Ok(()) +} + +/// Parse daily retry history from CSV +fn parse_daily_retry_history(json_str: Option<&str>) -> Option<HashMap<Date, i32>> { + match json_str { + Some(json) if !json.is_empty() => { + match serde_json::from_str::<HashMap<String, i32>>(json) { + Ok(string_retry_history) => { + // Convert string dates to Date objects + let format = format_description::parse("[year]-[month]-[day]") + .map_err(|e| { + BackfillError::CsvParsingError(format!( + "Invalid date format configuration: {}", + e + )) + }) + .ok()?; + + let mut date_retry_history = HashMap::new(); + + for (date_str, count) in string_retry_history { + match Date::parse(&date_str, &format) { + Ok(date) => { + date_retry_history.insert(date, count); + } + Err(e) => { + logger::warn!( + "Failed to parse date '{}' in daily_retry_history: {}", + date_str, + e + ); + } + } + } + + logger::debug!( + "Successfully parsed daily_retry_history with {} entries", + date_retry_history.len() + ); + Some(date_retry_history) + } + Err(e) => { + logger::warn!("Failed to parse daily_retry_history JSON '{}': {}", json, e); + None + } + } + } + _ => { + logger::debug!("Daily retry history not present or invalid, preserving existing data"); + None + } + } +} + +/// Build comprehensive card data from CSV record +fn build_comprehensive_card_data( + record: &RevenueRecoveryBackfillRequest, +) -> Result<ComprehensiveCardData, BackfillError> { + // Extract card type from request, if not present then update it with 'card' + let card_type = Some(determine_card_type(record.payment_method_sub_type)); + + // Parse expiration date + let (exp_month, exp_year) = parse_expiration_date( + record + .exp_date + .as_ref() + .map(|date| date.clone().expose()) + .as_deref(), + )?; + + let card_exp_month = exp_month.map(masking::Secret::new); + let card_exp_year = exp_year.map(masking::Secret::new); + + // Extract card network + let card_network = record.card_network.clone(); + + // Extract card issuer and issuing country + let card_issuer = record + .clean_bank_name + .as_ref() + .filter(|value| !value.is_empty()) + .cloned(); + + let card_issuing_country = record + .country_name + .as_ref() + .filter(|value| !value.is_empty()) + .cloned(); + + // Parse daily retry history + let daily_retry_history = parse_daily_retry_history(record.daily_retry_history.as_deref()); + + Ok(ComprehensiveCardData { + card_type, + card_exp_month, + card_exp_year, + card_network, + card_issuer, + card_issuing_country, + daily_retry_history, + }) +} + +/// Determine card type with fallback logic: payment_method_sub_type if not present -> "Card" +fn determine_card_type(payment_method_sub_type: Option<PaymentMethodType>) -> String { + match payment_method_sub_type { + Some(card_type_enum) => { + let mapped_type = match card_type_enum { + PaymentMethodType::Credit => "credit".to_string(), + PaymentMethodType::Debit => "debit".to_string(), + PaymentMethodType::Card => "card".to_string(), + // For all other payment method types, default to "card" + _ => "card".to_string(), + }; + logger::debug!( + "Using payment_method_sub_type enum '{:?}' -> '{}'", + card_type_enum, + mapped_type + ); + mapped_type + } + None => { + logger::info!("In CSV payment_method_sub_type not present, defaulting to 'card'"); + "card".to_string() + } + } +} + +/// Parse expiration date +fn parse_expiration_date( + exp_date: Option<&str>, +) -> Result<(Option<String>, Option<String>), BackfillError> { + exp_date + .filter(|date| !date.is_empty()) + .map(|date| { + date.split_once('/') + .ok_or_else(|| { + logger::warn!("Unrecognized expiration date format (MM/YY expected)"); + BackfillError::CsvParsingError( + "Invalid expiration date format: expected MM/YY".to_string(), + ) + }) + .and_then(|(month_part, year_part)| { + let month = month_part.trim(); + let year = year_part.trim(); + + logger::debug!("Split expiration date - parsing month and year"); + + // Validate and parse month + let month_num = month.parse::<u8>().map_err(|_| { + logger::warn!("Failed to parse month component in expiration date"); + BackfillError::CsvParsingError( + "Invalid month format in expiration date".to_string(), + ) + })?; + + if !(1..=12).contains(&month_num) { + logger::warn!("Invalid month value in expiration date (not in range 1-12)"); + return Err(BackfillError::CsvParsingError( + "Invalid month value in expiration date".to_string(), + )); + } + + // Handle year conversion + let final_year = match year.len() { + 4 => &year[2..4], // Convert 4-digit to 2-digit + 2 => year, // Already 2-digit + _ => { + logger::warn!( + "Invalid year length in expiration date (expected 2 or 4 digits)" + ); + return Err(BackfillError::CsvParsingError( + "Invalid year format in expiration date".to_string(), + )); + } + }; + + logger::debug!("Successfully parsed expiration date... ",); + Ok((Some(month.to_string()), Some(final_year.to_string()))) + }) + }) + .unwrap_or_else(|| { + logger::debug!("Empty expiration date, returning None"); + Ok((None, None)) + }) +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 00df2908f44..1d03e90ec30 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -224,7 +224,8 @@ pub fn mk_app( .service(routes::UserDeprecated::server(state.clone())) .service(routes::ProcessTrackerDeprecated::server(state.clone())) .service(routes::ProcessTracker::server(state.clone())) - .service(routes::Gsm::server(state.clone())); + .service(routes::Gsm::server(state.clone())) + .service(routes::RecoveryDataBackfill::server(state.clone())); } } diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index b8fde79e2a1..d49f81d9d99 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -48,6 +48,8 @@ pub mod profiles; #[cfg(feature = "recon")] pub mod recon; pub mod refunds; +#[cfg(feature = "v2")] +pub mod revenue_recovery_data_backfill; #[cfg(feature = "olap")] pub mod routing; pub mod three_ds_decision_rule; @@ -85,8 +87,6 @@ pub use self::app::PaymentMethodSession; pub use self::app::Proxy; #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub use self::app::Recon; -#[cfg(feature = "v2")] -pub use self::app::Tokenization; pub use self::app::{ ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, Cards, Chat, Configs, ConnectorOnboarding, Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm, @@ -99,6 +99,8 @@ pub use self::app::{ pub use self::app::{Blocklist, Organization, Routing, Verify, WebhookEvents}; #[cfg(feature = "payouts")] pub use self::app::{PayoutLink, Payouts}; +#[cfg(feature = "v2")] +pub use self::app::{RecoveryDataBackfill, Tokenization}; #[cfg(all(feature = "stripe", feature = "v1"))] pub use super::compatibility::stripe::StripeApis; #[cfg(feature = "olap")] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d52dc1570ce..9f27455c75c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2970,3 +2970,19 @@ impl ProfileAcquirer { ) } } + +#[cfg(feature = "v2")] +pub struct RecoveryDataBackfill; +#[cfg(feature = "v2")] +impl RecoveryDataBackfill { + pub fn server(state: AppState) -> Scope { + web::scope("/v2/recovery/data-backfill") + .app_data(web::Data::new(state)) + .service( + web::resource("").route( + web::post() + .to(super::revenue_recovery_data_backfill::revenue_recovery_data_backfill), + ), + ) + } +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 28581198d83..76a8839a91d 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -49,6 +49,7 @@ pub enum ApiIdentifier { ProfileAcquirer, ThreeDsDecisionRule, GenericTokenization, + RecoveryDataBackfill, } impl From<Flow> for ApiIdentifier { @@ -380,6 +381,8 @@ impl From<Flow> for ApiIdentifier { Flow::TokenizationCreate | Flow::TokenizationRetrieve | Flow::TokenizationDelete => { Self::GenericTokenization } + + Flow::RecoveryDataBackfill => Self::RecoveryDataBackfill, } } } diff --git a/crates/router/src/routes/revenue_recovery_data_backfill.rs b/crates/router/src/routes/revenue_recovery_data_backfill.rs new file mode 100644 index 00000000000..340d9a084bf --- /dev/null +++ b/crates/router/src/routes/revenue_recovery_data_backfill.rs @@ -0,0 +1,67 @@ +use actix_multipart::form::MultipartForm; +use actix_web::{web, HttpRequest, HttpResponse}; +use api_models::revenue_recovery_data_backfill::{BackfillQuery, RevenueRecoveryDataBackfillForm}; +use router_env::{instrument, tracing, Flow}; + +use crate::{ + core::{api_locking, revenue_recovery_data_backfill}, + routes::AppState, + services::{api, authentication as auth}, + types::domain, +}; + +#[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))] +pub async fn revenue_recovery_data_backfill( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<BackfillQuery>, + MultipartForm(form): MultipartForm<RevenueRecoveryDataBackfillForm>, +) -> HttpResponse { + let flow = Flow::RecoveryDataBackfill; + + // Parse cutoff_time from query parameter + let cutoff_datetime = match query + .cutoff_time + .as_ref() + .map(|time_str| { + time::PrimitiveDateTime::parse( + time_str, + &time::format_description::well_known::Iso8601::DEFAULT, + ) + }) + .transpose() + { + Ok(datetime) => datetime, + Err(err) => { + return HttpResponse::BadRequest().json(serde_json::json!({ + "error": format!("Invalid datetime format: {}. Use ISO8601: 2024-01-15T10:30:00", err) + })); + } + }; + + let records = match form.validate_and_get_records_with_errors() { + Ok(records) => records, + Err(e) => { + return HttpResponse::BadRequest().json(serde_json::json!({ + "error": e.to_string() + })); + } + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + records, + |state, _, records, _req| { + revenue_recovery_data_backfill::revenue_recovery_data_backfill( + state, + records.records, + cutoff_datetime, + ) + }, + &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 f083e8bbbed..e89db0d1aa8 100644 --- a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs +++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs @@ -1,9 +1,10 @@ use std::collections::HashMap; +use api_models; use common_enums::enums::CardNetwork; use common_utils::{date_time, errors::CustomResult, id_type}; use error_stack::ResultExt; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use redis_interface::{DelReply, SetnxReply}; use router_env::{instrument, logger, tracing}; use serde::{Deserialize, Serialize}; @@ -214,7 +215,6 @@ impl RedisTokenManager { .await .change_context(get_hash_err)?; - // build the result map using iterator adapters (explicit match preserved for logging) let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> = payment_processor_tokens .into_iter() @@ -754,4 +754,93 @@ impl RedisTokenManager { Ok(token) } + + /// 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, + cutoff_datetime: Option<PrimitiveDateTime>, + ) -> CustomResult<(), errors::StorageError> { + // Get existing token data + let mut token_map = + Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?; + + // Find the token to update + let existing_token = token_map.get_mut(token).ok_or_else(|| { + tracing::warn!( + customer_id = customer_id, + "Token not found in parsed Redis data - may be corrupted or missing for " + ); + error_stack::Report::new(errors::StorageError::ValueNotFound( + "Token not found in Redis".to_string(), + )) + })?; + + // Update the token details with new card data + card_data.card_type.as_ref().map(|card_type| { + existing_token.payment_processor_token_details.card_type = Some(card_type.clone()) + }); + + card_data.card_exp_month.as_ref().map(|exp_month| { + existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone()) + }); + + card_data.card_exp_year.as_ref().map(|exp_year| { + existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone()) + }); + + card_data.card_network.as_ref().map(|card_network| { + existing_token.payment_processor_token_details.card_network = Some(card_network.clone()) + }); + + card_data.card_issuer.as_ref().map(|card_issuer| { + existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone()) + }); + + // Update daily retry history if provided + card_data + .daily_retry_history + .as_ref() + .map(|retry_history| existing_token.daily_retry_history = retry_history.clone()); + + // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None + // If no scheduled_at value exists, leave it as None + existing_token.scheduled_at = existing_token + .scheduled_at + .and_then(|existing_scheduled_at| { + cutoff_datetime + .map(|cutoff| { + if existing_scheduled_at < cutoff { + tracing::info!( + customer_id = customer_id, + existing_scheduled_at = %existing_scheduled_at, + cutoff_datetime = %cutoff, + "Set scheduled_at to None because existing time is before cutoff time" + ); + None + } else { + Some(existing_scheduled_at) + } + }) + .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value + }); + + // Save the updated token map back to Redis + Self::update_or_add_connector_customer_payment_processor_tokens( + state, + customer_id, + token_map, + ) + .await?; + + tracing::info!( + customer_id = customer_id, + "Updated Redis token data with comprehensive card data using struct" + ); + + Ok(()) + } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index f5359d84010..0f03e26a5c8 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -652,6 +652,8 @@ pub enum Flow { RecoveryPaymentsCreate, /// Tokenization delete flow TokenizationDelete, + /// Payment method data backfill flow + RecoveryDataBackfill, /// Gift card balance check flow GiftCardBalanceCheck, }
2025-09-01T20:39:10Z
## 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 --> The format of csv:- <img width="1720" height="33" alt="Screenshot 2025-09-02 at 13 57 36" src="https://github.com/user-attachments/assets/d8e57dc8-1707-49b2-a27f-79888ee5a8b9" /> <img width="1711" height="32" alt="Screenshot 2025-09-02 at 13 57 54" src="https://github.com/user-attachments/assets/222bbb5a-0c0a-4920-ad8e-d6d931be86ad" /> <img width="1644" height="28" alt="Screenshot 2025-09-02 at 13 58 07" src="https://github.com/user-attachments/assets/5e86aa7b-e34e-40fb-bbff-742d7316d8d5" /> here `CustomerReq_ID` is the customer token and `Token` is the payment token which is used as an identifier in Redis for tokens, ("customer:{}:tokens", customer_id) is used to get token and `Token` is used to find the field which we need to update. So, we are parsing the csv and getting the valid records and building a request per record `RevenueRecoveryBackfillRequest`, from this request we are fetching the data like expiry month, year, card type, card issuer, card network, any of these fields are `null`, we are updating them from the request. Complexity:- for each valid record we are doing two Redis call, one for get and another for set. ### 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). --> For Revenue recovery service, we are storing data in Redis with format ``` HGETALL customer:fake_customer123:tokens 1) "fake_token123" 2) "{\"payment_processor_token_details\":{\"payment_processor_token\":\"fake_token123\",\"expiry_month\":\"08\",\"expiry_year\":\"26\",\"card_issuer\":\"Green Dot Bank Dba Bonneville Bank\",\"last_four_digits\":null,\"card_network\":\"Visa\",\"card_type\":\"debit\"},\"inserted_by_attempt_id\":\"12345_att_fake_entry123\",\"error_code\":\"insufficient_funds\",\"daily_retry_history\":{\"2024-05-29\":1},\"scheduled_at\":null}" ``` in last data migration `card_type` was populated as `null`, but for `Smart` retry logic we need fields like `card_type`, `card_issuer`, `card_network`. So, inorder to work with `Smart` retry we need to backfill `card_type` data from merchant csv. ## 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 'http://localhost:8080/recovery/data-backfill' \ --header 'Authorization: api_key =' \ --header 'x-profile-id: pro_PljcGfk8IckJFT1WdFsn' \ --header 'api-key:' \ --form 'file=@"/Users/aditya.c/Downloads/_first_100_rows.csv"' ``` Router log:- <img width="1064" height="747" alt="Screenshot 2025-09-02 at 13 47 22" src="https://github.com/user-attachments/assets/723b12f4-15bf-43ea-807b-968d5e40370a" /> cURL with query param for updating scheduled at time ``` curl --location 'http://localhost:8080/v2/recovery/data-backfill?cutoff_time=2025-09-17T10%3A30%3A00' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'x-profile-id: pro_4xOQlxvKwZbLUx8ThJXJ' \ --form 'file=@"/Users/aditya.c/Downloads/sample_merged_data (1).csv"' ``` Router log:- <img width="1044" height="369" alt="Screenshot 2025-09-17 at 17 06 56" src="https://github.com/user-attachments/assets/8f31960e-b560-4a4b-a651-831899500971" /> Redis-cli log(updating scheduledat to null if cut-off time is greater than scheduled at time):- <img width="1040" height="160" alt="Screenshot 2025-09-17 at 17 10 31" src="https://github.com/user-attachments/assets/f144357b-e693-4686-8df4-6b28b06208eb" /> ## 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
v1.117.0
fde51e17d44e9feea3cc5866e0692a5c9adb1975
fde51e17d44e9feea3cc5866e0692a5c9adb1975
juspay/hyperswitch
juspay__hyperswitch-9120
Bug: [BUG] Setup fail : migration_runner exits with code 1 during standalone setup ### Bug Description While setting up Hyperswitch locally using the scripts/setup.sh script, the setup consistently fails during the migration_runner step. The database (pg) and Redis services start successfully and report as Healthy, but the migration_runner container exits with code 1, causing the setup process to stop. This blocks local development/testing on Windows environments. Below is the ss of error : <img width="930" height="942" alt="Image" src="https://github.com/user-attachments/assets/1578a5d6-323b-4858-8599-fb2cac588804" /> ### Expected Behavior All the containers should have been started and compiled successfully ### Actual Behavior The error mentioned above occurred ### Steps To Reproduce Clone the Repo and run `scripts/setup.sh` ### Context For The Bug This is my first time setting up a project this big locally , so i might have miss something , or this might be an actual bug . Either way , i request some help in this matter ### Environment OS : Windows ### 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/.gitattributes b/.gitattributes index 176a458f94e..d7ed342927a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ * text=auto +*.patch text eol=lf \ No newline at end of file
2025-09-10T06:06:07Z
## 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 adds the following rule to `.gitattributes` to ensure `.patch` files always use LF line endings, regardless of developer OS: ```gitattributes *.patch text eol=lf ``` This rule overrides Windows’ default `core.autocrlf` behavior and prevents errors during migration when Diesel’s patch parser encounters CRLF line endings. **Additionally**: For developers who have already cloned the repository and whose `.patch` files may still have CRLF endings, a workaround : ```bash git checkout -- crates/diesel_models/drop_id.patch ``` This ensures the `.patch` file is re-checked-out with the correct LF line endings, without requiring a full reclone. Closes: #9120 ### 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). --> Diesel’s migration runner fails on Windows because CRLF line endings corrupt the patch file format (e.g., `diff --git a/file.rs b/file.rs\r\n`), causing “invalid char in unquoted filename” parsing errors. By forcing LF endings for patch files via `.gitattributes`, this PR ensures cross-platform consistency and prevents migration failures. Issue: #9120 ## 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)? --> * Applied the change on a Windows environment with `core.autocrlf=true` and confirmed `.patch` files now use `\n` instead of `\r\n`. * Ran `scripts/setup.sh` and verified that the migration runner no longer exits with code 1. * Provided the `git checkout -- <patch>` fix to confirm re-checkout resets line endings to LF without recloning. ## 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 ### Additional Context **CRLF vs LF Line Endings Explained** * **LF (Line Feed)** – used by Unix/Linux/macOS; represented by `\n` * **CRLF (Carriage Return + Line Feed)** – used by Windows; represented by `\r\n` Git’s `core.autocrlf=true` (Windows default) can introduce CRLF line endings on checkout and convert them back to LF on commit. Explicit `.gitattributes` configuration (`*.patch text eol=lf`) guarantees LF regardless of platform, preventing CRLF-related parsing issues. ---
v1.117.0
2edaa6e0578ae8cb6e4b44cc516b8c342262c082
2edaa6e0578ae8cb6e4b44cc516b8c342262c082